text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { DeploymentOperations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ResourceManagementClient } from "../resourceManagementClient"; import { DeploymentOperation, DeploymentOperationsListAtScopeNextOptionalParams, DeploymentOperationsListAtScopeOptionalParams, DeploymentOperationsListAtTenantScopeNextOptionalParams, DeploymentOperationsListAtTenantScopeOptionalParams, DeploymentOperationsListAtManagementGroupScopeNextOptionalParams, DeploymentOperationsListAtManagementGroupScopeOptionalParams, DeploymentOperationsListAtSubscriptionScopeNextOptionalParams, DeploymentOperationsListAtSubscriptionScopeOptionalParams, DeploymentOperationsListNextOptionalParams, DeploymentOperationsListOptionalParams, DeploymentOperationsGetAtScopeOptionalParams, DeploymentOperationsGetAtScopeResponse, DeploymentOperationsListAtScopeResponse, DeploymentOperationsGetAtTenantScopeOptionalParams, DeploymentOperationsGetAtTenantScopeResponse, DeploymentOperationsListAtTenantScopeResponse, DeploymentOperationsGetAtManagementGroupScopeOptionalParams, DeploymentOperationsGetAtManagementGroupScopeResponse, DeploymentOperationsListAtManagementGroupScopeResponse, DeploymentOperationsGetAtSubscriptionScopeOptionalParams, DeploymentOperationsGetAtSubscriptionScopeResponse, DeploymentOperationsListAtSubscriptionScopeResponse, DeploymentOperationsGetOptionalParams, DeploymentOperationsGetResponse, DeploymentOperationsListResponse, DeploymentOperationsListAtScopeNextResponse, DeploymentOperationsListAtTenantScopeNextResponse, DeploymentOperationsListAtManagementGroupScopeNextResponse, DeploymentOperationsListAtSubscriptionScopeNextResponse, DeploymentOperationsListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing DeploymentOperations operations. */ export class DeploymentOperationsImpl implements DeploymentOperations { private readonly client: ResourceManagementClient; /** * Initialize a new instance of the class DeploymentOperations class. * @param client Reference to the service client */ constructor(client: ResourceManagementClient) { this.client = client; } /** * Gets all deployments operations for a deployment. * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param options The options parameters. */ public listAtScope( scope: string, deploymentName: string, options?: DeploymentOperationsListAtScopeOptionalParams ): PagedAsyncIterableIterator<DeploymentOperation> { const iter = this.listAtScopePagingAll(scope, deploymentName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAtScopePagingPage(scope, deploymentName, options); } }; } private async *listAtScopePagingPage( scope: string, deploymentName: string, options?: DeploymentOperationsListAtScopeOptionalParams ): AsyncIterableIterator<DeploymentOperation[]> { let result = await this._listAtScope(scope, deploymentName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAtScopeNext( scope, deploymentName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAtScopePagingAll( scope: string, deploymentName: string, options?: DeploymentOperationsListAtScopeOptionalParams ): AsyncIterableIterator<DeploymentOperation> { for await (const page of this.listAtScopePagingPage( scope, deploymentName, options )) { yield* page; } } /** * Gets all deployments operations for a deployment. * @param deploymentName The name of the deployment. * @param options The options parameters. */ public listAtTenantScope( deploymentName: string, options?: DeploymentOperationsListAtTenantScopeOptionalParams ): PagedAsyncIterableIterator<DeploymentOperation> { const iter = this.listAtTenantScopePagingAll(deploymentName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAtTenantScopePagingPage(deploymentName, options); } }; } private async *listAtTenantScopePagingPage( deploymentName: string, options?: DeploymentOperationsListAtTenantScopeOptionalParams ): AsyncIterableIterator<DeploymentOperation[]> { let result = await this._listAtTenantScope(deploymentName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAtTenantScopeNext( deploymentName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAtTenantScopePagingAll( deploymentName: string, options?: DeploymentOperationsListAtTenantScopeOptionalParams ): AsyncIterableIterator<DeploymentOperation> { for await (const page of this.listAtTenantScopePagingPage( deploymentName, options )) { yield* page; } } /** * Gets all deployments operations for a deployment. * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param options The options parameters. */ public listAtManagementGroupScope( groupId: string, deploymentName: string, options?: DeploymentOperationsListAtManagementGroupScopeOptionalParams ): PagedAsyncIterableIterator<DeploymentOperation> { const iter = this.listAtManagementGroupScopePagingAll( groupId, deploymentName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAtManagementGroupScopePagingPage( groupId, deploymentName, options ); } }; } private async *listAtManagementGroupScopePagingPage( groupId: string, deploymentName: string, options?: DeploymentOperationsListAtManagementGroupScopeOptionalParams ): AsyncIterableIterator<DeploymentOperation[]> { let result = await this._listAtManagementGroupScope( groupId, deploymentName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAtManagementGroupScopeNext( groupId, deploymentName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAtManagementGroupScopePagingAll( groupId: string, deploymentName: string, options?: DeploymentOperationsListAtManagementGroupScopeOptionalParams ): AsyncIterableIterator<DeploymentOperation> { for await (const page of this.listAtManagementGroupScopePagingPage( groupId, deploymentName, options )) { yield* page; } } /** * Gets all deployments operations for a deployment. * @param deploymentName The name of the deployment. * @param options The options parameters. */ public listAtSubscriptionScope( deploymentName: string, options?: DeploymentOperationsListAtSubscriptionScopeOptionalParams ): PagedAsyncIterableIterator<DeploymentOperation> { const iter = this.listAtSubscriptionScopePagingAll(deploymentName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAtSubscriptionScopePagingPage(deploymentName, options); } }; } private async *listAtSubscriptionScopePagingPage( deploymentName: string, options?: DeploymentOperationsListAtSubscriptionScopeOptionalParams ): AsyncIterableIterator<DeploymentOperation[]> { let result = await this._listAtSubscriptionScope(deploymentName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAtSubscriptionScopeNext( deploymentName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAtSubscriptionScopePagingAll( deploymentName: string, options?: DeploymentOperationsListAtSubscriptionScopeOptionalParams ): AsyncIterableIterator<DeploymentOperation> { for await (const page of this.listAtSubscriptionScopePagingPage( deploymentName, options )) { yield* page; } } /** * Gets all deployments operations for a deployment. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param options The options parameters. */ public list( resourceGroupName: string, deploymentName: string, options?: DeploymentOperationsListOptionalParams ): PagedAsyncIterableIterator<DeploymentOperation> { const iter = this.listPagingAll(resourceGroupName, deploymentName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, deploymentName, options); } }; } private async *listPagingPage( resourceGroupName: string, deploymentName: string, options?: DeploymentOperationsListOptionalParams ): AsyncIterableIterator<DeploymentOperation[]> { let result = await this._list(resourceGroupName, deploymentName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, deploymentName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, deploymentName: string, options?: DeploymentOperationsListOptionalParams ): AsyncIterableIterator<DeploymentOperation> { for await (const page of this.listPagingPage( resourceGroupName, deploymentName, options )) { yield* page; } } /** * Gets a deployments operation. * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The options parameters. */ getAtScope( scope: string, deploymentName: string, operationId: string, options?: DeploymentOperationsGetAtScopeOptionalParams ): Promise<DeploymentOperationsGetAtScopeResponse> { return this.client.sendOperationRequest( { scope, deploymentName, operationId, options }, getAtScopeOperationSpec ); } /** * Gets all deployments operations for a deployment. * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param options The options parameters. */ private _listAtScope( scope: string, deploymentName: string, options?: DeploymentOperationsListAtScopeOptionalParams ): Promise<DeploymentOperationsListAtScopeResponse> { return this.client.sendOperationRequest( { scope, deploymentName, options }, listAtScopeOperationSpec ); } /** * Gets a deployments operation. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The options parameters. */ getAtTenantScope( deploymentName: string, operationId: string, options?: DeploymentOperationsGetAtTenantScopeOptionalParams ): Promise<DeploymentOperationsGetAtTenantScopeResponse> { return this.client.sendOperationRequest( { deploymentName, operationId, options }, getAtTenantScopeOperationSpec ); } /** * Gets all deployments operations for a deployment. * @param deploymentName The name of the deployment. * @param options The options parameters. */ private _listAtTenantScope( deploymentName: string, options?: DeploymentOperationsListAtTenantScopeOptionalParams ): Promise<DeploymentOperationsListAtTenantScopeResponse> { return this.client.sendOperationRequest( { deploymentName, options }, listAtTenantScopeOperationSpec ); } /** * Gets a deployments operation. * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The options parameters. */ getAtManagementGroupScope( groupId: string, deploymentName: string, operationId: string, options?: DeploymentOperationsGetAtManagementGroupScopeOptionalParams ): Promise<DeploymentOperationsGetAtManagementGroupScopeResponse> { return this.client.sendOperationRequest( { groupId, deploymentName, operationId, options }, getAtManagementGroupScopeOperationSpec ); } /** * Gets all deployments operations for a deployment. * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param options The options parameters. */ private _listAtManagementGroupScope( groupId: string, deploymentName: string, options?: DeploymentOperationsListAtManagementGroupScopeOptionalParams ): Promise<DeploymentOperationsListAtManagementGroupScopeResponse> { return this.client.sendOperationRequest( { groupId, deploymentName, options }, listAtManagementGroupScopeOperationSpec ); } /** * Gets a deployments operation. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The options parameters. */ getAtSubscriptionScope( deploymentName: string, operationId: string, options?: DeploymentOperationsGetAtSubscriptionScopeOptionalParams ): Promise<DeploymentOperationsGetAtSubscriptionScopeResponse> { return this.client.sendOperationRequest( { deploymentName, operationId, options }, getAtSubscriptionScopeOperationSpec ); } /** * Gets all deployments operations for a deployment. * @param deploymentName The name of the deployment. * @param options The options parameters. */ private _listAtSubscriptionScope( deploymentName: string, options?: DeploymentOperationsListAtSubscriptionScopeOptionalParams ): Promise<DeploymentOperationsListAtSubscriptionScopeResponse> { return this.client.sendOperationRequest( { deploymentName, options }, listAtSubscriptionScopeOperationSpec ); } /** * Gets a deployments operation. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The options parameters. */ get( resourceGroupName: string, deploymentName: string, operationId: string, options?: DeploymentOperationsGetOptionalParams ): Promise<DeploymentOperationsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, deploymentName, operationId, options }, getOperationSpec ); } /** * Gets all deployments operations for a deployment. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param options The options parameters. */ private _list( resourceGroupName: string, deploymentName: string, options?: DeploymentOperationsListOptionalParams ): Promise<DeploymentOperationsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, deploymentName, options }, listOperationSpec ); } /** * ListAtScopeNext * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param nextLink The nextLink from the previous successful call to the ListAtScope method. * @param options The options parameters. */ private _listAtScopeNext( scope: string, deploymentName: string, nextLink: string, options?: DeploymentOperationsListAtScopeNextOptionalParams ): Promise<DeploymentOperationsListAtScopeNextResponse> { return this.client.sendOperationRequest( { scope, deploymentName, nextLink, options }, listAtScopeNextOperationSpec ); } /** * ListAtTenantScopeNext * @param deploymentName The name of the deployment. * @param nextLink The nextLink from the previous successful call to the ListAtTenantScope method. * @param options The options parameters. */ private _listAtTenantScopeNext( deploymentName: string, nextLink: string, options?: DeploymentOperationsListAtTenantScopeNextOptionalParams ): Promise<DeploymentOperationsListAtTenantScopeNextResponse> { return this.client.sendOperationRequest( { deploymentName, nextLink, options }, listAtTenantScopeNextOperationSpec ); } /** * ListAtManagementGroupScopeNext * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param nextLink The nextLink from the previous successful call to the ListAtManagementGroupScope * method. * @param options The options parameters. */ private _listAtManagementGroupScopeNext( groupId: string, deploymentName: string, nextLink: string, options?: DeploymentOperationsListAtManagementGroupScopeNextOptionalParams ): Promise<DeploymentOperationsListAtManagementGroupScopeNextResponse> { return this.client.sendOperationRequest( { groupId, deploymentName, nextLink, options }, listAtManagementGroupScopeNextOperationSpec ); } /** * ListAtSubscriptionScopeNext * @param deploymentName The name of the deployment. * @param nextLink The nextLink from the previous successful call to the ListAtSubscriptionScope * method. * @param options The options parameters. */ private _listAtSubscriptionScopeNext( deploymentName: string, nextLink: string, options?: DeploymentOperationsListAtSubscriptionScopeNextOptionalParams ): Promise<DeploymentOperationsListAtSubscriptionScopeNextResponse> { return this.client.sendOperationRequest( { deploymentName, nextLink, options }, listAtSubscriptionScopeNextOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, deploymentName: string, nextLink: string, options?: DeploymentOperationsListNextOptionalParams ): Promise<DeploymentOperationsListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, deploymentName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const getAtScopeOperationSpec: coreClient.OperationSpec = { path: "/{scope}/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.scope, Parameters.deploymentName, Parameters.operationId ], headerParameters: [Parameters.accept], serializer }; const listAtScopeOperationSpec: coreClient.OperationSpec = { path: "/{scope}/providers/Microsoft.Resources/deployments/{deploymentName}/operations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.scope, Parameters.deploymentName ], headerParameters: [Parameters.accept], serializer }; const getAtTenantScopeOperationSpec: coreClient.OperationSpec = { path: "/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.deploymentName, Parameters.operationId ], headerParameters: [Parameters.accept], serializer }; const listAtTenantScopeOperationSpec: coreClient.OperationSpec = { path: "/providers/Microsoft.Resources/deployments/{deploymentName}/operations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [Parameters.$host, Parameters.deploymentName], headerParameters: [Parameters.accept], serializer }; const getAtManagementGroupScopeOperationSpec: coreClient.OperationSpec = { path: "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.deploymentName, Parameters.groupId, Parameters.operationId ], headerParameters: [Parameters.accept], serializer }; const listAtManagementGroupScopeOperationSpec: coreClient.OperationSpec = { path: "/providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.deploymentName, Parameters.groupId ], headerParameters: [Parameters.accept], serializer }; const getAtSubscriptionScopeOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.deploymentName, Parameters.subscriptionId, Parameters.operationId ], headerParameters: [Parameters.accept], serializer }; const listAtSubscriptionScopeOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.deploymentName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations/{operationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.deploymentName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.operationId ], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.deploymentName, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const listAtScopeNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.scope, Parameters.deploymentName ], headerParameters: [Parameters.accept], serializer }; const listAtTenantScopeNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.deploymentName ], headerParameters: [Parameters.accept], serializer }; const listAtManagementGroupScopeNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.deploymentName, Parameters.groupId ], headerParameters: [Parameters.accept], serializer }; const listAtSubscriptionScopeNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.deploymentName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.top], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.deploymentName, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { Cartesian2 } from '../angular-cesium/models/cartesian2'; import { Cartesian3 } from '../angular-cesium/models/cartesian3'; import { GeoUtilsService } from '../angular-cesium/services/geo-utils/geo-utils.service'; import * as h337 from 'heatmap.js/build/heatmap.js'; import { Injectable } from '@angular/core'; // Consider moving to a different package. if (!h337) { throw new Error('must install heatmap.js. please do npm -i heatmap.js '); } export interface Rectangle { west: number; south: number; east: number; north: number; } /** * x: lon * y: lat * value: point value */ export interface HeatPointDataPoint { x: number; y: number; value: number; } /** * min: the minimum allowed value for the data values * max: the maximum allowed value for the data values * heatPointsData: an array of data points in WGS84 coordinates and values like { x:lon, y:lat, value) */ export interface HeatmapDataSet { min?: number; max?: number; heatPointsData: HeatPointDataPoint[]; } /** * a heatmap.js options object (see http://www.patrick-wied.at/static/heatmapjs/docs.html#h337-create) */ export interface HeatMapOptions { [propName: string]: any; gradient?: any; radius?: number; opacity?: number; maxOpacity?: number; minOpacity?: number; blur?: any; } /** * Create heatmap material (Cesium.ImageMaterialProperty with heatmap as the image) * works with http://www.patrick-wied.at/static/heatmapjs. must do npm -i heatmap.js * usage: * ``` * const mCreator = new CesiumHeatMapMaterialCreator(); const containingRect = CesiumHeatMapMaterialCreator.calcCircleContainingRect(this.circleCenter, this.circleRadius); const userHeatmapOptions = { radius : 2000, minOpacity : 0, maxOpacity : 0.9, } as any; this.circleHeatMapMaterial = mCreator.create(containingRect, { heatPointsData : [ { x : -100.0, y : 24.0, value : 95 } ], min : 0, max : 100, }, userHeatmapOptions); * ``` * * inspired by https://github.com/danwild/CesiumHeatmap */ @Injectable() export class CesiumHeatMapMaterialCreator { private static containerCanvasCounter = 0; heatmapOptionsDefaults = { minCanvasSize: 700, // minimum size (in pixels) for the heatmap canvas maxCanvasSize: 2000, // maximum size (in pixels) for the heatmap canvas radiusFactor: 60, // data point size factor used if no radius is given // (the greater of height and width divided by this number yields the used radius) spacingFactor: 1, // extra space around the borders (point radius multiplied by this number yields the spacing) maxOpacity: 0.8, // the maximum opacity used if not given in the heatmap options object minOpacity: 0.1, // the minimum opacity used if not given in the heatmap options object blur: 0.85, // the blur used if not given in the heatmap options object gradient: { // the gradient used if not given in the heatmap options object '.3': 'blue', '.65': 'yellow', '.8': 'orange', '.95': 'red' }, }; WMP = new Cesium.WebMercatorProjection(); _spacing: number; width: number; height: number; _mbounds: any; bounds: any; _factor: number; _rectangle: Rectangle; heatmap: any; _xoffset: any; _yoffset: any; /** * * @param center - Cartesian3 * @param radius - Meters */ static calcCircleContainingRect(center: Cartesian3, radius: number) { return CesiumHeatMapMaterialCreator.calcEllipseContainingRect(center, radius, radius); } /** * * @param center - Cartesian3 * @param semiMinorAxis - meters * @param semiMajorAxis - meters */ static calcEllipseContainingRect(center: Cartesian3, semiMajorAxis: number, semiMinorAxis: number) { const top = GeoUtilsService.pointByLocationDistanceAndAzimuth( center, semiMinorAxis, 0, true ); const right = GeoUtilsService.pointByLocationDistanceAndAzimuth( center, semiMajorAxis, Math.PI / 2, true ); const bottom = GeoUtilsService.pointByLocationDistanceAndAzimuth( center, semiMajorAxis, Math.PI, true ); const left = GeoUtilsService.pointByLocationDistanceAndAzimuth( center, semiMajorAxis, Math.PI * 1.5, true ); const ellipsePoints = [top, right, bottom, left]; return Cesium.Rectangle.fromCartesianArray(ellipsePoints); } /** * * @param points Cartesian3 */ static calculateContainingRectFromPoints(points: Cartesian3[]) { return Cesium.Rectangle.fromCartesianArray(points); } /** Set an array of heatmap locations * * min: the minimum allowed value for the data values * max: the maximum allowed value for the data values * data: an array of data points in heatmap coordinates and values like {x, y, value} */ setData(min: any, max: any, data: any) { if (data && data.length > 0 && min !== null && min !== false && max !== null && max !== false) { this.heatmap.setData({ min: min, max: max, data: data }); return true; } return false; } /** Set an array of WGS84 locations * * min: the minimum allowed value for the data values * max: the maximum allowed value for the data values * data: an array of data points in WGS84 coordinates and values like { x:lon, y:lat, value } */ private setWGS84Data(min: any, max: any, data: any) { if (data && data.length > 0 && min !== null && min !== false && max !== null && max !== false) { const convdata = []; for (let i = 0; i < data.length; i++) { const gp = data[i]; const hp = this.wgs84PointToHeatmapPoint(gp); if (gp.value || gp.value === 0) { hp.value = gp.value; } convdata.push(hp); } return this.setData(min, max, convdata); } return false; } /** Convert a mercator location to the corresponding heatmap location * * p: a WGS84 location like {x: lon, y:lat} */ private mercatorPointToHeatmapPoint(p: Cartesian2) { const pn: any = {}; pn.x = Math.round((p.x - this._xoffset) / this._factor + this._spacing); pn.y = Math.round((p.y - this._yoffset) / this._factor + this._spacing); pn.y = this.height - pn.y; return pn; } /** Convert a WGS84 location to the corresponding heatmap location * * p: a WGS84 location like {x:lon, y:lat} */ private wgs84PointToHeatmapPoint = function (p: Cartesian2) { return this.mercatorPointToHeatmapPoint(this.wgs84ToMercator(p)); }; private createContainer(height: number, width: number) { const id = 'heatmap' + CesiumHeatMapMaterialCreator.containerCanvasCounter++; const container = document.createElement('div'); container.setAttribute('id', id); container.setAttribute('style', 'width: ' + width + 'px; height: ' + height + 'px; margin: 0px; display: none;'); document.body.appendChild(container); return {container, id}; } /** Convert a WGS84 location into a mercator location * * p: the WGS84 location like {x: lon, y: lat} */ private wgs84ToMercator(p: Cartesian2) { const mp = this.WMP.project(Cesium.Cartographic.fromDegrees(p.x, p.y)); return { x: mp.x, y: mp.y }; } private rad2deg = function (r: number) { const d = r / (Math.PI / 180.0); return d; }; /** Convert a WGS84 bounding box into a mercator bounding box* * bb: the WGS84 bounding box like {north, east, south, west} */ private wgs84ToMercatorBB(bb: any) { // TODO validate rad or deg const sw = this.WMP.project(Cesium.Cartographic.fromRadians(bb.west, bb.south)); const ne = this.WMP.project(Cesium.Cartographic.fromRadians(bb.east, bb.north)); return { north: ne.y, east: ne.x, south: sw.y, west: sw.x }; } /** Convert a mercator bounding box into a WGS84 bounding box * * bb: the mercator bounding box like {north, east, south, west} */ private mercatorToWgs84BB(bb: any) { const sw = this.WMP.unproject(new Cesium.Cartesian3(bb.west, bb.south)); const ne = this.WMP.unproject(new Cesium.Cartesian3(bb.east, bb.north)); return { north: this.rad2deg(ne.latitude), east: this.rad2deg(ne.longitude), south: this.rad2deg(sw.latitude), west: this.rad2deg(sw.longitude) }; } private setWidthAndHeight(mbb: any) { this.width = ((mbb.east > 0 && mbb.west < 0) ? mbb.east + Math.abs(mbb.west) : Math.abs(mbb.east - mbb.west)); this.height = ((mbb.north > 0 && mbb.south < 0) ? mbb.north + Math.abs(mbb.south) : Math.abs(mbb.north - mbb.south)); this._factor = 1; if (this.width > this.height && this.width > this.heatmapOptionsDefaults.maxCanvasSize) { this._factor = this.width / this.heatmapOptionsDefaults.maxCanvasSize; if (this.height / this._factor < this.heatmapOptionsDefaults.minCanvasSize) { this._factor = this.height / this.heatmapOptionsDefaults.minCanvasSize; } } else if (this.height > this.width && this.height > this.heatmapOptionsDefaults.maxCanvasSize) { this._factor = this.height / this.heatmapOptionsDefaults.maxCanvasSize; if (this.width / this._factor < this.heatmapOptionsDefaults.minCanvasSize) { this._factor = this.width / this.heatmapOptionsDefaults.minCanvasSize; } } else if (this.width < this.height && this.width < this.heatmapOptionsDefaults.minCanvasSize) { this._factor = this.width / this.heatmapOptionsDefaults.minCanvasSize; if (this.height / this._factor > this.heatmapOptionsDefaults.maxCanvasSize) { this._factor = this.height / this.heatmapOptionsDefaults.maxCanvasSize; } } else if (this.height < this.width && this.height < this.heatmapOptionsDefaults.minCanvasSize) { this._factor = this.height / this.heatmapOptionsDefaults.minCanvasSize; if (this.width / this._factor > this.heatmapOptionsDefaults.maxCanvasSize) { this._factor = this.width / this.heatmapOptionsDefaults.maxCanvasSize; } } this.width = this.width / this._factor; this.height = this.height / this._factor; } /** * containingBoundingRect: Cesium.Rectangle like {north, east, south, west} * min: the minimum allowed value for the data values * max: the maximum allowed value for the data values * datapoint: {x,y,value} * heatmapOptions: a heatmap.js options object (see http://www.patrick-wied.at/static/heatmapjs/docs.html#h337-create) * */ public create(containingBoundingRect: Rectangle, heatmapDataSet: HeatmapDataSet, heatmapOptions: HeatMapOptions) { const userBB = containingBoundingRect; const {heatPointsData, min = 0, max = 100} = heatmapDataSet; const finalHeatmapOptions = Object.assign({}, this.heatmapOptionsDefaults, heatmapOptions); this._mbounds = this.wgs84ToMercatorBB(userBB); this.setWidthAndHeight(this._mbounds); finalHeatmapOptions.radius = Math.round((heatmapOptions.radius) ? heatmapOptions.radius : ((this.width > this.height) ? this.width / this.heatmapOptionsDefaults.radiusFactor : this.height / this.heatmapOptionsDefaults.radiusFactor)); this._spacing = finalHeatmapOptions.radius * this.heatmapOptionsDefaults.spacingFactor; this._xoffset = this._mbounds.west; this._yoffset = this._mbounds.south; this.width = Math.round(this.width + this._spacing * 2); this.height = Math.round(this.height + this._spacing * 2); this._mbounds.west -= this._spacing * this._factor; this._mbounds.east += this._spacing * this._factor; this._mbounds.south -= this._spacing * this._factor; this._mbounds.north += this._spacing * this._factor; this.bounds = this.mercatorToWgs84BB(this._mbounds); this._rectangle = Cesium.Rectangle.fromDegrees(this.bounds.west, this.bounds.south, this.bounds.east, this.bounds.north); const {container, id} = this.createContainer(this.height, this.width); Object.assign(finalHeatmapOptions, {container}); this.heatmap = h337.create(finalHeatmapOptions); this.setWGS84Data(0, 100, heatPointsData); const heatMapCanvas = this.heatmap._renderer.canvas; const heatMapMaterial = new Cesium.ImageMaterialProperty({ image: heatMapCanvas, transparent: true, }); this.setClear(heatMapMaterial, id); return heatMapMaterial; } private setClear(heatMapMaterial: any, id: string) { heatMapMaterial.clear = () => { const elem = document.getElementById(id); return elem.parentNode.removeChild(elem); }; } }
the_stack
import * as React from "react"; import BrowserAdapter, { ICanAddEventListener, IIFrameWindow, IHostWindow } from "../../../src/components/BrowserAdapter"; import { Action } from "redux"; import { MemoryRouter } from "react-router-dom"; import MlsClient from "../../../src/MlsClient"; import actions from "../../../src/actionCreators/actions"; import { expect, should } from "chai"; import fetch from "../../../src/utilities/fetch"; import { fibonacciCode, emptyWorkspace } from "../../testResources"; import * as enzyme from "enzyme"; import * as Adapter from "enzyme-adapter-react-16"; import { NullAIClient } from "../../../src/ApplicationInsights"; enzyme.configure({ adapter: new Adapter() }); require("jsdom-global")(); interface ICanSendEvent { sendMessageEvent: (origin: string, data: any) => void; recordedEvents: Action[]; } interface ICanRecordPostedMessages { recordedMessages: Object[]; } should(); describe("BrowserAdapter Messaging", () => { var recordedActions: Action[]; var recordAction: (a: Action) => void; var hostWindow: IHostWindow & ICanRecordPostedMessages; let cookieValue: string; const setCookie = (_name: string, value: string) => { cookieValue = value; return ""; }; const getCookie = () => cookieValue; const apiBaseAddress = new URL("https://try.dot.net"); const hostOrigin = new URL("https://docs.microsoft.com"); const encodedHostOrigin = encodeURIComponent(hostOrigin.href); const iframeSrc = new URL("https://try.dot.net/v2/editor?hostOrigin=https%3A%2F%2Fdocs.microsoft.com&waitForConfiguration=true"); const referrer = new URL("https://docs.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.7.1"); let iframeWindow: ICanAddEventListener<MessageEvent> & IIFrameWindow & ICanSendEvent; beforeEach(() => { recordedActions = []; cookieValue = ""; recordAction = (a) => recordedActions.push(a); hostWindow = { recordedMessages: [], postMessage: (message, targetOrigin) => { hostWindow.recordedMessages.push({ message, targetOrigin }); } }; iframeWindow = { getApiBaseAddress: () => apiBaseAddress, getHostOrigin: () => hostOrigin, getReferrer: () => referrer, getQuery: () => iframeSrc.searchParams, addEventListener: (type, handler) => { type.should.equal("message"); iframeWindow.sendMessageEvent = (origin, data) => { handler(new MessageEvent(type, { origin, data })); }; }, recordedEvents: [], sendMessageEvent: () => { }, getClientParameters: () => { return {}; } }; }); it("forwards translated host messages if ?hostOrigin=... is specified and matches", () => { const expectedActions = [ actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace(emptyWorkspace), actions.setActiveBuffer("Program.cs"), actions.enableClientTelemetry(new NullAIClient()), actions.setClient(new MlsClient(fetch, hostOrigin, getCookie, new NullAIClient(), apiBaseAddress)), actions.notifyHostProvidedConfiguration({ hostOrigin }), actions.hostListenerReady(), actions.hostEditorReady(), actions.hostRunReady(), actions.loadCodeRequest("default"), actions.loadCodeSuccess(fibonacciCode, "Program.cs"), actions.runCodeResultSpecified( ["hello", "world"], false ) ]; enzyme.mount( <MemoryRouter initialEntries={[`?hostOrigin=${encodedHostOrigin}&debug=true`]}> <BrowserAdapter log={recordAction} getCookie={getCookie} setCookie={setCookie} aiFactory={(_str) => new NullAIClient()} hostWindow={hostWindow} iframeWindow={iframeWindow} /> </MemoryRouter>); iframeWindow.sendMessageEvent(hostOrigin.href, { type: "setRunResult", output: ["hello", "world"], succeeded: false }); recordedActions.should.deep.equal(expectedActions); }); it("forwards setSourceCode message", () => { const expectedActions = [ actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace(emptyWorkspace), actions.setActiveBuffer("Program.cs"), actions.enableClientTelemetry(new NullAIClient()), actions.setClient(new MlsClient(fetch, hostOrigin, getCookie, new NullAIClient(), apiBaseAddress)), actions.notifyHostProvidedConfiguration({ hostOrigin }), actions.hostListenerReady(), actions.hostEditorReady(), actions.hostRunReady(), actions.loadCodeRequest("default"), actions.loadCodeSuccess(fibonacciCode, "Program.cs"), actions.updateWorkspaceBuffer("Console.WriteLine(\"something new\");", "Program.cs") ]; enzyme.mount( <MemoryRouter initialEntries={[`?hostOrigin=${encodedHostOrigin}&debug=true`]}> <BrowserAdapter log={recordAction} getCookie={getCookie} setCookie={setCookie} aiFactory={(_str) => new NullAIClient()} hostWindow={hostWindow} iframeWindow={iframeWindow} /> </MemoryRouter>); iframeWindow.sendMessageEvent(hostOrigin.href, { type: "setSourceCode", sourceCode: "Console.WriteLine(\"something new\");" }); recordedActions.should.deep.equal(expectedActions); }); it("does not forward host messages if ?hostOrigin=... is specified but does not match", () => { const expectedActions = [ actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace(emptyWorkspace), actions.setActiveBuffer("Program.cs"), actions.enableClientTelemetry(new NullAIClient()), actions.setClient(new MlsClient(fetch, hostOrigin, getCookie, new NullAIClient(), apiBaseAddress)), actions.notifyHostProvidedConfiguration({ hostOrigin }), actions.hostListenerReady(), actions.hostEditorReady(), actions.hostRunReady(), actions.loadCodeRequest("default"), actions.loadCodeSuccess(fibonacciCode, "Program.cs") ]; enzyme.mount( <MemoryRouter initialEntries={[`?hostOrigin=${encodedHostOrigin}&debug=true`]}> <BrowserAdapter log={recordAction} getCookie={getCookie} setCookie={setCookie} iframeWindow={iframeWindow} hostWindow={hostWindow} aiFactory={(_str) => new NullAIClient} /> </MemoryRouter>); iframeWindow.sendMessageEvent("https://docs.not-microsoft.com/", actions.runClicked()); recordedActions.should.deep.equal(expectedActions); }); it("dispatches actions to the hostWindow", () => { const expectedActions = [{ editorId: "", messageOrigin: `/?hostOrigin=${encodedHostOrigin}`, type: "HostListenerReady" }, { editorId: "", messageOrigin: "/?hostOrigin=https%3A%2F%2Fdocs.microsoft.com%2F", type: "HostEditorReady" }, { editorId: "", messageOrigin: "/?hostOrigin=https%3A%2F%2Fdocs.microsoft.com%2F", type: "HostRunReady" }]; enzyme.mount( <MemoryRouter initialEntries={[`?hostOrigin=${encodedHostOrigin}`]}> <BrowserAdapter hostWindow={hostWindow} getCookie={getCookie} setCookie={setCookie} aiFactory={(_str) => new NullAIClient()} iframeWindow={iframeWindow} /> </MemoryRouter>); var result = hostWindow.recordedMessages .filter((e: { targetOrigin: string }) => e.targetOrigin === hostOrigin.href) .map((e: { message: string }) => e.message); result.should.deep.equal(expectedActions); }); it("does not log if 'debug' is not specified", () => { enzyme.mount( <MemoryRouter> <BrowserAdapter log={recordAction} getCookie={getCookie} setCookie={setCookie} aiFactory={(_str) => new NullAIClient()} hostWindow={hostWindow} iframeWindow={iframeWindow} /> </MemoryRouter>); expect(recordedActions).to.be.empty; }); it("hides the editor at startup when ?waitForConfiguration=true", () => { const expectedActions = [ actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace(emptyWorkspace), actions.setActiveBuffer("Program.cs"), actions.hideEditor(), actions.disableBranding(), actions.enableClientTelemetry(new NullAIClient()), actions.setClient(new MlsClient(fetch, hostOrigin, getCookie, new NullAIClient(), apiBaseAddress)), actions.notifyHostProvidedConfiguration({ hostOrigin }), actions.hostListenerReady(), actions.hostEditorReady(), actions.hostRunReady(), actions.loadCodeRequest("default"), actions.loadCodeSuccess(fibonacciCode, "Program.cs") ]; enzyme.mount( <MemoryRouter initialEntries={[`?waitForConfiguration=true&debug=true`]}> <BrowserAdapter log={recordAction} getCookie={getCookie} setCookie={setCookie} aiFactory={(_str) => new NullAIClient()} hostWindow={hostWindow} iframeWindow={iframeWindow} /> </MemoryRouter>); recordedActions.should.deep.equal(expectedActions); }); });
the_stack
import * as net from 'net'; import {EventEmitter} from 'events'; import {BitsUtil} from '../util/BitsUtil'; import {BuildInfo} from '../BuildInfo'; import {AddressImpl, IOError, UUID} from '../core'; import {ClientMessageHandler} from '../protocol/ClientMessage'; import {deferredPromise, DeferredPromise} from '../util/Util'; import {ILogger} from '../logging/ILogger'; import { ClientMessage, Frame, SIZE_OF_FRAME_LENGTH_AND_FLAGS } from '../protocol/ClientMessage'; import {ClientConfig} from '../config'; import {ConnectionManager} from './ConnectionManager'; import {LifecycleService} from '../LifecycleService'; const FROZEN_ARRAY = Object.freeze([]) as OutputQueueItem[]; const PROPERTY_PIPELINING_ENABLED = 'hazelcast.client.autopipelining.enabled'; const PROPERTY_PIPELINING_THRESHOLD = 'hazelcast.client.autopipelining.threshold.bytes'; const PROPERTY_NO_DELAY = 'hazelcast.client.socket.no.delay'; abstract class Writer extends EventEmitter { abstract write(message: ClientMessage, resolver: DeferredPromise<void>): void; abstract close(): void; } interface OutputQueueItem { message: ClientMessage; resolver: DeferredPromise<void>; } /** @internal */ export class PipelinedWriter extends Writer { private queue: OutputQueueItem[] = []; private error: Error; private scheduled = false; private canWrite = true; // reusable buffer for coalescing private readonly coalesceBuf: Buffer; constructor( private readonly socket: net.Socket, // coalescing threshold in bytes private readonly threshold: number, private readonly incrementBytesWrittenFn: (numberOfBytes: number) => void, ) { super(); this.coalesceBuf = Buffer.allocUnsafe(threshold); // write queued items on drain event socket.on('drain', () => { this.canWrite = true; this.schedule(); }); } write(message: ClientMessage, resolver: DeferredPromise<void>): void { if (this.error) { // if there was a write error, it's useless to keep writing to the socket return process.nextTick(() => resolver.reject(this.error)); } this.queue.push({ message, resolver }); this.schedule(); } close(): void { this.canWrite = false; // no more items can be added now this.queue = FROZEN_ARRAY; } private schedule(): void { if (!this.scheduled && this.canWrite) { this.scheduled = true; // nextTick allows queue to be processed on the current event loop phase process.nextTick(() => this.process()); } } private process(): void { if (this.error) { return; } let totalLength = 0; let queueIdx = 0; while (queueIdx < this.queue.length && totalLength < this.threshold) { const msg = this.queue[queueIdx].message; const msgLength = msg.getTotalLength(); // if the next buffer exceeds the threshold, // try to take multiple queued buffers which fit this.coalesceBuf if (queueIdx > 0 && totalLength + msgLength > this.threshold) { break; } totalLength += msgLength; queueIdx++; } if (totalLength === 0) { this.scheduled = false; return; } const writeBatch = this.queue.slice(0, queueIdx); this.queue = this.queue.slice(queueIdx); let buf; if (writeBatch.length === 1 && totalLength > this.threshold) { // take the only large message buf = writeBatch[0].message.toBuffer(); } else { // coalesce buffers let pos = 0; for (const item of writeBatch) { pos = item.message.writeTo(this.coalesceBuf, pos); } buf = this.coalesceBuf.slice(0, totalLength); } // write to the socket: no further writes until flushed this.canWrite = this.socket.write(buf, (err: Error) => { if (err) { this.handleError(err, writeBatch); return; } this.emit('write'); this.incrementBytesWrittenFn(buf.length); for (const item of writeBatch) { item.resolver.resolve(); } if (this.queue.length === 0 || !this.canWrite) { // will start running on the next message or drain event this.scheduled = false; return; } // setImmediate allows I/O between writes setImmediate(() => this.process()); }); } private handleError(err: any, sentResolvers: OutputQueueItem[]): void { this.error = new IOError(err); for (const item of sentResolvers) { item.resolver.reject(this.error); } for (const item of this.queue) { item.resolver.reject(this.error); } this.close(); } } /** @internal */ export class DirectWriter extends Writer { constructor( private readonly socket: net.Socket, private readonly incrementBytesWrittenFn: (numberOfBytes: number) => void, ) { super(); } write(message: ClientMessage, resolver: DeferredPromise<void>): void { const buffer = message.toBuffer(); this.socket.write(buffer, (err: any) => { if (err) { resolver.reject(new IOError(err)); return; } this.emit('write'); this.incrementBytesWrittenFn(buffer.length); resolver.resolve(); }); } close(): void { // no-op } } /** @internal */ export class ClientMessageReader { private chunks: Buffer[] = []; private chunksTotalSize = 0; private frameSize = 0; private flags = 0; private clientMessage: ClientMessage = null; append(buffer: Buffer): void { this.chunksTotalSize += buffer.length; this.chunks.push(buffer); } read(): ClientMessage { for (;;) { if (this.readFrame()) { if (this.clientMessage.endFrame.isFinalFrame()) { const message = this.clientMessage; this.reset(); return message; } } else { return null; } } } readFrame(): boolean { if (this.chunksTotalSize < SIZE_OF_FRAME_LENGTH_AND_FLAGS) { // we don't have even the frame length and flags ready return false; } if (this.frameSize === 0) { this.readFrameSizeAndFlags(); } if (this.chunksTotalSize < this.frameSize) { return false; } let buf = this.chunks.length === 1 ? this.chunks[0] : Buffer.concat(this.chunks, this.chunksTotalSize); if (this.chunksTotalSize > this.frameSize) { if (this.chunks.length === 1) { this.chunks[0] = buf.slice(this.frameSize); } else { this.chunks = [buf.slice(this.frameSize)]; } buf = buf.slice(SIZE_OF_FRAME_LENGTH_AND_FLAGS, this.frameSize); } else { this.chunks = []; buf = buf.slice(SIZE_OF_FRAME_LENGTH_AND_FLAGS); } this.chunksTotalSize -= this.frameSize; this.frameSize = 0; // No need to reset flags since it will be overwritten on the next readFrameSizeAndFlags call. const frame = new Frame(buf, this.flags); if (this.clientMessage == null) { this.clientMessage = ClientMessage.createForDecode(frame); } else { this.clientMessage.addFrame(frame); } return true; } private reset(): void { this.clientMessage = null; } private readFrameSizeAndFlags(): void { if (this.chunks[0].length >= SIZE_OF_FRAME_LENGTH_AND_FLAGS) { this.frameSize = this.chunks[0].readInt32LE(0); this.flags = this.chunks[0].readUInt16LE(BitsUtil.INT_SIZE_IN_BYTES); return; } let readChunksSize = 0; for (let i = 0; i < this.chunks.length; i++) { readChunksSize += this.chunks[i].length; if (readChunksSize >= SIZE_OF_FRAME_LENGTH_AND_FLAGS) { const merged = Buffer.concat(this.chunks.slice(0, i + 1), readChunksSize); this.frameSize = merged.readInt32LE(0); this.flags = merged.readUInt16LE(BitsUtil.INT_SIZE_IN_BYTES); return; } } throw new Error('Detected illegal internal call in ClientMessageReader!'); } } /** @internal */ export class FragmentedClientMessageHandler { private readonly fragmentedMessages = new Map<number, ClientMessage>(); constructor(private readonly logger: ILogger) {} handleFragmentedMessage(clientMessage: ClientMessage, callback: ClientMessageHandler): void { const fragmentationFrame = clientMessage.startFrame; const fragmentationId = clientMessage.getFragmentationId(); clientMessage.dropFragmentationFrame(); if (fragmentationFrame.hasBeginFragmentFlag()) { this.fragmentedMessages.set(fragmentationId, clientMessage); } else { const existingMessage = this.fragmentedMessages.get(fragmentationId); if (existingMessage == null) { this.logger.debug('FragmentedClientMessageHandler', 'A fragmented message without the begin part is received. Fragmentation id: ' + fragmentationId); return; } existingMessage.merge(clientMessage); if (fragmentationFrame.hasEndFragmentFlag()) { this.fragmentedMessages.delete(fragmentationId); callback(existingMessage); } } } } /** @internal */ export class Connection { private remoteUuid: UUID; private readonly localAddress: AddressImpl; private lastReadTimeMillis: number; private lastWriteTimeMillis: number; private readonly startTime: number = Date.now(); private closedTime: number; private closedReason: string; private closedCause: Error; private connectedServerVersion: number; private readonly writer: Writer; private readonly reader: ClientMessageReader; private readonly fragmentedMessageHandler: FragmentedClientMessageHandler; constructor( private readonly connectionManager: ConnectionManager, clientConfig: ClientConfig, private readonly logger: ILogger, private remoteAddress: AddressImpl, private readonly socket: net.Socket, private readonly connectionId: number, private readonly lifecycleService: LifecycleService, private readonly incrementBytesReadFn: (numberOfBytes: number) => void, private readonly incrementBytesWrittenFn: (numberOfBytes: number) => void, ) { const enablePipelining = clientConfig.properties[PROPERTY_PIPELINING_ENABLED] as boolean; const pipeliningThreshold = clientConfig.properties[PROPERTY_PIPELINING_THRESHOLD] as number; const noDelay = clientConfig.properties[PROPERTY_NO_DELAY] as boolean; this.socket.setNoDelay(noDelay); this.localAddress = new AddressImpl(this.socket.localAddress, this.socket.localPort); this.lastReadTimeMillis = 0; this.closedTime = 0; this.connectedServerVersion = BuildInfo.UNKNOWN_VERSION_ID; this.writer = enablePipelining ? new PipelinedWriter(this.socket, pipeliningThreshold, this.incrementBytesWrittenFn) : new DirectWriter(this.socket, this.incrementBytesWrittenFn); this.writer.on('write', () => { this.lastWriteTimeMillis = Date.now(); }); this.reader = new ClientMessageReader(); this.fragmentedMessageHandler = new FragmentedClientMessageHandler(this.logger); } /** * Returns the address of local port that is associated with this connection. * @returns */ getLocalAddress(): AddressImpl { return this.localAddress; } /** * Returns the address of remote node that is associated with this connection. * @returns */ getRemoteAddress(): AddressImpl { return this.remoteAddress; } setRemoteAddress(address: AddressImpl): void { this.remoteAddress = address; } getRemoteUuid(): UUID { return this.remoteUuid; } setRemoteUuid(remoteUuid: UUID): void { this.remoteUuid = remoteUuid; } write(message: ClientMessage): Promise<void> { const deferred = deferredPromise<void>(); this.writer.write(message, deferred); return deferred.promise; } setConnectedServerVersion(versionString: string): void { this.connectedServerVersion = BuildInfo.calculateServerVersionFromString(versionString); } getConnectedServerVersion(): number { return this.connectedServerVersion; } /** * Closes this connection. */ close(reason: string, cause: Error): void { if (this.closedTime !== 0) { return; } this.closedTime = Date.now(); this.closedCause = cause; this.closedReason = reason; this.logClose(); this.writer.close(); this.socket.end(); this.connectionManager.onConnectionClose(this); } isAlive(): boolean { return this.closedTime === 0; } getClosedReason(): string { return this.closedReason; } getStartTime(): number { return this.startTime; } getLastReadTimeMillis(): number { return this.lastReadTimeMillis; } getLastWriteTimeMillis(): number { return this.lastWriteTimeMillis; } equals(other: Connection): boolean { if (other == null) { return false; } return this.connectionId === other.connectionId; } toString(): string { return 'Connection{' + 'alive=' + this.isAlive() + ', connectionId=' + this.connectionId + ', remoteAddress=' + this.remoteAddress + '}'; } /** * Registers a function to pass received data on 'data' events on this connection. * @param callback */ registerResponseCallback(callback: ClientMessageHandler): void { this.socket.on('data', (buffer: Buffer) => { this.lastReadTimeMillis = Date.now(); this.reader.append(buffer); let clientMessage = this.reader.read(); while (clientMessage !== null) { if (clientMessage.startFrame.hasUnfragmentedMessageFlag()) { callback(clientMessage); } else { this.fragmentedMessageHandler.handleFragmentedMessage(clientMessage, callback); } clientMessage = this.reader.read(); } this.incrementBytesReadFn(buffer.length); }); } private logClose(): void { let message = this.toString() + ' closed. Reason: '; if (this.closedReason != null) { message += this.closedReason; } else { message += 'Socket explicitly closed'; } if (this.closedCause != null) { message += ' - '; const cause = this.closedCause as NodeJS.ErrnoException; if (cause.code != null) { message += cause.code + ': '; } message += cause.message; } if (this.lifecycleService.isRunning()) { if (this.closedCause == null) { this.logger.info('Connection', message); } else { this.logger.warn('Connection', message); } } else { this.logger.trace('Connection', message); } } }
the_stack
import * as React from 'react' import { render, screen, within } from '@testing-library/react' import { Modal, ModalHeader, ModalFooter, ModalBody, ModalCloseButton } from './modal' import userEvent from '@testing-library/user-event' import { axe } from 'jest-axe' describe('Modal', () => { function TestCaseWithState() { const [isOpen, setOpen] = React.useState(false) return ( <> <button type="button" onClick={() => setOpen(true)}> Click me </button> <Modal isOpen={isOpen} onDismiss={() => setOpen(false)} aria-label="modal"> <button type="button" onClick={() => setOpen(false)}> Close me </button> <button type="button">Another button</button> </Modal> </> ) } it('renders a semantic accessible dialog', () => { render( <Modal isOpen aria-label="I'm an accessible dialog"> Hello </Modal>, ) expect(screen.getByRole('dialog', { name: "I'm an accessible dialog" })).toBeInTheDocument() }) it('does not acknowledge the className prop, but exceptionallySetClassName instead', () => { render( <Modal aria-label="modal" // @ts-expect-error className="wrong" exceptionallySetClassName="right" > Hello </Modal>, ) const modal = screen.getByRole('dialog', { name: 'modal' }) expect(modal).toHaveClass('right') expect(modal).not.toHaveClass('wrong') }) it('renders its children as its content', () => { render( <Modal isOpen aria-label="modal"> <div>one</div> <div>two</div> </Modal>, ) const modal = screen.getByRole('dialog', { name: 'modal' }) expect(modal.innerHTML).toMatchInlineSnapshot(`"<div>one</div><div>two</div>"`) }) it('is dismissed if isOpen="false"', () => { render(<TestCaseWithState />) expect(screen.queryByRole('dialog', { name: 'modal' })).not.toBeInTheDocument() userEvent.click(screen.getByRole('button', { name: 'Click me' })) expect(screen.getByRole('dialog', { name: 'modal' })).toBeInTheDocument() userEvent.click(screen.getByRole('button', { name: 'Close me' })) expect(screen.queryByRole('dialog', { name: 'modal' })).not.toBeInTheDocument() }) it('hides the content underneath from assistive technologies', () => { render(<TestCaseWithState />) userEvent.click(screen.getByRole('button', { name: 'Click me' })) // Button is present, but not found by role expect(screen.queryByRole('button', { name: 'Click me' })).not.toBeInTheDocument() expect(screen.getByText('Click me')).toBeInTheDocument() // Button is visible by role again once the modal is gone userEvent.click(screen.getByRole('button', { name: 'Close me' })) expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument() }) it('is dismissed when clicking in the overlay', () => { render(<TestCaseWithState />) userEvent.click(screen.getByRole('button', { name: 'Click me' })) expect(screen.getByRole('dialog', { name: 'modal' })).toBeInTheDocument() userEvent.click(screen.getByTestId('modal-overlay')) expect(screen.queryByRole('dialog', { name: 'modal' })).not.toBeInTheDocument() }) }) describe('ModalHeader', () => { it('renders a semantic banner', () => { render(<ModalHeader>Hello</ModalHeader>) expect(screen.getByRole('banner')).toBeInTheDocument() }) it('does not acknowledge the className prop, but exceptionallySetClassName instead', () => { render( <ModalHeader data-testid="modal-header" // @ts-expect-error className="wrong" exceptionallySetClassName="right" > Hello </ModalHeader>, ) const modalHeader = screen.getByTestId('modal-header') expect(modalHeader).toHaveClass('right') expect(modalHeader).not.toHaveClass('wrong') }) it('renders its children as its content', () => { render( <ModalHeader data-testid="modal-header"> <div data-testid="modal-header-content">Hello</div> </ModalHeader>, ) expect( within(screen.getByTestId('modal-header')).getByTestId('modal-header-content'), ).toBeInTheDocument() }) it("renders a button that calls the modal's onDismiss callback when clicked", () => { const onDismiss = jest.fn() render( <Modal isOpen onDismiss={onDismiss} aria-label="modal"> <ModalHeader>Hello</ModalHeader> </Modal>, ) expect(onDismiss).not.toHaveBeenCalled() userEvent.click(screen.getByRole('button', { name: 'Close modal' })) expect(onDismiss).toHaveBeenCalledTimes(1) }) it('allows to render custom content in place of the button', () => { render(<ModalHeader button={<a href="/help">Help</a>}>Hello</ModalHeader>) expect(screen.queryByRole('button', { name: 'Close modal' })).not.toBeInTheDocument() expect(screen.getByRole('link', { name: 'Help' })).toBeInTheDocument() }) it('optionally renders a divider', () => { const { rerender } = render(<ModalHeader>Hello</ModalHeader>) expect(screen.queryByRole('separator')).not.toBeInTheDocument() rerender(<ModalHeader withDivider>Hello</ModalHeader>) expect(screen.getByRole('separator')).toBeInTheDocument() }) }) describe('ModalFooter', () => { it('renders a semantic contentinfo', () => { render(<ModalFooter>Hello</ModalFooter>) expect(screen.getByRole('contentinfo')).toBeInTheDocument() }) it('does not acknowledge the className prop, but exceptionallySetClassName instead', () => { render( <ModalFooter data-testid="modal-footer" // @ts-expect-error className="wrong" exceptionallySetClassName="right" > Hello </ModalFooter>, ) const modalFooter = screen.getByTestId('modal-footer') expect(modalFooter).toHaveClass('right') expect(modalFooter).not.toHaveClass('wrong') }) it('renders its children as its content', () => { render( <ModalFooter data-testid="modal-footer"> <div data-testid="modal-footer-content">Hello</div> </ModalFooter>, ) expect( within(screen.getByTestId('modal-footer')).getByTestId('modal-footer-content'), ).toBeInTheDocument() }) it('optionally renders a divider', () => { const { rerender } = render(<ModalFooter>Hello</ModalFooter>) expect(screen.queryByRole('separator')).not.toBeInTheDocument() rerender(<ModalFooter withDivider>Hello</ModalFooter>) expect(screen.getByRole('separator')).toBeInTheDocument() }) }) describe('ModalBody', () => { it('does not acknowledge the className prop, but exceptionallySetClassName instead', () => { render( <ModalBody data-testid="modal-body" // @ts-expect-error className="wrong" exceptionallySetClassName="right" > Hello </ModalBody>, ) const modalBody = screen.getByTestId('modal-body') expect(modalBody).toHaveClass('right') expect(modalBody).not.toHaveClass('wrong') }) it('renders its children as its content', () => { render( <ModalBody data-testid="modal-body"> <div data-testid="modal-body-content">Hello</div> </ModalBody>, ) expect( within(screen.getByTestId('modal-body')).getByTestId('modal-body-content'), ).toBeInTheDocument() }) it('adapts its styles to the height prop of the outer Modal', () => { const { rerender } = render( <Modal isOpen height="fitContent" aria-label="modal"> <ModalBody data-testid="modal-body">Content</ModalBody> </Modal>, ) const modalBody = screen.getByTestId('modal-body') expect(modalBody).toHaveClass('flexGrow-0') expect(modalBody).not.toHaveClass('flexGrow-1') expect(modalBody).not.toHaveClass('height-full') rerender( <Modal isOpen height="expand" aria-label="modal"> <ModalBody data-testid="modal-body">Content</ModalBody> </Modal>, ) expect(modalBody).not.toHaveClass('flexGrow-0') expect(modalBody).toHaveClass('flexGrow-1') expect(modalBody).toHaveClass('height-full') }) }) describe('ModalCloseButton', () => { function renderTestCase() { const onDismiss = jest.fn() const renderResult = render( <Modal isOpen onDismiss={onDismiss} aria-label="modal"> <ModalHeader button={<ModalCloseButton aria-label="Cerrar ventana" />}> Hello </ModalHeader> </Modal>, ) return { button: screen.getByRole('button', { name: 'Cerrar ventana' }), onDismiss, ...renderResult, } } it('can be used to render a customized button in place of the default one', () => { renderTestCase() expect(screen.queryByRole('button', { name: 'Close modal' })).not.toBeInTheDocument() expect(screen.getByRole('button', { name: 'Cerrar ventana' })).toBeInTheDocument() }) it("calls the modal's onDismiss callback when clicked", () => { const { button, onDismiss } = renderTestCase() expect(onDismiss).not.toHaveBeenCalled() userEvent.click(button) expect(onDismiss).toHaveBeenCalledTimes(1) }) it('renders as a regular non-submit button', () => { const { button } = renderTestCase() expect(button).toHaveAttribute('type', 'button') }) it('renders a svg icon as its content', () => { const { button } = renderTestCase() expect(button.firstElementChild?.tagName).toBe('svg') }) }) describe('a11y', () => { it('renders with no a11y violations with custom content', async () => { const { container } = render( <Modal isOpen={true} aria-label="modal"> <input type="text" aria-labelledby="test-label" /> <label id="test-label">Test Input</label> </Modal>, ) const results = await axe(container) expect(results).toHaveNoViolations() }) it('renders with no a11y violations when using inner-structure components', async () => { const { container } = render( <Modal isOpen={true} aria-label="modal"> <ModalHeader>Header</ModalHeader> <ModalBody>Body</ModalBody> <ModalFooter>Footer</ModalFooter> </Modal>, ) const results = await axe(container) expect(results).toHaveNoViolations() }) it("calls the modal's onDismiss callback when 'Esc' is pressed", () => { const onDismiss = jest.fn() render( <Modal isOpen onDismiss={onDismiss} aria-label="modal"> <ModalHeader>Hello</ModalHeader> </Modal>, ) const modal = screen.getByRole('dialog', { name: 'modal' }) expect(onDismiss).not.toHaveBeenCalled() userEvent.type(modal, '{esc}') expect(onDismiss).toHaveBeenCalledTimes(1) }) })
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 AccessAnalyzer extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: AccessAnalyzer.Types.ClientConfiguration) config: Config & AccessAnalyzer.Types.ClientConfiguration; /** * Retroactively applies the archive rule to existing findings that meet the archive rule criteria. */ applyArchiveRule(params: AccessAnalyzer.Types.ApplyArchiveRuleRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Retroactively applies the archive rule to existing findings that meet the archive rule criteria. */ applyArchiveRule(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Cancels the requested policy generation. */ cancelPolicyGeneration(params: AccessAnalyzer.Types.CancelPolicyGenerationRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.CancelPolicyGenerationResponse) => void): Request<AccessAnalyzer.Types.CancelPolicyGenerationResponse, AWSError>; /** * Cancels the requested policy generation. */ cancelPolicyGeneration(callback?: (err: AWSError, data: AccessAnalyzer.Types.CancelPolicyGenerationResponse) => void): Request<AccessAnalyzer.Types.CancelPolicyGenerationResponse, AWSError>; /** * Creates an access preview that allows you to preview IAM Access Analyzer findings for your resource before deploying resource permissions. */ createAccessPreview(params: AccessAnalyzer.Types.CreateAccessPreviewRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.CreateAccessPreviewResponse) => void): Request<AccessAnalyzer.Types.CreateAccessPreviewResponse, AWSError>; /** * Creates an access preview that allows you to preview IAM Access Analyzer findings for your resource before deploying resource permissions. */ createAccessPreview(callback?: (err: AWSError, data: AccessAnalyzer.Types.CreateAccessPreviewResponse) => void): Request<AccessAnalyzer.Types.CreateAccessPreviewResponse, AWSError>; /** * Creates an analyzer for your account. */ createAnalyzer(params: AccessAnalyzer.Types.CreateAnalyzerRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.CreateAnalyzerResponse) => void): Request<AccessAnalyzer.Types.CreateAnalyzerResponse, AWSError>; /** * Creates an analyzer for your account. */ createAnalyzer(callback?: (err: AWSError, data: AccessAnalyzer.Types.CreateAnalyzerResponse) => void): Request<AccessAnalyzer.Types.CreateAnalyzerResponse, AWSError>; /** * Creates an archive rule for the specified analyzer. Archive rules automatically archive new findings that meet the criteria you define when you create the rule. To learn about filter keys that you can use to create an archive rule, see IAM Access Analyzer filter keys in the IAM User Guide. */ createArchiveRule(params: AccessAnalyzer.Types.CreateArchiveRuleRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Creates an archive rule for the specified analyzer. Archive rules automatically archive new findings that meet the criteria you define when you create the rule. To learn about filter keys that you can use to create an archive rule, see IAM Access Analyzer filter keys in the IAM User Guide. */ createArchiveRule(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified analyzer. When you delete an analyzer, IAM Access Analyzer is disabled for the account or organization in the current or specific Region. All findings that were generated by the analyzer are deleted. You cannot undo this action. */ deleteAnalyzer(params: AccessAnalyzer.Types.DeleteAnalyzerRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified analyzer. When you delete an analyzer, IAM Access Analyzer is disabled for the account or organization in the current or specific Region. All findings that were generated by the analyzer are deleted. You cannot undo this action. */ deleteAnalyzer(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified archive rule. */ deleteArchiveRule(params: AccessAnalyzer.Types.DeleteArchiveRuleRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified archive rule. */ deleteArchiveRule(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Retrieves information about an access preview for the specified analyzer. */ getAccessPreview(params: AccessAnalyzer.Types.GetAccessPreviewRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.GetAccessPreviewResponse) => void): Request<AccessAnalyzer.Types.GetAccessPreviewResponse, AWSError>; /** * Retrieves information about an access preview for the specified analyzer. */ getAccessPreview(callback?: (err: AWSError, data: AccessAnalyzer.Types.GetAccessPreviewResponse) => void): Request<AccessAnalyzer.Types.GetAccessPreviewResponse, AWSError>; /** * Retrieves information about a resource that was analyzed. */ getAnalyzedResource(params: AccessAnalyzer.Types.GetAnalyzedResourceRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.GetAnalyzedResourceResponse) => void): Request<AccessAnalyzer.Types.GetAnalyzedResourceResponse, AWSError>; /** * Retrieves information about a resource that was analyzed. */ getAnalyzedResource(callback?: (err: AWSError, data: AccessAnalyzer.Types.GetAnalyzedResourceResponse) => void): Request<AccessAnalyzer.Types.GetAnalyzedResourceResponse, AWSError>; /** * Retrieves information about the specified analyzer. */ getAnalyzer(params: AccessAnalyzer.Types.GetAnalyzerRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.GetAnalyzerResponse) => void): Request<AccessAnalyzer.Types.GetAnalyzerResponse, AWSError>; /** * Retrieves information about the specified analyzer. */ getAnalyzer(callback?: (err: AWSError, data: AccessAnalyzer.Types.GetAnalyzerResponse) => void): Request<AccessAnalyzer.Types.GetAnalyzerResponse, AWSError>; /** * Retrieves information about an archive rule. To learn about filter keys that you can use to create an archive rule, see IAM Access Analyzer filter keys in the IAM User Guide. */ getArchiveRule(params: AccessAnalyzer.Types.GetArchiveRuleRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.GetArchiveRuleResponse) => void): Request<AccessAnalyzer.Types.GetArchiveRuleResponse, AWSError>; /** * Retrieves information about an archive rule. To learn about filter keys that you can use to create an archive rule, see IAM Access Analyzer filter keys in the IAM User Guide. */ getArchiveRule(callback?: (err: AWSError, data: AccessAnalyzer.Types.GetArchiveRuleResponse) => void): Request<AccessAnalyzer.Types.GetArchiveRuleResponse, AWSError>; /** * Retrieves information about the specified finding. */ getFinding(params: AccessAnalyzer.Types.GetFindingRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.GetFindingResponse) => void): Request<AccessAnalyzer.Types.GetFindingResponse, AWSError>; /** * Retrieves information about the specified finding. */ getFinding(callback?: (err: AWSError, data: AccessAnalyzer.Types.GetFindingResponse) => void): Request<AccessAnalyzer.Types.GetFindingResponse, AWSError>; /** * Retrieves the policy that was generated using StartPolicyGeneration. */ getGeneratedPolicy(params: AccessAnalyzer.Types.GetGeneratedPolicyRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.GetGeneratedPolicyResponse) => void): Request<AccessAnalyzer.Types.GetGeneratedPolicyResponse, AWSError>; /** * Retrieves the policy that was generated using StartPolicyGeneration. */ getGeneratedPolicy(callback?: (err: AWSError, data: AccessAnalyzer.Types.GetGeneratedPolicyResponse) => void): Request<AccessAnalyzer.Types.GetGeneratedPolicyResponse, AWSError>; /** * Retrieves a list of access preview findings generated by the specified access preview. */ listAccessPreviewFindings(params: AccessAnalyzer.Types.ListAccessPreviewFindingsRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ListAccessPreviewFindingsResponse) => void): Request<AccessAnalyzer.Types.ListAccessPreviewFindingsResponse, AWSError>; /** * Retrieves a list of access preview findings generated by the specified access preview. */ listAccessPreviewFindings(callback?: (err: AWSError, data: AccessAnalyzer.Types.ListAccessPreviewFindingsResponse) => void): Request<AccessAnalyzer.Types.ListAccessPreviewFindingsResponse, AWSError>; /** * Retrieves a list of access previews for the specified analyzer. */ listAccessPreviews(params: AccessAnalyzer.Types.ListAccessPreviewsRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ListAccessPreviewsResponse) => void): Request<AccessAnalyzer.Types.ListAccessPreviewsResponse, AWSError>; /** * Retrieves a list of access previews for the specified analyzer. */ listAccessPreviews(callback?: (err: AWSError, data: AccessAnalyzer.Types.ListAccessPreviewsResponse) => void): Request<AccessAnalyzer.Types.ListAccessPreviewsResponse, AWSError>; /** * Retrieves a list of resources of the specified type that have been analyzed by the specified analyzer.. */ listAnalyzedResources(params: AccessAnalyzer.Types.ListAnalyzedResourcesRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ListAnalyzedResourcesResponse) => void): Request<AccessAnalyzer.Types.ListAnalyzedResourcesResponse, AWSError>; /** * Retrieves a list of resources of the specified type that have been analyzed by the specified analyzer.. */ listAnalyzedResources(callback?: (err: AWSError, data: AccessAnalyzer.Types.ListAnalyzedResourcesResponse) => void): Request<AccessAnalyzer.Types.ListAnalyzedResourcesResponse, AWSError>; /** * Retrieves a list of analyzers. */ listAnalyzers(params: AccessAnalyzer.Types.ListAnalyzersRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ListAnalyzersResponse) => void): Request<AccessAnalyzer.Types.ListAnalyzersResponse, AWSError>; /** * Retrieves a list of analyzers. */ listAnalyzers(callback?: (err: AWSError, data: AccessAnalyzer.Types.ListAnalyzersResponse) => void): Request<AccessAnalyzer.Types.ListAnalyzersResponse, AWSError>; /** * Retrieves a list of archive rules created for the specified analyzer. */ listArchiveRules(params: AccessAnalyzer.Types.ListArchiveRulesRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ListArchiveRulesResponse) => void): Request<AccessAnalyzer.Types.ListArchiveRulesResponse, AWSError>; /** * Retrieves a list of archive rules created for the specified analyzer. */ listArchiveRules(callback?: (err: AWSError, data: AccessAnalyzer.Types.ListArchiveRulesResponse) => void): Request<AccessAnalyzer.Types.ListArchiveRulesResponse, AWSError>; /** * Retrieves a list of findings generated by the specified analyzer. To learn about filter keys that you can use to retrieve a list of findings, see IAM Access Analyzer filter keys in the IAM User Guide. */ listFindings(params: AccessAnalyzer.Types.ListFindingsRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ListFindingsResponse) => void): Request<AccessAnalyzer.Types.ListFindingsResponse, AWSError>; /** * Retrieves a list of findings generated by the specified analyzer. To learn about filter keys that you can use to retrieve a list of findings, see IAM Access Analyzer filter keys in the IAM User Guide. */ listFindings(callback?: (err: AWSError, data: AccessAnalyzer.Types.ListFindingsResponse) => void): Request<AccessAnalyzer.Types.ListFindingsResponse, AWSError>; /** * Lists all of the policy generations requested in the last seven days. */ listPolicyGenerations(params: AccessAnalyzer.Types.ListPolicyGenerationsRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ListPolicyGenerationsResponse) => void): Request<AccessAnalyzer.Types.ListPolicyGenerationsResponse, AWSError>; /** * Lists all of the policy generations requested in the last seven days. */ listPolicyGenerations(callback?: (err: AWSError, data: AccessAnalyzer.Types.ListPolicyGenerationsResponse) => void): Request<AccessAnalyzer.Types.ListPolicyGenerationsResponse, AWSError>; /** * Retrieves a list of tags applied to the specified resource. */ listTagsForResource(params: AccessAnalyzer.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ListTagsForResourceResponse) => void): Request<AccessAnalyzer.Types.ListTagsForResourceResponse, AWSError>; /** * Retrieves a list of tags applied to the specified resource. */ listTagsForResource(callback?: (err: AWSError, data: AccessAnalyzer.Types.ListTagsForResourceResponse) => void): Request<AccessAnalyzer.Types.ListTagsForResourceResponse, AWSError>; /** * Starts the policy generation request. */ startPolicyGeneration(params: AccessAnalyzer.Types.StartPolicyGenerationRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.StartPolicyGenerationResponse) => void): Request<AccessAnalyzer.Types.StartPolicyGenerationResponse, AWSError>; /** * Starts the policy generation request. */ startPolicyGeneration(callback?: (err: AWSError, data: AccessAnalyzer.Types.StartPolicyGenerationResponse) => void): Request<AccessAnalyzer.Types.StartPolicyGenerationResponse, AWSError>; /** * Immediately starts a scan of the policies applied to the specified resource. */ startResourceScan(params: AccessAnalyzer.Types.StartResourceScanRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Immediately starts a scan of the policies applied to the specified resource. */ startResourceScan(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Adds a tag to the specified resource. */ tagResource(params: AccessAnalyzer.Types.TagResourceRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.TagResourceResponse) => void): Request<AccessAnalyzer.Types.TagResourceResponse, AWSError>; /** * Adds a tag to the specified resource. */ tagResource(callback?: (err: AWSError, data: AccessAnalyzer.Types.TagResourceResponse) => void): Request<AccessAnalyzer.Types.TagResourceResponse, AWSError>; /** * Removes a tag from the specified resource. */ untagResource(params: AccessAnalyzer.Types.UntagResourceRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.UntagResourceResponse) => void): Request<AccessAnalyzer.Types.UntagResourceResponse, AWSError>; /** * Removes a tag from the specified resource. */ untagResource(callback?: (err: AWSError, data: AccessAnalyzer.Types.UntagResourceResponse) => void): Request<AccessAnalyzer.Types.UntagResourceResponse, AWSError>; /** * Updates the criteria and values for the specified archive rule. */ updateArchiveRule(params: AccessAnalyzer.Types.UpdateArchiveRuleRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the criteria and values for the specified archive rule. */ updateArchiveRule(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the status for the specified findings. */ updateFindings(params: AccessAnalyzer.Types.UpdateFindingsRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the status for the specified findings. */ updateFindings(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Requests the validation of a policy and returns a list of findings. The findings help you identify issues and provide actionable recommendations to resolve the issue and enable you to author functional policies that meet security best practices. */ validatePolicy(params: AccessAnalyzer.Types.ValidatePolicyRequest, callback?: (err: AWSError, data: AccessAnalyzer.Types.ValidatePolicyResponse) => void): Request<AccessAnalyzer.Types.ValidatePolicyResponse, AWSError>; /** * Requests the validation of a policy and returns a list of findings. The findings help you identify issues and provide actionable recommendations to resolve the issue and enable you to author functional policies that meet security best practices. */ validatePolicy(callback?: (err: AWSError, data: AccessAnalyzer.Types.ValidatePolicyResponse) => void): Request<AccessAnalyzer.Types.ValidatePolicyResponse, AWSError>; } declare namespace AccessAnalyzer { export type AccessPointArn = string; export type AccessPointPolicy = string; export interface AccessPreview { /** * The ARN of the analyzer used to generate the access preview. */ analyzerArn: AnalyzerArn; /** * A map of resource ARNs for the proposed resource configuration. */ configurations: ConfigurationsMap; /** * The time at which the access preview was created. */ createdAt: Timestamp; /** * The unique ID for the access preview. */ id: AccessPreviewId; /** * The status of the access preview. Creating - The access preview creation is in progress. Completed - The access preview is complete. You can preview findings for external access to the resource. Failed - The access preview creation has failed. */ status: AccessPreviewStatus; /** * Provides more details about the current status of the access preview. For example, if the creation of the access preview fails, a Failed status is returned. This failure can be due to an internal issue with the analysis or due to an invalid resource configuration. */ statusReason?: AccessPreviewStatusReason; } export interface AccessPreviewFinding { /** * The action in the analyzed policy statement that an external principal has permission to perform. */ action?: ActionList; /** * Provides context on how the access preview finding compares to existing access identified in IAM Access Analyzer. New - The finding is for newly-introduced access. Unchanged - The preview finding is an existing finding that would remain unchanged. Changed - The preview finding is an existing finding with a change in status. For example, a Changed finding with preview status Resolved and existing status Active indicates the existing Active finding would become Resolved as a result of the proposed permissions change. */ changeType: FindingChangeType; /** * The condition in the analyzed policy statement that resulted in a finding. */ condition?: ConditionKeyMap; /** * The time at which the access preview finding was created. */ createdAt: Timestamp; /** * An error. */ error?: String; /** * The existing ID of the finding in IAM Access Analyzer, provided only for existing findings. */ existingFindingId?: FindingId; /** * The existing status of the finding, provided only for existing findings. */ existingFindingStatus?: FindingStatus; /** * The ID of the access preview finding. This ID uniquely identifies the element in the list of access preview findings and is not related to the finding ID in Access Analyzer. */ id: AccessPreviewFindingId; /** * Indicates whether the policy that generated the finding allows public access to the resource. */ isPublic?: Boolean; /** * The external principal that has access to a resource within the zone of trust. */ principal?: PrincipalMap; /** * The resource that an external principal has access to. This is the resource associated with the access preview. */ resource?: String; /** * The Amazon Web Services account ID that owns the resource. For most Amazon Web Services resources, the owning account is the account in which the resource was created. */ resourceOwnerAccount: String; /** * The type of the resource that can be accessed in the finding. */ resourceType: ResourceType; /** * The sources of the finding. This indicates how the access that generated the finding is granted. It is populated for Amazon S3 bucket findings. */ sources?: FindingSourceList; /** * The preview status of the finding. This is what the status of the finding would be after permissions deployment. For example, a Changed finding with preview status Resolved and existing status Active indicates the existing Active finding would become Resolved as a result of the proposed permissions change. */ status: FindingStatus; } export type AccessPreviewFindingId = string; export type AccessPreviewFindingsList = AccessPreviewFinding[]; export type AccessPreviewId = string; export type AccessPreviewStatus = "COMPLETED"|"CREATING"|"FAILED"|string; export interface AccessPreviewStatusReason { /** * The reason code for the current status of the access preview. */ code: AccessPreviewStatusReasonCode; } export type AccessPreviewStatusReasonCode = "INTERNAL_ERROR"|"INVALID_CONFIGURATION"|string; export interface AccessPreviewSummary { /** * The ARN of the analyzer used to generate the access preview. */ analyzerArn: AnalyzerArn; /** * The time at which the access preview was created. */ createdAt: Timestamp; /** * The unique ID for the access preview. */ id: AccessPreviewId; /** * The status of the access preview. Creating - The access preview creation is in progress. Completed - The access preview is complete and previews the findings for external access to the resource. Failed - The access preview creation has failed. */ status: AccessPreviewStatus; statusReason?: AccessPreviewStatusReason; } export type AccessPreviewsList = AccessPreviewSummary[]; export type AclCanonicalId = string; export interface AclGrantee { /** * The value specified is the canonical user ID of an Amazon Web Services account. */ id?: AclCanonicalId; /** * Used for granting permissions to a predefined group. */ uri?: AclUri; } export type AclPermission = "READ"|"WRITE"|"READ_ACP"|"WRITE_ACP"|"FULL_CONTROL"|string; export type AclUri = string; export type ActionList = String[]; export interface AnalyzedResource { /** * The actions that an external principal is granted permission to use by the policy that generated the finding. */ actions?: ActionList; /** * The time at which the resource was analyzed. */ analyzedAt: Timestamp; /** * The time at which the finding was created. */ createdAt: Timestamp; /** * An error message. */ error?: String; /** * Indicates whether the policy that generated the finding grants public access to the resource. */ isPublic: Boolean; /** * The ARN of the resource that was analyzed. */ resourceArn: ResourceArn; /** * The Amazon Web Services account ID that owns the resource. */ resourceOwnerAccount: String; /** * The type of the resource that was analyzed. */ resourceType: ResourceType; /** * Indicates how the access that generated the finding is granted. This is populated for Amazon S3 bucket findings. */ sharedVia?: SharedViaList; /** * The current status of the finding generated from the analyzed resource. */ status?: FindingStatus; /** * The time at which the finding was updated. */ updatedAt: Timestamp; } export interface AnalyzedResourceSummary { /** * The ARN of the analyzed resource. */ resourceArn: ResourceArn; /** * The Amazon Web Services account ID that owns the resource. */ resourceOwnerAccount: String; /** * The type of resource that was analyzed. */ resourceType: ResourceType; } export type AnalyzedResourcesList = AnalyzedResourceSummary[]; export type AnalyzerArn = string; export type AnalyzerStatus = "ACTIVE"|"CREATING"|"DISABLED"|"FAILED"|string; export interface AnalyzerSummary { /** * The ARN of the analyzer. */ arn: AnalyzerArn; /** * A timestamp for the time at which the analyzer was created. */ createdAt: Timestamp; /** * The resource that was most recently analyzed by the analyzer. */ lastResourceAnalyzed?: String; /** * The time at which the most recently analyzed resource was analyzed. */ lastResourceAnalyzedAt?: Timestamp; /** * The name of the analyzer. */ name: Name; /** * The status of the analyzer. An Active analyzer successfully monitors supported resources and generates new findings. The analyzer is Disabled when a user action, such as removing trusted access for Identity and Access Management Access Analyzer from Organizations, causes the analyzer to stop generating new findings. The status is Creating when the analyzer creation is in progress and Failed when the analyzer creation has failed. */ status: AnalyzerStatus; /** * The statusReason provides more details about the current status of the analyzer. For example, if the creation for the analyzer fails, a Failed status is returned. For an analyzer with organization as the type, this failure can be due to an issue with creating the service-linked roles required in the member accounts of the Amazon Web Services organization. */ statusReason?: StatusReason; /** * The tags added to the analyzer. */ tags?: TagsMap; /** * The type of analyzer, which corresponds to the zone of trust chosen for the analyzer. */ type: Type; } export type AnalyzersList = AnalyzerSummary[]; export interface ApplyArchiveRuleRequest { /** * The Amazon resource name (ARN) of the analyzer. */ analyzerArn: AnalyzerArn; /** * A client token. */ clientToken?: String; /** * The name of the rule to apply. */ ruleName: Name; } export interface ArchiveRuleSummary { /** * The time at which the archive rule was created. */ createdAt: Timestamp; /** * A filter used to define the archive rule. */ filter: FilterCriteriaMap; /** * The name of the archive rule. */ ruleName: Name; /** * The time at which the archive rule was last updated. */ updatedAt: Timestamp; } export type ArchiveRulesList = ArchiveRuleSummary[]; export type Boolean = boolean; export interface CancelPolicyGenerationRequest { /** * The JobId that is returned by the StartPolicyGeneration operation. The JobId can be used with GetGeneratedPolicy to retrieve the generated policies or used with CancelPolicyGeneration to cancel the policy generation request. */ jobId: JobId; } export interface CancelPolicyGenerationResponse { } export type CloudTrailArn = string; export interface CloudTrailDetails { /** * The ARN of the service role that IAM Access Analyzer uses to access your CloudTrail trail and service last accessed information. */ accessRole: RoleArn; /** * The end of the time range for which IAM Access Analyzer reviews your CloudTrail events. Events with a timestamp after this time are not considered to generate a policy. If this is not included in the request, the default value is the current time. */ endTime?: Timestamp; /** * The start of the time range for which IAM Access Analyzer reviews your CloudTrail events. Events with a timestamp before this time are not considered to generate a policy. */ startTime: Timestamp; /** * A Trail object that contains settings for a trail. */ trails: TrailList; } export interface CloudTrailProperties { /** * The end of the time range for which IAM Access Analyzer reviews your CloudTrail events. Events with a timestamp after this time are not considered to generate a policy. If this is not included in the request, the default value is the current time. */ endTime: Timestamp; /** * The start of the time range for which IAM Access Analyzer reviews your CloudTrail events. Events with a timestamp before this time are not considered to generate a policy. */ startTime: Timestamp; /** * A TrailProperties object that contains settings for trail properties. */ trailProperties: TrailPropertiesList; } export type ConditionKeyMap = {[key: string]: String}; export interface Configuration { /** * The access control configuration is for an IAM role. */ iamRole?: IamRoleConfiguration; /** * The access control configuration is for a KMS key. */ kmsKey?: KmsKeyConfiguration; /** * The access control configuration is for an Amazon S3 Bucket. */ s3Bucket?: S3BucketConfiguration; /** * The access control configuration is for a Secrets Manager secret. */ secretsManagerSecret?: SecretsManagerSecretConfiguration; /** * The access control configuration is for an Amazon SQS queue. */ sqsQueue?: SqsQueueConfiguration; } export type ConfigurationsMap = {[key: string]: Configuration}; export type ConfigurationsMapKey = string; export interface CreateAccessPreviewRequest { /** * The ARN of the account analyzer used to generate the access preview. You can only create an access preview for analyzers with an Account type and Active status. */ analyzerArn: AnalyzerArn; /** * A client token. */ clientToken?: String; /** * Access control configuration for your resource that is used to generate the access preview. The access preview includes findings for external access allowed to the resource with the proposed access control configuration. The configuration must contain exactly one element. */ configurations: ConfigurationsMap; } export interface CreateAccessPreviewResponse { /** * The unique ID for the access preview. */ id: AccessPreviewId; } export interface CreateAnalyzerRequest { /** * The name of the analyzer to create. */ analyzerName: Name; /** * Specifies the archive rules to add for the analyzer. Archive rules automatically archive findings that meet the criteria you define for the rule. */ archiveRules?: InlineArchiveRulesList; /** * A client token. */ clientToken?: String; /** * The tags to apply to the analyzer. */ tags?: TagsMap; /** * The type of analyzer to create. Only ACCOUNT and ORGANIZATION analyzers are supported. You can create only one analyzer per account per Region. You can create up to 5 analyzers per organization per Region. */ type: Type; } export interface CreateAnalyzerResponse { /** * The ARN of the analyzer that was created by the request. */ arn?: AnalyzerArn; } export interface CreateArchiveRuleRequest { /** * The name of the created analyzer. */ analyzerName: Name; /** * A client token. */ clientToken?: String; /** * The criteria for the rule. */ filter: FilterCriteriaMap; /** * The name of the rule to create. */ ruleName: Name; } export interface Criterion { /** * A "contains" operator to match for the filter used to create the rule. */ contains?: ValueList; /** * An "equals" operator to match for the filter used to create the rule. */ eq?: ValueList; /** * An "exists" operator to match for the filter used to create the rule. */ exists?: Boolean; /** * A "not equals" operator to match for the filter used to create the rule. */ neq?: ValueList; } export interface DeleteAnalyzerRequest { /** * The name of the analyzer to delete. */ analyzerName: Name; /** * A client token. */ clientToken?: String; } export interface DeleteArchiveRuleRequest { /** * The name of the analyzer that associated with the archive rule to delete. */ analyzerName: Name; /** * A client token. */ clientToken?: String; /** * The name of the rule to delete. */ ruleName: Name; } export type FilterCriteriaMap = {[key: string]: Criterion}; export interface Finding { /** * The action in the analyzed policy statement that an external principal has permission to use. */ action?: ActionList; /** * The time at which the resource was analyzed. */ analyzedAt: Timestamp; /** * The condition in the analyzed policy statement that resulted in a finding. */ condition: ConditionKeyMap; /** * The time at which the finding was generated. */ createdAt: Timestamp; /** * An error. */ error?: String; /** * The ID of the finding. */ id: FindingId; /** * Indicates whether the policy that generated the finding allows public access to the resource. */ isPublic?: Boolean; /** * The external principal that access to a resource within the zone of trust. */ principal?: PrincipalMap; /** * The resource that an external principal has access to. */ resource?: String; /** * The Amazon Web Services account ID that owns the resource. */ resourceOwnerAccount: String; /** * The type of the resource identified in the finding. */ resourceType: ResourceType; /** * The sources of the finding. This indicates how the access that generated the finding is granted. It is populated for Amazon S3 bucket findings. */ sources?: FindingSourceList; /** * The current status of the finding. */ status: FindingStatus; /** * The time at which the finding was updated. */ updatedAt: Timestamp; } export type FindingChangeType = "CHANGED"|"NEW"|"UNCHANGED"|string; export type FindingId = string; export type FindingIdList = FindingId[]; export interface FindingSource { /** * Includes details about how the access that generated the finding is granted. This is populated for Amazon S3 bucket findings. */ detail?: FindingSourceDetail; /** * Indicates the type of access that generated the finding. */ type: FindingSourceType; } export interface FindingSourceDetail { /** * The ARN of the access point that generated the finding. The ARN format depends on whether the ARN represents an access point or a multi-region access point. */ accessPointArn?: String; } export type FindingSourceList = FindingSource[]; export type FindingSourceType = "POLICY"|"BUCKET_ACL"|"S3_ACCESS_POINT"|string; export type FindingStatus = "ACTIVE"|"ARCHIVED"|"RESOLVED"|string; export type FindingStatusUpdate = "ACTIVE"|"ARCHIVED"|string; export interface FindingSummary { /** * The action in the analyzed policy statement that an external principal has permission to use. */ action?: ActionList; /** * The time at which the resource-based policy that generated the finding was analyzed. */ analyzedAt: Timestamp; /** * The condition in the analyzed policy statement that resulted in a finding. */ condition: ConditionKeyMap; /** * The time at which the finding was created. */ createdAt: Timestamp; /** * The error that resulted in an Error finding. */ error?: String; /** * The ID of the finding. */ id: FindingId; /** * Indicates whether the finding reports a resource that has a policy that allows public access. */ isPublic?: Boolean; /** * The external principal that has access to a resource within the zone of trust. */ principal?: PrincipalMap; /** * The resource that the external principal has access to. */ resource?: String; /** * The Amazon Web Services account ID that owns the resource. */ resourceOwnerAccount: String; /** * The type of the resource that the external principal has access to. */ resourceType: ResourceType; /** * The sources of the finding. This indicates how the access that generated the finding is granted. It is populated for Amazon S3 bucket findings. */ sources?: FindingSourceList; /** * The status of the finding. */ status: FindingStatus; /** * The time at which the finding was most recently updated. */ updatedAt: Timestamp; } export type FindingsList = FindingSummary[]; export interface GeneratedPolicy { /** * The text to use as the content for the new policy. The policy is created using the CreatePolicy action. */ policy: String; } export type GeneratedPolicyList = GeneratedPolicy[]; export interface GeneratedPolicyProperties { /** * Lists details about the Trail used to generated policy. */ cloudTrailProperties?: CloudTrailProperties; /** * This value is set to true if the generated policy contains all possible actions for a service that IAM Access Analyzer identified from the CloudTrail trail that you specified, and false otherwise. */ isComplete?: Boolean; /** * The ARN of the IAM entity (user or role) for which you are generating a policy. */ principalArn: PrincipalArn; } export interface GeneratedPolicyResult { /** * The text to use as the content for the new policy. The policy is created using the CreatePolicy action. */ generatedPolicies?: GeneratedPolicyList; /** * A GeneratedPolicyProperties object that contains properties of the generated policy. */ properties: GeneratedPolicyProperties; } export interface GetAccessPreviewRequest { /** * The unique ID for the access preview. */ accessPreviewId: AccessPreviewId; /** * The ARN of the analyzer used to generate the access preview. */ analyzerArn: AnalyzerArn; } export interface GetAccessPreviewResponse { /** * An object that contains information about the access preview. */ accessPreview: AccessPreview; } export interface GetAnalyzedResourceRequest { /** * The ARN of the analyzer to retrieve information from. */ analyzerArn: AnalyzerArn; /** * The ARN of the resource to retrieve information about. */ resourceArn: ResourceArn; } export interface GetAnalyzedResourceResponse { /** * An AnalyzedResource object that contains information that IAM Access Analyzer found when it analyzed the resource. */ resource?: AnalyzedResource; } export interface GetAnalyzerRequest { /** * The name of the analyzer retrieved. */ analyzerName: Name; } export interface GetAnalyzerResponse { /** * An AnalyzerSummary object that contains information about the analyzer. */ analyzer: AnalyzerSummary; } export interface GetArchiveRuleRequest { /** * The name of the analyzer to retrieve rules from. */ analyzerName: Name; /** * The name of the rule to retrieve. */ ruleName: Name; } export interface GetArchiveRuleResponse { archiveRule: ArchiveRuleSummary; } export interface GetFindingRequest { /** * The ARN of the analyzer that generated the finding. */ analyzerArn: AnalyzerArn; /** * The ID of the finding to retrieve. */ id: FindingId; } export interface GetFindingResponse { /** * A finding object that contains finding details. */ finding?: Finding; } export interface GetGeneratedPolicyRequest { /** * The level of detail that you want to generate. You can specify whether to generate policies with placeholders for resource ARNs for actions that support resource level granularity in policies. For example, in the resource section of a policy, you can receive a placeholder such as "Resource":"arn:aws:s3:::${BucketName}" instead of "*". */ includeResourcePlaceholders?: Boolean; /** * The level of detail that you want to generate. You can specify whether to generate service-level policies. IAM Access Analyzer uses iam:servicelastaccessed to identify services that have been used recently to create this service-level template. */ includeServiceLevelTemplate?: Boolean; /** * The JobId that is returned by the StartPolicyGeneration operation. The JobId can be used with GetGeneratedPolicy to retrieve the generated policies or used with CancelPolicyGeneration to cancel the policy generation request. */ jobId: JobId; } export interface GetGeneratedPolicyResponse { /** * A GeneratedPolicyResult object that contains the generated policies and associated details. */ generatedPolicyResult: GeneratedPolicyResult; /** * A GeneratedPolicyDetails object that contains details about the generated policy. */ jobDetails: JobDetails; } export type GranteePrincipal = string; export interface IamRoleConfiguration { /** * The proposed trust policy for the IAM role. */ trustPolicy?: IamTrustPolicy; } export type IamTrustPolicy = string; export interface InlineArchiveRule { /** * The condition and values for a criterion. */ filter: FilterCriteriaMap; /** * The name of the rule. */ ruleName: Name; } export type InlineArchiveRulesList = InlineArchiveRule[]; export type Integer = number; export interface InternetConfiguration { } export type IssueCode = string; export type IssuingAccount = string; export interface JobDetails { /** * A timestamp of when the job was completed. */ completedOn?: Timestamp; /** * The job error for the policy generation request. */ jobError?: JobError; /** * The JobId that is returned by the StartPolicyGeneration operation. The JobId can be used with GetGeneratedPolicy to retrieve the generated policies or used with CancelPolicyGeneration to cancel the policy generation request. */ jobId: JobId; /** * A timestamp of when the job was started. */ startedOn: Timestamp; /** * The status of the job request. */ status: JobStatus; } export interface JobError { /** * The job error code. */ code: JobErrorCode; /** * Specific information about the error. For example, which service quota was exceeded or which resource was not found. */ message: String; } export type JobErrorCode = "AUTHORIZATION_ERROR"|"RESOURCE_NOT_FOUND_ERROR"|"SERVICE_QUOTA_EXCEEDED_ERROR"|"SERVICE_ERROR"|string; export type JobId = string; export type JobStatus = "IN_PROGRESS"|"SUCCEEDED"|"FAILED"|"CANCELED"|string; export type KmsConstraintsKey = string; export type KmsConstraintsMap = {[key: string]: KmsConstraintsValue}; export type KmsConstraintsValue = string; export interface KmsGrantConfiguration { /** * Use this structure to propose allowing cryptographic operations in the grant only when the operation request includes the specified encryption context. */ constraints?: KmsGrantConstraints; /** * The principal that is given permission to perform the operations that the grant permits. */ granteePrincipal: GranteePrincipal; /** * The Amazon Web Services account under which the grant was issued. The account is used to propose KMS grants issued by accounts other than the owner of the key. */ issuingAccount: IssuingAccount; /** * A list of operations that the grant permits. */ operations: KmsGrantOperationsList; /** * The principal that is given permission to retire the grant by using RetireGrant operation. */ retiringPrincipal?: RetiringPrincipal; } export type KmsGrantConfigurationsList = KmsGrantConfiguration[]; export interface KmsGrantConstraints { /** * A list of key-value pairs that must match the encryption context in the cryptographic operation request. The grant allows the operation only when the encryption context in the request is the same as the encryption context specified in this constraint. */ encryptionContextEquals?: KmsConstraintsMap; /** * A list of key-value pairs that must be included in the encryption context of the cryptographic operation request. The grant allows the cryptographic operation only when the encryption context in the request includes the key-value pairs specified in this constraint, although it can include additional key-value pairs. */ encryptionContextSubset?: KmsConstraintsMap; } export type KmsGrantOperation = "CreateGrant"|"Decrypt"|"DescribeKey"|"Encrypt"|"GenerateDataKey"|"GenerateDataKeyPair"|"GenerateDataKeyPairWithoutPlaintext"|"GenerateDataKeyWithoutPlaintext"|"GetPublicKey"|"ReEncryptFrom"|"ReEncryptTo"|"RetireGrant"|"Sign"|"Verify"|string; export type KmsGrantOperationsList = KmsGrantOperation[]; export interface KmsKeyConfiguration { /** * A list of proposed grant configurations for the KMS key. If the proposed grant configuration is for an existing key, the access preview uses the proposed list of grant configurations in place of the existing grants. Otherwise, the access preview uses the existing grants for the key. */ grants?: KmsGrantConfigurationsList; /** * Resource policy configuration for the KMS key. The only valid value for the name of the key policy is default. For more information, see Default key policy. */ keyPolicies?: KmsKeyPoliciesMap; } export type KmsKeyPoliciesMap = {[key: string]: KmsKeyPolicy}; export type KmsKeyPolicy = string; export type LearnMoreLink = string; export interface ListAccessPreviewFindingsRequest { /** * The unique ID for the access preview. */ accessPreviewId: AccessPreviewId; /** * The ARN of the analyzer used to generate the access. */ analyzerArn: AnalyzerArn; /** * Criteria to filter the returned findings. */ filter?: FilterCriteriaMap; /** * The maximum number of results to return in the response. */ maxResults?: Integer; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListAccessPreviewFindingsResponse { /** * A list of access preview findings that match the specified filter criteria. */ findings: AccessPreviewFindingsList; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListAccessPreviewsRequest { /** * The ARN of the analyzer used to generate the access preview. */ analyzerArn: AnalyzerArn; /** * The maximum number of results to return in the response. */ maxResults?: Integer; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListAccessPreviewsResponse { /** * A list of access previews retrieved for the analyzer. */ accessPreviews: AccessPreviewsList; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListAnalyzedResourcesRequest { /** * The ARN of the analyzer to retrieve a list of analyzed resources from. */ analyzerArn: AnalyzerArn; /** * The maximum number of results to return in the response. */ maxResults?: Integer; /** * A token used for pagination of results returned. */ nextToken?: Token; /** * The type of resource. */ resourceType?: ResourceType; } export interface ListAnalyzedResourcesResponse { /** * A list of resources that were analyzed. */ analyzedResources: AnalyzedResourcesList; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListAnalyzersRequest { /** * The maximum number of results to return in the response. */ maxResults?: Integer; /** * A token used for pagination of results returned. */ nextToken?: Token; /** * The type of analyzer. */ type?: Type; } export interface ListAnalyzersResponse { /** * The analyzers retrieved. */ analyzers: AnalyzersList; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListArchiveRulesRequest { /** * The name of the analyzer to retrieve rules from. */ analyzerName: Name; /** * The maximum number of results to return in the request. */ maxResults?: Integer; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListArchiveRulesResponse { /** * A list of archive rules created for the specified analyzer. */ archiveRules: ArchiveRulesList; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListFindingsRequest { /** * The ARN of the analyzer to retrieve findings from. */ analyzerArn: AnalyzerArn; /** * A filter to match for the findings to return. */ filter?: FilterCriteriaMap; /** * The maximum number of results to return in the response. */ maxResults?: Integer; /** * A token used for pagination of results returned. */ nextToken?: Token; /** * The sort order for the findings returned. */ sort?: SortCriteria; } export interface ListFindingsResponse { /** * A list of findings retrieved from the analyzer that match the filter criteria specified, if any. */ findings: FindingsList; /** * A token used for pagination of results returned. */ nextToken?: Token; } export interface ListPolicyGenerationsRequest { /** * The maximum number of results to return in the response. */ maxResults?: ListPolicyGenerationsRequestMaxResultsInteger; /** * A token used for pagination of results returned. */ nextToken?: Token; /** * The ARN of the IAM entity (user or role) for which you are generating a policy. Use this with ListGeneratedPolicies to filter the results to only include results for a specific principal. */ principalArn?: PrincipalArn; } export type ListPolicyGenerationsRequestMaxResultsInteger = number; export interface ListPolicyGenerationsResponse { /** * A token used for pagination of results returned. */ nextToken?: Token; /** * A PolicyGeneration object that contains details about the generated policy. */ policyGenerations: PolicyGenerationList; } export interface ListTagsForResourceRequest { /** * The ARN of the resource to retrieve tags from. */ resourceArn: String; } export interface ListTagsForResourceResponse { /** * The tags that are applied to the specified resource. */ tags?: TagsMap; } export type Locale = "DE"|"EN"|"ES"|"FR"|"IT"|"JA"|"KO"|"PT_BR"|"ZH_CN"|"ZH_TW"|string; export interface Location { /** * A path in a policy, represented as a sequence of path elements. */ path: PathElementList; /** * A span in a policy. */ span: Span; } export type LocationList = Location[]; export type Name = string; export interface NetworkOriginConfiguration { /** * The configuration for the Amazon S3 access point or multi-region access point with an Internet origin. */ internetConfiguration?: InternetConfiguration; vpcConfiguration?: VpcConfiguration; } export type OrderBy = "ASC"|"DESC"|string; export interface PathElement { /** * Refers to an index in a JSON array. */ index?: Integer; /** * Refers to a key in a JSON object. */ key?: String; /** * Refers to a substring of a literal string in a JSON object. */ substring?: Substring; /** * Refers to the value associated with a given key in a JSON object. */ value?: String; } export type PathElementList = PathElement[]; export type PolicyDocument = string; export interface PolicyGeneration { /** * A timestamp of when the policy generation was completed. */ completedOn?: Timestamp; /** * The JobId that is returned by the StartPolicyGeneration operation. The JobId can be used with GetGeneratedPolicy to retrieve the generated policies or used with CancelPolicyGeneration to cancel the policy generation request. */ jobId: JobId; /** * The ARN of the IAM entity (user or role) for which you are generating a policy. */ principalArn: PrincipalArn; /** * A timestamp of when the policy generation started. */ startedOn: Timestamp; /** * The status of the policy generation request. */ status: JobStatus; } export interface PolicyGenerationDetails { /** * The ARN of the IAM entity (user or role) for which you are generating a policy. */ principalArn: PrincipalArn; } export type PolicyGenerationList = PolicyGeneration[]; export type PolicyName = string; export type PolicyType = "IDENTITY_POLICY"|"RESOURCE_POLICY"|"SERVICE_CONTROL_POLICY"|string; export interface Position { /** * The column of the position, starting from 0. */ column: Integer; /** * The line of the position, starting from 1. */ line: Integer; /** * The offset within the policy that corresponds to the position, starting from 0. */ offset: Integer; } export type PrincipalArn = string; export type PrincipalMap = {[key: string]: String}; export type ReasonCode = "AWS_SERVICE_ACCESS_DISABLED"|"DELEGATED_ADMINISTRATOR_DEREGISTERED"|"ORGANIZATION_DELETED"|"SERVICE_LINKED_ROLE_CREATION_FAILED"|string; export type RegionList = String[]; export type ResourceArn = string; export type ResourceType = "AWS::S3::Bucket"|"AWS::IAM::Role"|"AWS::SQS::Queue"|"AWS::Lambda::Function"|"AWS::Lambda::LayerVersion"|"AWS::KMS::Key"|"AWS::SecretsManager::Secret"|string; export type RetiringPrincipal = string; export type RoleArn = string; export interface S3AccessPointConfiguration { /** * The access point or multi-region access point policy. */ accessPointPolicy?: AccessPointPolicy; /** * The proposed Internet and VpcConfiguration to apply to this Amazon S3 access point. VpcConfiguration does not apply to multi-region access points. If the access preview is for a new resource and neither is specified, the access preview uses Internet for the network origin. If the access preview is for an existing resource and neither is specified, the access preview uses the exiting network origin. */ networkOrigin?: NetworkOriginConfiguration; /** * The proposed S3PublicAccessBlock configuration to apply to this Amazon S3 access point or multi-region access point. */ publicAccessBlock?: S3PublicAccessBlockConfiguration; } export type S3AccessPointConfigurationsMap = {[key: string]: S3AccessPointConfiguration}; export interface S3BucketAclGrantConfiguration { /** * The grantee to whom you’re assigning access rights. */ grantee: AclGrantee; /** * The permissions being granted. */ permission: AclPermission; } export type S3BucketAclGrantConfigurationsList = S3BucketAclGrantConfiguration[]; export interface S3BucketConfiguration { /** * The configuration of Amazon S3 access points or multi-region access points for the bucket. You can propose up to 10 new access points per bucket. */ accessPoints?: S3AccessPointConfigurationsMap; /** * The proposed list of ACL grants for the Amazon S3 bucket. You can propose up to 100 ACL grants per bucket. If the proposed grant configuration is for an existing bucket, the access preview uses the proposed list of grant configurations in place of the existing grants. Otherwise, the access preview uses the existing grants for the bucket. */ bucketAclGrants?: S3BucketAclGrantConfigurationsList; /** * The proposed bucket policy for the Amazon S3 bucket. */ bucketPolicy?: S3BucketPolicy; /** * The proposed block public access configuration for the Amazon S3 bucket. */ bucketPublicAccessBlock?: S3PublicAccessBlockConfiguration; } export type S3BucketPolicy = string; export interface S3PublicAccessBlockConfiguration { /** * Specifies whether Amazon S3 should ignore public ACLs for this bucket and objects in this bucket. */ ignorePublicAcls: Boolean; /** * Specifies whether Amazon S3 should restrict public bucket policies for this bucket. */ restrictPublicBuckets: Boolean; } export interface SecretsManagerSecretConfiguration { /** * The proposed ARN, key ID, or alias of the KMS customer master key (CMK). */ kmsKeyId?: SecretsManagerSecretKmsId; /** * The proposed resource policy defining who can access or manage the secret. */ secretPolicy?: SecretsManagerSecretPolicy; } export type SecretsManagerSecretKmsId = string; export type SecretsManagerSecretPolicy = string; export type SharedViaList = String[]; export interface SortCriteria { /** * The name of the attribute to sort on. */ attributeName?: String; /** * The sort order, ascending or descending. */ orderBy?: OrderBy; } export interface Span { /** * The end position of the span (exclusive). */ end: Position; /** * The start position of the span (inclusive). */ start: Position; } export interface SqsQueueConfiguration { /** * The proposed resource policy for the Amazon SQS queue. */ queuePolicy?: SqsQueuePolicy; } export type SqsQueuePolicy = string; export interface StartPolicyGenerationRequest { /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, the subsequent retries with the same client token return the result from the original successful request and they have no additional effect. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. */ clientToken?: String; /** * A CloudTrailDetails object that contains details about a Trail that you want to analyze to generate policies. */ cloudTrailDetails?: CloudTrailDetails; /** * Contains the ARN of the IAM entity (user or role) for which you are generating a policy. */ policyGenerationDetails: PolicyGenerationDetails; } export interface StartPolicyGenerationResponse { /** * The JobId that is returned by the StartPolicyGeneration operation. The JobId can be used with GetGeneratedPolicy to retrieve the generated policies or used with CancelPolicyGeneration to cancel the policy generation request. */ jobId: JobId; } export interface StartResourceScanRequest { /** * The ARN of the analyzer to use to scan the policies applied to the specified resource. */ analyzerArn: AnalyzerArn; /** * The ARN of the resource to scan. */ resourceArn: ResourceArn; } export interface StatusReason { /** * The reason code for the current status of the analyzer. */ code: ReasonCode; } export type String = string; export interface Substring { /** * The length of the substring. */ length: Integer; /** * The start index of the substring, starting from 0. */ start: Integer; } export type TagKeys = String[]; export interface TagResourceRequest { /** * The ARN of the resource to add the tag to. */ resourceArn: String; /** * The tags to add to the resource. */ tags: TagsMap; } export interface TagResourceResponse { } export type TagsMap = {[key: string]: String}; export type Timestamp = Date; export type Token = string; export interface Trail { /** * Possible values are true or false. If set to true, IAM Access Analyzer retrieves CloudTrail data from all regions to analyze and generate a policy. */ allRegions?: Boolean; /** * Specifies the ARN of the trail. The format of a trail ARN is arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail. */ cloudTrailArn: CloudTrailArn; /** * A list of regions to get CloudTrail data from and analyze to generate a policy. */ regions?: RegionList; } export type TrailList = Trail[]; export interface TrailProperties { /** * Possible values are true or false. If set to true, IAM Access Analyzer retrieves CloudTrail data from all regions to analyze and generate a policy. */ allRegions?: Boolean; /** * Specifies the ARN of the trail. The format of a trail ARN is arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail. */ cloudTrailArn: CloudTrailArn; /** * A list of regions to get CloudTrail data from and analyze to generate a policy. */ regions?: RegionList; } export type TrailPropertiesList = TrailProperties[]; export type Type = "ACCOUNT"|"ORGANIZATION"|string; export interface UntagResourceRequest { /** * The ARN of the resource to remove the tag from. */ resourceArn: String; /** * The key for the tag to add. */ tagKeys: TagKeys; } export interface UntagResourceResponse { } export interface UpdateArchiveRuleRequest { /** * The name of the analyzer to update the archive rules for. */ analyzerName: Name; /** * A client token. */ clientToken?: String; /** * A filter to match for the rules to update. Only rules that match the filter are updated. */ filter: FilterCriteriaMap; /** * The name of the rule to update. */ ruleName: Name; } export interface UpdateFindingsRequest { /** * The ARN of the analyzer that generated the findings to update. */ analyzerArn: AnalyzerArn; /** * A client token. */ clientToken?: String; /** * The IDs of the findings to update. */ ids?: FindingIdList; /** * The ARN of the resource identified in the finding. */ resourceArn?: ResourceArn; /** * The state represents the action to take to update the finding Status. Use ARCHIVE to change an Active finding to an Archived finding. Use ACTIVE to change an Archived finding to an Active finding. */ status: FindingStatusUpdate; } export interface ValidatePolicyFinding { /** * A localized message that explains the finding and provides guidance on how to address it. */ findingDetails: String; /** * The impact of the finding. Security warnings report when the policy allows access that we consider overly permissive. Errors report when a part of the policy is not functional. Warnings report non-security issues when a policy does not conform to policy writing best practices. Suggestions recommend stylistic improvements in the policy that do not impact access. */ findingType: ValidatePolicyFindingType; /** * The issue code provides an identifier of the issue associated with this finding. */ issueCode: IssueCode; /** * A link to additional documentation about the type of finding. */ learnMoreLink: LearnMoreLink; /** * The list of locations in the policy document that are related to the finding. The issue code provides a summary of an issue identified by the finding. */ locations: LocationList; } export type ValidatePolicyFindingList = ValidatePolicyFinding[]; export type ValidatePolicyFindingType = "ERROR"|"SECURITY_WARNING"|"SUGGESTION"|"WARNING"|string; export interface ValidatePolicyRequest { /** * The locale to use for localizing the findings. */ locale?: Locale; /** * The maximum number of results to return in the response. */ maxResults?: Integer; /** * A token used for pagination of results returned. */ nextToken?: Token; /** * The JSON policy document to use as the content for the policy. */ policyDocument: PolicyDocument; /** * The type of policy to validate. Identity policies grant permissions to IAM principals. Identity policies include managed and inline policies for IAM roles, users, and groups. They also include service-control policies (SCPs) that are attached to an Amazon Web Services organization, organizational unit (OU), or an account. Resource policies grant permissions on Amazon Web Services resources. Resource policies include trust policies for IAM roles and bucket policies for Amazon S3 buckets. You can provide a generic input such as identity policy or resource policy or a specific input such as managed policy or Amazon S3 bucket policy. */ policyType: PolicyType; } export interface ValidatePolicyResponse { /** * The list of findings in a policy returned by IAM Access Analyzer based on its suite of policy checks. */ findings: ValidatePolicyFindingList; /** * A token used for pagination of results returned. */ nextToken?: Token; } export type ValueList = String[]; export interface VpcConfiguration { /** * If this field is specified, this access point will only allow connections from the specified VPC ID. */ vpcId: VpcId; } export type VpcId = 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 = "2019-11-01"|"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 AccessAnalyzer client. */ export import Types = AccessAnalyzer; } export = AccessAnalyzer;
the_stack
import ProxyEvent from "../../../../main/js/joynr/proxy/ProxyEvent"; import DiscoveryQos from "../../../../main/js/joynr/proxy/DiscoveryQos"; import MessagingQos from "../../../../main/js/joynr/messaging/MessagingQos"; import MulticastSubscriptionQos from "../../../../main/js/joynr/proxy/MulticastSubscriptionQos"; import DiscoveryEntryWithMetaInfo from "../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo"; import Version from "../../../../main/js/generated/joynr/types/Version"; import ProviderQos from "../../../../main/js/generated/joynr/types/ProviderQos"; import * as UtilInternal from "../../../../main/js/joynr/util/UtilInternal"; describe("libjoynr-js.joynr.proxy.ProxyEvent", () => { let weakSignal: any, broadcastWithoutFilterParameters: any; let subscriptionId: any; const subscriptionQos = new MulticastSubscriptionQos(); let subscriptionManagerSpy: any; let proxyParticipantId: any; let providerDiscoveryEntry: any; let broadcastName: string; beforeEach(done => { proxyParticipantId = "proxyParticipantId"; providerDiscoveryEntry = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 0, minorVersion: 23 }), domain: "testProviderDomain", interfaceName: "interfaceName", participantId: "providerParticipantId", qos: new ProviderQos({} as any), lastSeenDateMs: Date.now(), expiryDateMs: Date.now() + 60000, publicKeyId: "publicKeyId", isLocal: true }); const fakeProxy = { proxyParticipantId, providerDiscoveryEntry }; subscriptionManagerSpy = { registerBroadcastSubscription: jest.fn(), unregisterSubscription: jest.fn() }; subscriptionId = "subscriptionId"; subscriptionManagerSpy.registerBroadcastSubscription.mockReturnValue(Promise.resolve(subscriptionId)); subscriptionManagerSpy.unregisterSubscription.mockReturnValue(Promise.resolve()); broadcastName = "weakSignal"; weakSignal = new ProxyEvent(fakeProxy, { broadcastName, discoveryQos: new DiscoveryQos(), messagingQos: new MessagingQos(), dependencies: { subscriptionManager: subscriptionManagerSpy }, selective: true, filterParameters: { a: "reservedForTypeInfo", b: "reservedForTypeInfo", c: "reservedForTypeInfo" }, broadcastParameter: [] }); broadcastWithoutFilterParameters = new ProxyEvent(fakeProxy, { broadcastName, discoveryQos: new DiscoveryQos(), messagingQos: new MessagingQos(), dependencies: { subscriptionManager: subscriptionManagerSpy }, broadcastParameter: [] }); done(); }); it("selective broadcast without filter parameters works", done => { const filterParameterValues = { a: "valueForA" }; const broadcastFilterParameters = broadcastWithoutFilterParameters.createFilterParameters(); broadcastFilterParameters.filterParameters = filterParameterValues; expect(broadcastFilterParameters.filterParameters).toEqual(filterParameterValues); done(); }); it("is of correct type", done => { expect(weakSignal).toBeDefined(); expect(weakSignal).not.toBeNull(); expect(typeof weakSignal === "object").toBeTruthy(); expect(weakSignal instanceof ProxyEvent).toBeTruthy(); done(); }); it("has correct members", () => { expect(weakSignal.subscribe).toBeDefined(); expect(weakSignal.unsubscribe).toBeDefined(); }); it("subscribe calls subscriptionManager", async () => { const partitions = ["1", "2", "3"]; const onReceive = function() {}; const onError = function() {}; const onSubscribed = function() {}; const expectedPartitions = UtilInternal.extend([], partitions); const expectedSubscriptionQos = new MulticastSubscriptionQos(UtilInternal.extendDeep({}, subscriptionQos)); let expectedDiscoveryEntry: any = UtilInternal.extendDeep({}, providerDiscoveryEntry); expectedDiscoveryEntry.providerVersion = new Version(expectedDiscoveryEntry.providerVersion); expectedDiscoveryEntry.qos = new ProviderQos(expectedDiscoveryEntry.qos); expectedDiscoveryEntry = new DiscoveryEntryWithMetaInfo(expectedDiscoveryEntry); await weakSignal.subscribe({ subscriptionQos, partitions, onReceive, onError, onSubscribed }); expect(subscriptionManagerSpy.registerBroadcastSubscription).toHaveBeenCalled(); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].proxyId).toEqual( proxyParticipantId ); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].providerDiscoveryEntry).toEqual( expectedDiscoveryEntry ); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].broadcastName).toBe(broadcastName); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].subscriptionQos).toEqual( expect.objectContaining({ _typeName: expectedSubscriptionQos._typeName, expiryDateMs: expectedSubscriptionQos.expiryDateMs }) ); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].subscriptionId).toBeUndefined(); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].selective).toEqual(true); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].partitions).toEqual( expectedPartitions ); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].onError).toBe(onError); expect(subscriptionManagerSpy.registerBroadcastSubscription.mock.calls[0][0].onSubscribed).toBe(onSubscribed); }); it("subscribe provides a subscriptionId", async () => { const passedId = await weakSignal.subscribe({ subscriptionQos, onReceive() {} }); expect(passedId).toBeDefined(); expect(typeof passedId === "string").toBeTruthy(); }); it("subscribe and unsubscribe notify on success", async () => { // precondition: the broadcast object has already been created expect(weakSignal.subscribe).toBeDefined(); expect(typeof weakSignal.subscribe === "function").toBeTruthy(); expect(weakSignal.unsubscribe).toBeDefined(); expect(typeof weakSignal.unsubscribe === "function").toBeTruthy(); const passedSubscriptionId = await weakSignal.subscribe({ subscriptionQos, receive() {} }); return weakSignal.unsubscribe({ subscriptionId: passedSubscriptionId }); }); it("subscribe rejects if filter parameters are only partially filled", done => { subscriptionManagerSpy.registerBroadcastSubscription.mockReturnValue(Promise.resolve()); //subscribing without filter parameters should work weakSignal .subscribe({ subscriptionQos, receive() {} }) .then(() => { //subscribing with empty filter parameters should work return weakSignal.subscribe({ subscriptionQos, receive() {}, filterParameters: weakSignal.createFilterParameters() }); }) .then(() => { //subscribing with filter parameters having value null should work return weakSignal.subscribe({ subscriptionQos, receive() {} }); }) .then(() => { //subscribing with filter parameters having value null should work return weakSignal.subscribe({ subscriptionQos, receive() {}, filterParameters: null }); }) .then(() => { //subscribing with partially defined filter parameters should fail const filterParameters = weakSignal.createFilterParameters(); filterParameters.setA("a"); filterParameters.setB("b"); //do not set filter paramter "c", so assuming an error during subscribe return weakSignal .subscribe({ subscriptionQos, receive() {}, filterParameters }) .then(() => done.fail()) .catch(() => done()); }) .catch(() => done.fail()); }); it("subscribe notifies on failure", done => { // precondition: the broadcast object has already been created expect(weakSignal.subscribe).toBeDefined(); expect(typeof weakSignal.subscribe === "function").toBeTruthy(); const expectedError = new Error("error registering broadcast"); subscriptionManagerSpy.registerBroadcastSubscription.mockReturnValue(Promise.reject(expectedError)); weakSignal .subscribe({ subscriptionQos, receive() {} }) .then(() => done.fail()) .catch((error: any) => { expect(error).toEqual(expectedError); done(); }) .catch(() => done.fail()); }); it("unsubscribe notifies on failure", async () => { // precondition: the broadcast object has already been created expect(weakSignal.subscribe).toBeDefined(); expect(typeof weakSignal.subscribe === "function").toBeTruthy(); expect(weakSignal.unsubscribe).toBeDefined(); expect(typeof weakSignal.unsubscribe === "function").toBeTruthy(); const expectedError = new Error("error unsubscribing from broadcast"); subscriptionManagerSpy.unregisterSubscription.mockReturnValue(Promise.reject(expectedError)); const passedSubscriptionId = await weakSignal.subscribe({ subscriptionQos, receive() {} }); await expect( weakSignal.unsubscribe({ subscriptionId: passedSubscriptionId }) ).rejects.toBeInstanceOf(Error); }); it("throws error if subscribe is invoked with invalid partitions", () => { expect(() => { weakSignal.subscribe({ subscriptionQos, partitions: ["_"] }); }).toThrow(); expect(() => { weakSignal.subscribe({ subscriptionQos, partitions: ["./$"] }); }).toThrow(); }); });
the_stack
import { CSSInlineStyles } from "./cssTypes"; import { afterFrameCallback, beforeFrameCallback, beforeRenderCallback, reallyBeforeFrameCallback, RenderPhase, } from "./frameCallbacks"; import { isString, isNumber, isObject, isFunction, isArray } from "./isFunc"; import { assert, createTextNode, hOP, is, newHashObj, noop } from "./localHelpers"; // Bobril.Core export type IBobrilChild<T = any> = boolean | number | string | IBobrilNode<T> | null | undefined; export type IBobrilChildren = IBobrilChild | IBobrilChildArray; export interface IBobrilChildArray extends Array<IBobrilChildren> {} export type IBobrilCacheChildren = string | IBobrilCacheNode[] | undefined; export interface IDisposable { dispose(): void; } export type IDisposeFunction = (ctx?: any) => void; export type IDisposableLike = IDisposable | IDisposeFunction; export type MethodId = string | number; export interface IBobrilRoot { // Factory function f: (rootData: IBobrilRoot) => IBobrilChildren; // Root element e: HTMLElement | undefined; /// @deprecated Virtual Dom Cache - true cache is in n c: IBobrilCacheChildren; // Optional Logical parent p: IBobrilCacheNode | undefined; // Virtual Dom Cache Node n: IBobrilCacheNode | undefined; } export type ICtxClass<TData = any> = { new (data: TData, me: IBobrilCacheNode<TData>): BobrilCtx<TData>; }; export type IBobrilRoots = { [id: string]: IBobrilRoot }; export interface IBobrilAttributes { id?: string; href?: string; value?: boolean | string | string[] | IProp<boolean | string | string[]>; tabindex?: number; tabIndex?: never; [name: string]: any; } export interface IEventParam { target: IBobrilCacheNode; } export interface IBubblingAndBroadcastEvents { onInput?(event: IInputEvent): GenericEventResult; } /// These events could be used with `useEvent` or `useCaptureEvent` export interface IHookableEvents extends IBubblingAndBroadcastEvents { /// called on string input element when selection or caret position changes onSelectionChange?(event: ISelectionChangeEvent): GenericEventResult; onFocus?(event: IEventParam): GenericEventResult; onBlur?(event: IEventParam): GenericEventResult; } /// These events could be used with `useCaptureEvents` export interface ICapturableEvents extends IHookableEvents { onScroll?(event: IBobrilScroll): GenericEventResult; } export interface IBobrilEvents extends IBubblingAndBroadcastEvents { /// called on input element after any change with new value (string|boolean|string[]) - it does NOT bubble, use onInput if need bubbling onChange?(value: any): void; /// called on string input element when selection or caret position changes (void result is just for backward compatibility, bubbling) onSelectionChange?(event: ISelectionChangeEvent): void | GenericEventResult; // focus moved from outside of this element to some child of this element onFocusIn?(): void; // focus moved from inside of this element to some outside element onFocusOut?(): void; /// void result is for barward compatibility, it is bubbled onFocus?(event: IEventParam): void | GenericEventResult; /// void result is for barward compatibility, it is bubbled onBlur?(event: IEventParam): void | GenericEventResult; } export type IBobrilEventsWithCtx<TCtx> = { [N in keyof IBobrilEvents]?: NonNullable<IBobrilEvents[N]> extends (...args: any) => any ? Parameters<NonNullable<IBobrilEvents[N]>>["length"] extends 0 ? (ctx: TCtx) => ReturnType<NonNullable<IBobrilEvents[N]>> : ( ctx: TCtx, event: Parameters<NonNullable<IBobrilEvents[N]>>[0] ) => ReturnType<NonNullable<IBobrilEvents[N]>> : never; }; export interface IBobrilComponent<TData = any, TCtx extends IBobrilCtx<TData> = any> extends IBobrilEventsWithCtx<TCtx> { /// parent component of derived/overriding component super?: IBobrilComponent; /// if id of old node is different from new node it is considered completely different so init will be called before render directly /// it does prevent calling render method twice on same node id?: string; /// original function or component src?: any; ctxClass?: ICtxClass<TData>; /// called before new node in virtual dom should be created, me members (tag, attrs, children, ...) could be modified, ctx is initialized to { data: me.data||{}, me: me, cfg: fromParent } init?(ctx: IBobrilCtx<TData>, me: IBobrilCacheNode): void; /// in case of update after shouldChange returns true, you can do any update/init tasks, ctx.data is updated to me.data and oldMe.component updated to me.component before calling this /// in case of init this is called after init method, oldMe is equal to undefined in that case render?(ctx: IBobrilCtx<TData>, me: IBobrilNode, oldMe?: IBobrilCacheNode): void; /// called after all children are rendered, but before updating own attrs /// so this is useful for kind of layout in JS features postRender?(ctx: IBobrilCtx<TData>, me: IBobrilNode, oldMe?: IBobrilCacheNode): void; /// return false when whole subtree should not be changed from last time, you can still update any me members except key, default implementation always return true shouldChange?(ctx: IBobrilCtx<TData>, me: IBobrilNode, oldMe: IBobrilCacheNode): boolean; /// called from children to parents order for new nodes postInitDom?(ctx: IBobrilCtx<TData>, me: IBobrilCacheNode, element: HTMLElement): void; /// called from children to parents order for updated nodes postUpdateDom?(ctx: IBobrilCtx<TData>, me: IBobrilCacheNode, element: HTMLElement): void; /// called from children to parents order for updated nodes but in every frame even when render was not run postUpdateDomEverytime?(ctx: IBobrilCtx<TData>, me: IBobrilCacheNode, element: HTMLElement): void; /// called just before removing node from dom destroy?(ctx: IBobrilCtx<TData>, me: IBobrilNode, element: HTMLElement): void; /// called when bubbling event to parent so you could stop bubbling without preventing default handling shouldStopBubble?(ctx: IBobrilCtx<TData>, name: string, param: Object): boolean; /// called when broadcast wants to dive in this node so you could silence broadcast for you and your children shouldStopBroadcast?(ctx: IBobrilCtx<TData>, name: string, param: Object): boolean; /// used to implement any instance method which will be search by runMethodFrom using wave kind of broadcast stopping on first method returning true runMethod?(ctx: IBobrilCtx<TData>, methodId: MethodId, param?: Object): boolean; } export type RefType = | [IBobrilCtx, string] | ((node: IBobrilCacheNode | undefined) => void) | { current: IBobrilCacheNode | undefined }; // new node should at least have tag or component or children member export interface IBobrilNodeCommon<T = any> { tag?: string; key?: string; className?: string; style?: Record<string, string | number | undefined> | (() => IBobrilStyle); attrs?: IBobrilAttributes; children?: IBobrilChildren; ref?: RefType; /// set this for children to be set to their ctx.cfg, if undefined your own ctx.cfg will be used anyway; but better to use `extendCfg` cfg?: any; component?: IBobrilComponent<T>; // Bobril does not touch this, it is completely for user passing custom data to component // It is very similar to props in ReactJs, it must be immutable, you have access to this through ctx.data data?: T; /// Forbid array like objects to be IBobrilNode, use IBobrilChildren instead length?: never; } /// VDom node which Bobril will render and expand into IBobrilCacheNode export type IBobrilNode<T = any> = Exclude<IBobrilNodeCommon<T> & object, Function>; export interface IBobrilNodeWithKey<T = any> extends IBobrilNode<T> { key: string; } /// remembered and rendered VDom node export interface IBobrilCacheNode<T = any> { readonly tag: string | undefined; readonly key: string | undefined; readonly className: string | undefined; readonly style: Record<string, string | undefined> | undefined; readonly ctxStyle: IBobrilCtx<IBobrilStyles> | undefined; readonly attrs: IBobrilAttributes | undefined; readonly children: IBobrilCacheChildren; readonly ref: RefType | undefined; readonly cfg: any; readonly component: IBobrilComponent<T>; readonly data: T; readonly element: Node | Node[] | undefined; readonly parent: IBobrilCacheNode | undefined; readonly ctx: IBobrilCtx | undefined; /// Originally created or updated from - used for partial updates readonly orig: IBobrilNode<T>; } /// There are not many reasons why client code should be allowed to modify VDom, that's why it is called Unsafe. export type IBobrilCacheNodeUnsafe<T = any> = { -readonly [P in keyof IBobrilCacheNode<T>]: IBobrilCacheNode<T>[P] }; export interface IBobrilCtx<TData = any> { // properties passed from parent component, treat it as immutable data: TData; me: IBobrilCacheNode<TData>; // properties passed from parent component automatically, but could be extended for children to IBobrilNode.cfg cfg: any | undefined; refs: { [name: string]: IBobrilCacheNode | undefined } | undefined; disposables: IDisposableLike[] | undefined; } type HookFlags = number; const hasPostInitDom: HookFlags = 1; const hasPostUpdateDom: HookFlags = 2; const hasPostUpdateDomEverytime: HookFlags = 4; const hasEvents: HookFlags = 8; const hasCaptureEvents: HookFlags = 16; const hasUseEffect: HookFlags = 32; interface IBobrilCtxInternal<TData = any> extends IBobrilCtx<TData> { $hookFlags: HookFlags; $hooks: any[] | undefined; $bobxCtx: object | undefined; } export class BobrilCtx<TData> implements IBobrilCtxInternal { constructor(data?: TData, me?: IBobrilCacheNode<TData>) { this.data = data!; this.me = me!; this.cfg = undefined; this.refs = undefined; this.disposables = undefined; this.$hookFlags = 0; this.$hooks = undefined; this.$bobxCtx = undefined; } data: TData; me: IBobrilCacheNode<TData>; cfg: any | undefined; refs: { [name: string]: IBobrilCacheNode | undefined } | undefined; disposables: IDisposableLike[] | undefined; $hookFlags: HookFlags; $hooks: any[] | undefined; $bobxCtx: object | undefined; } export interface IBobrilScroll { node: IBobrilCacheNode | undefined; } export interface ISelectionChangeEvent extends IEventParam { startPosition: number; // endPosition tries to be also caret position (does not work on any IE or Edge 12) endPosition: number; } declare var DEBUG: boolean; var isArrayVdom = isArray; export function setIsArrayVdom( isArrayFnc: <T>( arg: T | {} ) => arg is T extends readonly any[] ? (unknown extends T ? never : readonly any[]) : any[] ) { isArrayVdom = isArrayFnc; } const emptyObject = {}; if (DEBUG) Object.freeze(emptyObject); function createEl(name: string): HTMLElement { return document.createElement(name); } export function assertNever(switchValue: never): never { throw new Error("Switch is not exhaustive for value: " + JSON.stringify(switchValue)); } export let assign = Object.assign; // PureFuncs: flatten export function flatten(a: any | any[]): any[] { if (!isArrayVdom(a)) { if (a == undefined || a === false || a === true) return []; return [a]; } a = a.slice(0); let aLen = a.length; for (let i = 0; i < aLen; ) { let item = a[i]; if (isArrayVdom(item)) { a.splice.apply(a, [i, 1].concat(item)); aLen = a.length; continue; } if (item == undefined || item === false || item === true) { a.splice(i, 1); aLen--; continue; } i++; } return a; } export function swallowPromise<T>(promise: Promise<T>): void { promise.catch((reason) => { console.error("Uncaught exception from swallowPromise", reason); }); } var inSvg: boolean = false; var inNotFocusable: boolean = false; var updateCall: Array<Function> = []; var updateInstance: Array<IBobrilCacheNode> = []; var effectInstance: Array<IBobrilCacheNode> = []; export function ieVersion() { return (<any>document).documentMode; } const focusableTag = /^input$|^select$|^textarea$|^button$/; const tabindexStr = "tabindex"; function isNaturallyFocusable(tag: string | undefined, attrs: IBobrilAttributes | undefined): boolean { if (tag == undefined) return false; if (focusableTag.test(tag)) return true; if (tag === "a" && attrs != null && attrs.href != null) return true; return false; } function updateElement( n: IBobrilCacheNode, el: Element, newAttrs: IBobrilAttributes | undefined, oldAttrs: IBobrilAttributes, notFocusable: boolean ): IBobrilAttributes { var attrName: string, newAttr: any, oldAttr: any, valueOldAttr: any, valueNewAttr: any; let wasTabindex = false; if (newAttrs != null) for (attrName in newAttrs) { newAttr = newAttrs[attrName]; oldAttr = oldAttrs[attrName]; if (notFocusable && attrName === tabindexStr) { newAttr = -1; wasTabindex = true; } else if (attrName === tValue && !inSvg) { if (isFunction(newAttr)) { oldAttrs[bValue] = newAttr; newAttr = newAttr(); } valueOldAttr = oldAttr; valueNewAttr = newAttr; oldAttrs[attrName] = newAttr; continue; } if (oldAttr !== newAttr) { oldAttrs[attrName] = newAttr; if (inSvg) { if (attrName === "href") el.setAttributeNS("http://www.w3.org/1999/xlink", "href", newAttr); else el.setAttribute(attrName, newAttr); } else if (attrName in el && !(attrName === "list" || attrName === "form")) { (<any>el)[attrName] = newAttr; } else el.setAttribute(attrName, newAttr); } } if (notFocusable && !wasTabindex && isNaturallyFocusable(n.tag, newAttrs)) { el.setAttribute(tabindexStr, "-1"); oldAttrs[tabindexStr] = -1; } if (newAttrs == undefined) { for (attrName in oldAttrs) { if (oldAttrs[attrName] !== undefined) { if (notFocusable && attrName === tabindexStr) continue; if (attrName === bValue) continue; oldAttrs[attrName] = undefined; el.removeAttribute(attrName); } } } else { for (attrName in oldAttrs) { if (oldAttrs[attrName] !== undefined && !(attrName in newAttrs)) { if (notFocusable && attrName === tabindexStr) continue; if (attrName === bValue) continue; oldAttrs[attrName] = undefined; el.removeAttribute(attrName); } } } if (valueNewAttr !== undefined) { setValueAttribute(el, n, valueNewAttr, valueOldAttr); } return oldAttrs; } function setValueAttribute(el: Element, node: IBobrilCacheNodeUnsafe, newValue: any, oldValue: any) { var tagName = el.tagName; var isSelect = tagName === "SELECT"; var isInput = tagName === "INPUT" || tagName === "TEXTAREA"; if (!isInput && !isSelect) { if (newValue !== oldValue) (<any>el)[tValue] = newValue; return; } if (node.ctx === undefined) { node.ctx = new BobrilCtx(undefined, node); node.component = emptyObject; } if (oldValue === undefined) { (<any>node.ctx)[bValue] = newValue; } var isMultiSelect = isSelect && (<HTMLSelectElement>el).multiple; var emitDiff = false; if (isMultiSelect) { var options = (<HTMLSelectElement>el).options; var currentMulti = selectedArray(options); if (!stringArrayEqual(newValue, currentMulti)) { if ( oldValue === undefined || stringArrayEqual(currentMulti, oldValue) || !stringArrayEqual(newValue, (<any>node.ctx)[bValue]) ) { for (var j = 0; j < options.length; j++) { options[j]!.selected = stringArrayContains(newValue, options[j]!.value); } currentMulti = selectedArray(options); if (stringArrayEqual(currentMulti, newValue)) { emitDiff = true; } } else { emitDiff = true; } } } else if (isInput || isSelect) { if (isInput && isCheckboxLike(<HTMLInputElement>el)) { var currentChecked = (<any>el).checked; if (newValue !== currentChecked) { if (oldValue === undefined || currentChecked === oldValue || newValue !== (<any>node.ctx)[bValue]) { (<any>el).checked = newValue; } else { emitDiff = true; } } } else { var isCombobox = isSelect && (<HTMLSelectElement>el).size < 2; var currentValue = (<any>el)[tValue]; if (newValue !== currentValue) { if (oldValue === undefined || currentValue === oldValue || newValue !== (<any>node.ctx)[bValue]) { if (isSelect) { if (newValue === "") { (<HTMLSelectElement>el).selectedIndex = isCombobox ? 0 : -1; } else { (<any>el)[tValue] = newValue; } if (newValue !== "" || isCombobox) { currentValue = (<any>el)[tValue]; if (newValue !== currentValue) { emitDiff = true; } } } else { (<any>el)[tValue] = newValue; } } else { emitDiff = true; } } } } if (emitDiff) { emitOnChange(undefined, el, node); } else { (<any>node.ctx)[bValue] = newValue; } } function pushInitCallback(c: IBobrilCacheNode) { var cc = c.component; if (cc) { let fn = cc[postInitDom]; if (fn) { updateCall.push(fn); updateInstance.push(c); } let flags = getHookFlags(c); if (flags & hasPostInitDom) { updateCall.push(hookPostInitDom); updateInstance.push(c); } if (flags & hasUseEffect) { effectInstance.push(c); } } else { var sctx = c.ctxStyle; if (sctx) { const flags = (sctx as IBobrilCtxInternal).$hookFlags | 0; if (flags & hasPostInitDom) { updateCall.push(hookPostInitDom); updateInstance.push(c); } if (flags & hasUseEffect) { effectInstance.push(c); } } } } function getHookFlags(c: IBobrilCacheNode<any>) { let flags = (c.ctx! as IBobrilCtxInternal).$hookFlags | 0; if (c.ctxStyle != undefined) flags = (c.ctxStyle as IBobrilCtxInternal).$hookFlags | flags; return flags; } function pushUpdateCallback(c: IBobrilCacheNode) { var cc = c.component; if (cc) { let fn = cc[postUpdateDom]; if (fn) { updateCall.push(fn); updateInstance.push(c); } let flags = getHookFlags(c); if (flags & hasPostUpdateDom) { updateCall.push(hookPostUpdateDom); updateInstance.push(c); } fn = cc[postUpdateDomEverytime]; if (fn) { updateCall.push(fn); updateInstance.push(c); } if (flags & hasPostUpdateDomEverytime) { updateCall.push(hookPostUpdateDomEverytime); updateInstance.push(c); } if (flags & hasUseEffect) { effectInstance.push(c); } } else { var sctx = c.ctxStyle; if (sctx) { const flags = (sctx as IBobrilCtxInternal).$hookFlags | 0; if (flags & hasPostUpdateDom) { updateCall.push(hookPostUpdateDom); updateInstance.push(c); } if (flags & hasPostUpdateDomEverytime) { updateCall.push(hookPostUpdateDomEverytime); updateInstance.push(c); } if (flags & hasUseEffect) { effectInstance.push(c); } } } } function pushUpdateEverytimeCallback(c: IBobrilCacheNode) { var cc = c.component; if (cc) { let fn = cc[postUpdateDomEverytime]; if (fn) { updateCall.push(fn); updateInstance.push(c); } if (getHookFlags(c) & hasPostUpdateDomEverytime) { updateCall.push(hookPostUpdateDomEverytime); updateInstance.push(c); } } else { var sctx = c.ctxStyle; if (sctx) { const flags = (sctx as IBobrilCtxInternal).$hookFlags | 0; if (flags & hasPostUpdateDomEverytime) { updateCall.push(hookPostUpdateDomEverytime); updateInstance.push(c); } } } } function findCfg(parent: IBobrilCacheNode | undefined): any { var cfg: any; while (parent) { cfg = parent.cfg; if (cfg !== undefined) break; if (parent.ctx !== undefined && parent.component !== emptyObject) { cfg = parent.ctx.cfg; break; } parent = parent.parent; } return cfg; } function setRef(ref: RefType | undefined, value: IBobrilCacheNode | undefined) { if (ref === undefined) return; if ("current" in ref) { ref.current = value; } else if (isFunction(ref)) { ref(value); } else if (isArray(ref)) { const ctx = ref[0]; let refs = ctx.refs; if (refs === undefined) { refs = newHashObj(); ctx.refs = refs; } refs[ref[1]] = value; } } let focusRootStack: IBobrilCacheNode[] = []; let focusRootTop: IBobrilCacheNode | null = null; export function registerFocusRoot(ctx: IBobrilCtx) { focusRootStack.push(ctx.me); addDisposable(ctx, unregisterFocusRoot); ignoreShouldChange(); } export function unregisterFocusRoot(ctx: IBobrilCtx) { let idx = focusRootStack.indexOf(ctx.me); if (idx !== -1) { focusRootStack.splice(idx, 1); ignoreShouldChange(); } } let createNodeStyle: ( el: HTMLElement, newStyle: Record<string, string | number | undefined> | (() => IBobrilStyles) | undefined, newClass: string | undefined, c: IBobrilCacheNode, inSvg: boolean ) => void; let updateNodeStyle: ( el: HTMLElement, newStyle: Record<string, string | number | undefined> | (() => IBobrilStyles) | undefined, newClass: string | undefined, c: IBobrilCacheNode, inSvg: boolean ) => void; let style: (node: IBobrilNode, ...styles: IBobrilStyles[]) => IBobrilNode; export function internalSetCssInJsCallbacks( create: ( el: HTMLElement, newStyle: Record<string, string | number | undefined> | (() => IBobrilStyles) | undefined, newClass: string | undefined, c: IBobrilCacheNode, inSvg: boolean ) => void, update: ( el: HTMLElement, newStyle: Record<string, string | number | undefined> | (() => IBobrilStyles) | undefined, newClass: string | undefined, c: IBobrilCacheNode, inSvg: boolean ) => void, s: (node: IBobrilNode, ...styles: IBobrilStyles[]) => IBobrilNode ) { createNodeStyle = create; updateNodeStyle = update; style = s; } let currentCtx: IBobrilCtx | undefined; let hookId = -1; export function getCurrentCtx() { return currentCtx; } export function setCurrentCtx(ctx: IBobrilCtx | undefined) { currentCtx = ctx; } let measureFullComponentDuration = false; let measureComponentMethods = false; export function setMeasureConfiguration(conf: { measureFullComponentDuration: boolean; measureComponentMethods: boolean; }) { measureFullComponentDuration = conf.measureFullComponentDuration; measureComponentMethods = conf.measureComponentMethods; } export function createNode( n: IBobrilNode, parentNode: IBobrilCacheNode | undefined, createInto: Element, createBefore: Node | null ): IBobrilCacheNode { var c = <IBobrilCacheNodeUnsafe>{ // This makes CacheNode just one object class = fast tag: n.tag, key: n.key, ref: n.ref, className: n.className, style: n.style, attrs: n.attrs, children: n.children, component: n.component, data: n.data, cfg: undefined, parent: parentNode, element: undefined, ctx: undefined, orig: n, }; var backupInSvg = inSvg; var backupInNotFocusable = inNotFocusable; var component = c.component; var el: Node | undefined; if (DEBUG && component && measureFullComponentDuration) { var componentStartMark = `create ${frameCounter} ${++visitedComponentCounter}`; window.performance.mark(componentStartMark); } setRef(c.ref, c); if (component) { var ctx: IBobrilCtxInternal; if (component.ctxClass) { ctx = new component.ctxClass(c.data || {}, c) as any; if (ctx.data === undefined) ctx.data = c.data || {}; if (ctx.me === undefined) ctx.me = c; } else { ctx = new BobrilCtx(c.data || {}, c); } ctx.cfg = n.cfg === undefined ? findCfg(parentNode) : n.cfg; c.ctx = ctx; currentCtx = ctx; if (component.init) { if (DEBUG && measureComponentMethods) window.performance.mark(`${component.id} init-start`); component.init(ctx, c); if (DEBUG && measureComponentMethods) window.performance.measure(`${component.id} [init]`, `${component.id} init-start`); } if (beforeRenderCallback !== noop) beforeRenderCallback(n, RenderPhase.Create); if (component.render) { hookId = 0; if (DEBUG && measureComponentMethods) window.performance.mark(`${component.id} render-start`); component.render(ctx, c); if (DEBUG && measureComponentMethods) window.performance.measure(`${component.id} [render]`, `${component.id} render-start`); hookId = -1; } currentCtx = undefined; } else { if (DEBUG) Object.freeze(n); } var tag = c.tag; if (tag === "-") { // Skip update c.tag = undefined; c.children = undefined; if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} create`, componentStartMark!); return c; } else if (tag === "@") { createInto = c.data; createBefore = null; tag = undefined; } var children = c.children; var inSvgForeignObject = false; if (isNumber(children)) { children = "" + children; c.children = children; } if (tag === undefined) { if (isString(children)) { el = createTextNode(<string>children); c.element = el; domNode2node.set(el, c); createInto.insertBefore(el, createBefore); } else { createChildren(c, createInto, createBefore); } if (component) { if (component.postRender) { if (DEBUG && measureComponentMethods) window.performance.mark(`${component.id} postRender-start`); component.postRender(c.ctx!, c); if (DEBUG && measureComponentMethods) window.performance.measure(`${component.id} [postRender]`, `${component.id} postRender-start`); } pushInitCallback(c); } if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} create`, componentStartMark!); return c; } if (tag === "/") { var htmlText = <string>children; if (htmlText === "") { // nothing needs to be created } else if (createBefore == undefined) { var before = createInto.lastChild as Node | null; (<HTMLElement>createInto).insertAdjacentHTML("beforeend", htmlText); c.element = <Node[]>[]; if (before) { before = before.nextSibling; } else { before = createInto.firstChild; } while (before) { domNode2node.set(before, c); (<Node[]>c.element).push(before); before = before.nextSibling; } } else { el = createBefore; var elPrev = createBefore.previousSibling; var removeEl = false; var parent = createInto; if (!(<HTMLElement>el).insertAdjacentHTML) { el = parent.insertBefore(createEl("i"), el); removeEl = true; } (<HTMLElement>el).insertAdjacentHTML("beforebegin", htmlText); if (elPrev) { elPrev = elPrev.nextSibling; } else { elPrev = parent.firstChild; } var newElements: Array<Node> = []; while (elPrev !== el) { domNode2node.set(elPrev!, c); newElements.push(elPrev!); elPrev = elPrev!.nextSibling; } c.element = newElements; if (removeEl) { parent.removeChild(el); } } if (component) { if (component.postRender) { if (DEBUG && measureComponentMethods) window.performance.mark(`${component.id} postRender-start`); component.postRender(c.ctx!, c); if (DEBUG && measureComponentMethods) window.performance.measure(`${component.id} [postRender]`, `${component.id} postRender-start`); } pushInitCallback(c); } if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} create`, componentStartMark!); return c; } if (inSvg || tag === "svg") { el = document.createElementNS("http://www.w3.org/2000/svg", tag); inSvgForeignObject = tag === "foreignObject"; inSvg = !inSvgForeignObject; } else { el = createEl(tag); } createInto.insertBefore(el, createBefore); domNode2node.set(el, c); c.element = el; createChildren(c, <Element>el, null); if (component) { if (component.postRender) { if (DEBUG && measureComponentMethods) window.performance.mark(`${component.id} postRender-start`); component.postRender(c.ctx!, c); if (DEBUG && measureComponentMethods) window.performance.measure(`${component.id} [postRender]`, `${component.id} postRender-start`); } } if (inNotFocusable && focusRootTop === c) inNotFocusable = false; if (inSvgForeignObject) inSvg = true; if (c.attrs || inNotFocusable) c.attrs = updateElement(c, <HTMLElement>el, c.attrs, {}, inNotFocusable); createNodeStyle(el as HTMLElement, c.style, enrichClassName(c, c.className), c, inSvg); inSvg = backupInSvg; inNotFocusable = backupInNotFocusable; pushInitCallback(c); if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} create`, componentStartMark!); return c; } export function applyDynamicStyle(factory: () => IBobrilStyles, c: IBobrilCacheNode): IBobrilNode { var ctxStyle = c.ctxStyle; var backupCtx = currentCtx; if (ctxStyle === undefined) { ctxStyle = new BobrilCtx(factory, c); (c as IBobrilCacheNodeUnsafe).ctxStyle = ctxStyle; currentCtx = ctxStyle; if (beforeRenderCallback !== noop) beforeRenderCallback(ctxStyle, RenderPhase.Create); } else { currentCtx = ctxStyle; if (beforeRenderCallback !== noop) beforeRenderCallback(ctxStyle, RenderPhase.Update); } hookId = 0; var s = factory(); hookId = -1; currentCtx = backupCtx; return style({}, s); } export function destroyDynamicStyle(c: IBobrilCacheNode) { let ctxStyle = c.ctxStyle; if (ctxStyle !== undefined) { currentCtx = ctxStyle; if (beforeRenderCallback !== noop) beforeRenderCallback(ctxStyle, RenderPhase.Destroy); let disposables = ctxStyle.disposables; if (isArray(disposables)) { for (let i = disposables.length; i-- > 0; ) { let d = disposables[i]!; if (isFunction(d)) d(ctxStyle); else d.dispose(); } } currentCtx = undefined; } } var keysInClassNames = false; export function setKeysInClassNames(value: boolean) { keysInClassNames = value; } function enrichClassName(c: IBobrilCacheNode, n: string | undefined): string | undefined { if (!keysInClassNames) return n; var add = ""; do { var k = c.key; if (k) add = " " + k + add; c = c.parent!; } while (c != undefined && c.element == undefined); if (n) return n + add; return add.substr(1); } function normalizeNode(n: any): IBobrilNode | undefined { if (n === false || n === true || n === null) return undefined; if (isString(n)) { return { children: n }; } if (isNumber(n)) { return { children: "" + n }; } return <IBobrilNode | undefined>n; } function createChildren(c: IBobrilCacheNodeUnsafe, createInto: Element, createBefore: Node | null): void { var ch = c.children; if (isString(ch)) { createInto.textContent = ch; return; } let res = <IBobrilCacheNode[]>[]; flattenVdomChildren(res, ch); for (let i = 0; i < res.length; i++) { res[i] = createNode(res[i]!, c, createInto, createBefore); } c.children = res; } function destroyNode(c: IBobrilCacheNode) { setRef(c.ref, undefined); let ch = c.children; if (isArray(ch)) { for (let i = 0, l = ch.length; i < l; i++) { destroyNode(ch[i]!); } } let component = c.component; if (component) { let ctx = c.ctx!; currentCtx = ctx; if (beforeRenderCallback !== noop) beforeRenderCallback(c, RenderPhase.Destroy); if (component.destroy) component.destroy(ctx, c, <HTMLElement>c.element); let disposables = ctx.disposables; if (isArray(disposables)) { for (let i = disposables.length; i-- > 0; ) { let d = disposables[i]!; if (isFunction(d)) d(ctx); else d.dispose(); } } currentCtx = undefined; } destroyDynamicStyle(c); if (c.tag === "@") { removeNodeRecursive(c); } } export function addDisposable(ctx: IBobrilCtx, disposable: IDisposableLike) { let disposables = ctx.disposables; if (disposables == undefined) { disposables = []; ctx.disposables = disposables; } disposables.push(disposable); } export function isDisposable(val: any): val is IDisposable { return isObject(val) && val["dispose"]; } function removeNodeRecursive(c: IBobrilCacheNode) { var el = c.element; if (isArray(el)) { var pa = (<Node[]>el)[0]!.parentNode; if (pa) { for (let i = 0; i < (<Node[]>el).length; i++) { pa.removeChild((<Node[]>el)[i]!); } } } else if (el != null) { let p = (<Node>el).parentNode; if (p) p.removeChild(<Node>el); } else { var ch = c.children; if (isArray(ch)) { for (var i = 0, l = (<IBobrilCacheNode[]>ch).length; i < l; i++) { removeNodeRecursive((<IBobrilCacheNode[]>ch)[i]!); } } } } function removeNode(c: IBobrilCacheNode) { destroyNode(c); removeNodeRecursive(c); } var roots: IBobrilRoots = newHashObj(); var domNode2node: WeakMap<Node, IBobrilCacheNode> = new WeakMap(); export function vdomPath(n: Node | null | undefined): IBobrilCacheNode[] { var res: IBobrilCacheNode[] = []; while (n != undefined) { var bn = domNode2node.get(n); if (bn !== undefined) { do { res.push(bn); bn = bn.parent; } while (bn !== undefined); res.reverse(); return res; } n = n.parentNode; } return res; } // PureFuncs: deref, getDomNode export function deref(n: Node | null | undefined): IBobrilCacheNode | undefined { while (n != undefined) { var bn = domNode2node.get(n); if (bn !== undefined) { return bn; } n = n.parentNode; } return undefined; } function finishUpdateNode(n: IBobrilNode, c: IBobrilCacheNodeUnsafe, component: IBobrilComponent | null | undefined) { if (component) { if (component.postRender) { currentCtx = c.ctx!; component.postRender(currentCtx, n, c); currentCtx = undefined; } } c.data = n.data; pushUpdateCallback(c); } function finishUpdateNodeWithoutChange(c: IBobrilCacheNode, createInto: Element, createBefore: Node | null) { currentCtx = undefined; if (isArray(c.children)) { const backupInSvg = inSvg; const backupInNotFocusable = inNotFocusable; if (c.tag === "svg") { inSvg = true; } else if (inSvg && c.tag === "foreignObject") inSvg = false; if (inNotFocusable && focusRootTop === c) inNotFocusable = false; selectedUpdate( <IBobrilCacheNode[]>c.children, <Element>c.element || createInto, c.element != null ? null : createBefore ); inSvg = backupInSvg; inNotFocusable = backupInNotFocusable; } pushUpdateEverytimeCallback(c); } export function updateNode( n: IBobrilNode, c: IBobrilCacheNode, createInto: Element, createBefore: Node | null, deepness: number, inSelectedUpdate?: boolean ): IBobrilCacheNode { var component = n.component; var bigChange = false; var ctx = c.ctx; if (DEBUG && component && measureFullComponentDuration) { var componentStartMark = `update ${frameCounter} ${++visitedComponentCounter}`; window.performance.mark(componentStartMark); } if (component != null && ctx != null) { let locallyInvalidated = false; if ((<any>ctx)[ctxInvalidated] >= frameCounter) { deepness = Math.max(deepness, (<any>ctx)[ctxDeepness]); locallyInvalidated = true; } if (component.id !== c.component.id) { bigChange = true; } else { currentCtx = ctx; if (n.cfg !== undefined) ctx.cfg = n.cfg; else ctx.cfg = findCfg(c.parent); if (component.shouldChange) if (!ignoringShouldChange && !locallyInvalidated) { if (DEBUG && measureComponentMethods) window.performance.mark(`${component.id} shouldChange-start`); const shouldChange = component.shouldChange(ctx, n, c); if (DEBUG && measureComponentMethods) window.performance.measure( `${component.id} [shouldChange]`, `${component.id} shouldChange-start` ); if (!shouldChange) { finishUpdateNodeWithoutChange(c, createInto, createBefore); if (DEBUG && measureFullComponentDuration) window.performance.measure(`${component.id} update`, componentStartMark!); return c; } } (<any>ctx).data = n.data || {}; (c as IBobrilCacheNodeUnsafe).component = component; if (beforeRenderCallback !== noop) beforeRenderCallback(n, inSelectedUpdate ? RenderPhase.LocalUpdate : RenderPhase.Update); if (component.render) { (c as IBobrilCacheNodeUnsafe).orig = n; n = assign({}, n); // need to clone me because it should not be modified for next updates (c as IBobrilCacheNodeUnsafe).cfg = undefined; if (n.cfg !== undefined) n.cfg = undefined; hookId = 0; if (DEBUG && measureComponentMethods) window.performance.mark(`${component.id} render-start`); component.render(ctx, n, c); if (DEBUG && measureComponentMethods) window.performance.measure(`${component.id} [render]`, `${component.id} render-start`); hookId = -1; if (n.cfg !== undefined) { if (c.cfg === undefined) (c as IBobrilCacheNodeUnsafe).cfg = n.cfg; else assign(c.cfg, n.cfg); } } currentCtx = undefined; } } else { // In case there is no component and source is same reference it is considered not changed if (c.orig === n && !ignoringShouldChange) { finishUpdateNodeWithoutChange(c, createInto, createBefore); if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} update`, componentStartMark!); return c; } (c as IBobrilCacheNodeUnsafe).orig = n; if (DEBUG) Object.freeze(n); } var newChildren = n.children; var cachedChildren = c.children; var tag = n.tag; if (tag === "-") { finishUpdateNodeWithoutChange(c, createInto, createBefore); if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} update`, componentStartMark!); return c; } const backupInSvg = inSvg; const backupInNotFocusable = inNotFocusable; if (isNumber(newChildren)) { newChildren = "" + newChildren; } if ( bigChange || (component != undefined && ctx == undefined) || (component == undefined && ctx != undefined && ctx.me.component !== emptyObject) ) { // it is big change of component.id or old one was not even component or old one was component and new is not anymore => recreate } else if (tag === "/") { if (c.tag === "/" && cachedChildren === newChildren) { finishUpdateNode(n, c, component); if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} update`, componentStartMark!); return c; } } else if (tag === c.tag) { if (tag === "@") { if (n.data !== c.data) { var r: IBobrilCacheNode = createNode(n, c.parent, n.data, null); removeNode(c); if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} update`, componentStartMark!); return r; } createInto = n.data; createBefore = getLastDomNode(c); if (createBefore != null) createBefore = createBefore.nextSibling; tag = undefined; } if (tag === undefined) { if (isString(newChildren) && isString(cachedChildren)) { if (newChildren !== cachedChildren) { var el = <Element>c.element; el.textContent = newChildren; (c as IBobrilCacheNodeUnsafe).children = newChildren; } } else { if (inNotFocusable && focusRootTop === c) inNotFocusable = false; if (deepness <= 0) { if (isArray(cachedChildren)) selectedUpdate(<IBobrilCacheNode[]>c.children, createInto, createBefore); } else { (c as IBobrilCacheNodeUnsafe).children = updateChildren( createInto, newChildren, cachedChildren, c, createBefore, deepness - 1 ); } inSvg = backupInSvg; inNotFocusable = backupInNotFocusable; } finishUpdateNode(n, c, component); if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} update`, componentStartMark!); return c; } else { var inSvgForeignObject = false; if (tag === "svg") { inSvg = true; } else if (inSvg && tag === "foreignObject") { inSvgForeignObject = true; inSvg = false; } if (inNotFocusable && focusRootTop === c) inNotFocusable = false; var el = <Element>c.element; if (isString(newChildren) && !isArray(cachedChildren)) { if (newChildren !== cachedChildren) { el.textContent = newChildren; cachedChildren = newChildren; } } else { if (deepness <= 0) { if (isArray(cachedChildren)) selectedUpdate(<IBobrilCacheNode[]>c.children, el, null); } else { cachedChildren = updateChildren(el, newChildren, cachedChildren, c, null, deepness - 1); } } (c as IBobrilCacheNodeUnsafe).children = cachedChildren; if (inSvgForeignObject) inSvg = true; finishUpdateNode(n, c, component); if (c.attrs || n.attrs || inNotFocusable) (c as IBobrilCacheNodeUnsafe).attrs = updateElement(c, el, n.attrs, c.attrs || {}, inNotFocusable); updateNodeStyle(el as HTMLElement, n.style, enrichClassName(c, n.className), c, inSvg); inSvg = backupInSvg; inNotFocusable = backupInNotFocusable; if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} update`, componentStartMark!); return c; } } var parEl = c.element; if (isArray(parEl)) parEl = parEl[0]; if (parEl == undefined) parEl = createInto; else parEl = <Element>parEl.parentNode; var r: IBobrilCacheNode = createNode(n, c.parent, <Element>parEl, getDomNode(c)); removeNode(c); if (DEBUG && component && measureFullComponentDuration) window.performance.measure(`${component.id} update`, componentStartMark!); return r; } export function getDomNode(c: IBobrilCacheNode | undefined): Node | null { if (c === undefined) return null; var el: Node | Node[] | null | undefined = c.element; if (el != null) { if (isArray(el)) return el[0]!; return el; } var ch = c.children; if (!isArray(ch)) return null; for (var i = 0; i < ch.length; i++) { el = getDomNode(ch[i]); if (el) return el; } return null; } export function getLastDomNode(c: IBobrilCacheNode | undefined): Node | null { if (c === undefined) return null; var el: Node | Node[] | null | undefined = c.element; if (el != null) { if (isArray(el)) return el[el.length - 1]!; return el; } var ch = c.children; if (!isArray(ch)) return null; for (var i = ch.length; i-- > 0; ) { el = getLastDomNode(ch[i]); if (el) return el; } return null; } function findNextNode(a: IBobrilCacheNode[], i: number, len: number, def: Node | null): Node | null { while (++i < len) { var ai = a[i]; if (ai == undefined) continue; var n = getDomNode(ai); if (n != null) return n; } return def; } export function callPostCallbacks() { var count = updateInstance.length; for (var i = 0; i < count; i++) { var n = updateInstance[i]!; currentCtx = n.ctx; if (currentCtx) { if (DEBUG && measureComponentMethods) window.performance.mark(`${n.component.id} post-start`); updateCall[i]!.call(n.component, currentCtx, n, n.element); if (DEBUG && measureComponentMethods) window.performance.measure(`${n.component.id} [post*]`, `${n.component.id} post-start`); } currentCtx = n.ctxStyle; if (currentCtx) { if (DEBUG && measureComponentMethods) window.performance.mark(`style post-start`); updateCall[i]!.call(n.component, currentCtx, n, n.element); if (DEBUG && measureComponentMethods) window.performance.measure(`style [post*]`, `style post-start`); } } currentCtx = undefined; updateCall = []; updateInstance = []; } export function callEffects() { var count = effectInstance.length; for (var i = 0; i < count; i++) { var n = effectInstance[i]!; currentCtx = n.ctx; if (currentCtx) { if (DEBUG && measureComponentMethods) window.performance.mark(`${n.component.id} effect-start`); const hooks = (currentCtx as IBobrilCtxInternal).$hooks!; const len = hooks.length; for (let i = 0; i < len; i++) { const hook = hooks[i]; const fn = hook.useEffect; if (fn !== undefined) { fn.call(hook, currentCtx); } } if (DEBUG && measureComponentMethods) window.performance.measure(`${n.component.id} [effect*]`, `${n.component.id} effect-start`); } currentCtx = n.ctxStyle; if (currentCtx) { if (DEBUG && measureComponentMethods) window.performance.mark(`style effect-start`); const hooks = (currentCtx as IBobrilCtxInternal).$hooks!; const len = hooks.length; for (let i = 0; i < len; i++) { const hook = hooks[i]; const fn = hook.useEffect; if (fn !== undefined) { fn.call(hook, currentCtx); } } if (DEBUG && measureComponentMethods) window.performance.measure(`style [effect*]`, `style effect-start`); } } currentCtx = undefined; effectInstance = []; } function updateNodeInUpdateChildren( newNode: IBobrilNode, cachedChildren: IBobrilCacheNode[], cachedIndex: number, cachedLength: number, createBefore: Node | null, element: Element, deepness: number ) { cachedChildren[cachedIndex] = updateNode( newNode, cachedChildren[cachedIndex]!, element, findNextNode(cachedChildren, cachedIndex, cachedLength, createBefore), deepness ); } function reorderInUpdateChildrenRec(c: IBobrilCacheNode, element: Element, before: Node | null): void { var el = c.element; if (el != null) { if (isArray(el)) { for (var i = 0; i < el.length; i++) { element.insertBefore(el[i]!, before); } } else element.insertBefore(el, before); return; } var ch = c.children; if (!isArray(ch)) return; for (var i = 0; i < (<IBobrilCacheNode[]>ch).length; i++) { reorderInUpdateChildrenRec((<IBobrilCacheNode[]>ch)[i]!, element, before); } } function reorderInUpdateChildren( cachedChildren: IBobrilCacheNode[], cachedIndex: number, cachedLength: number, createBefore: Node | null, element: Element ) { var before = findNextNode(cachedChildren, cachedIndex, cachedLength, createBefore); var cur = cachedChildren[cachedIndex]!; var what = getDomNode(cur); if (what != null && what !== before) { reorderInUpdateChildrenRec(cur, element, before); } } function reorderAndUpdateNodeInUpdateChildren( newNode: IBobrilNode, cachedChildren: IBobrilCacheNode[], cachedIndex: number, cachedLength: number, createBefore: Node | null, element: Element, deepness: number ) { var before = findNextNode(cachedChildren, cachedIndex, cachedLength, createBefore); var cur = cachedChildren[cachedIndex]!; var what = getDomNode(cur); if (what != null && what !== before) { reorderInUpdateChildrenRec(cur, element, before); } cachedChildren[cachedIndex] = updateNode(newNode, cur, element, before, deepness); } function recursiveFlattenVdomChildren(res: IBobrilNode[], children: IBobrilChildren) { if (children == undefined) return; if (isArrayVdom(children)) { for (let i = 0; i < children.length; i++) { recursiveFlattenVdomChildren(res, children[i]); } } else { let item = normalizeNode(children); if (item !== undefined) res.push(item); } } function flattenVdomChildren(res: IBobrilNode[], children: IBobrilChildren) { recursiveFlattenVdomChildren(res, children); if (DEBUG) { var set = new Set(); for (let i = 0; i < res.length; i++) { const key = res[i]!.key; if (key == undefined) continue; if (set.has(key)) { console.warn("Duplicate Bobril node key " + key); } set.add(key); } } } export function updateChildren( element: Element, newChildren: IBobrilChildren, cachedChildren: IBobrilCacheChildren, parentNode: IBobrilCacheNode | undefined, createBefore: Node | null, deepness: number ): IBobrilCacheNode[] { if (cachedChildren == undefined) cachedChildren = []; if (!isArray(cachedChildren)) { if (element.firstChild) element.removeChild(element.firstChild); cachedChildren = <any>[]; } let newCh = <IBobrilNode[]>[]; flattenVdomChildren(newCh, newChildren); return updateChildrenCore( element, <IBobrilNode[]>newCh, <IBobrilCacheNode[]>cachedChildren, parentNode, createBefore, deepness ); } function updateChildrenCore( element: Element, newChildren: IBobrilNode[], cachedChildren: IBobrilCacheNode[], parentNode: IBobrilCacheNode | undefined, createBefore: Node | null, deepness: number ): IBobrilCacheNode[] { let newEnd = newChildren.length; var cachedLength = cachedChildren.length; let cachedEnd = cachedLength; let newIndex = 0; let cachedIndex = 0; while (newIndex < newEnd && cachedIndex < cachedEnd) { if (newChildren[newIndex]!.key === cachedChildren[cachedIndex]!.key) { updateNodeInUpdateChildren( newChildren[newIndex]!, cachedChildren, cachedIndex, cachedLength, createBefore, element, deepness ); newIndex++; cachedIndex++; continue; } while (true) { if (newChildren[newEnd - 1]!.key === cachedChildren[cachedEnd - 1]!.key) { newEnd--; cachedEnd--; updateNodeInUpdateChildren( newChildren[newEnd]!, cachedChildren, cachedEnd, cachedLength, createBefore, element, deepness ); if (newIndex < newEnd && cachedIndex < cachedEnd) continue; } break; } if (newIndex < newEnd && cachedIndex < cachedEnd) { if (newChildren[newIndex]!.key === cachedChildren[cachedEnd - 1]!.key) { cachedChildren.splice(cachedIndex, 0, cachedChildren[cachedEnd - 1]!); cachedChildren.splice(cachedEnd, 1); reorderAndUpdateNodeInUpdateChildren( newChildren[newIndex]!, cachedChildren, cachedIndex, cachedLength, createBefore, element, deepness ); newIndex++; cachedIndex++; continue; } if (newChildren[newEnd - 1]!.key === cachedChildren[cachedIndex]!.key) { cachedChildren.splice(cachedEnd, 0, cachedChildren[cachedIndex]!); cachedChildren.splice(cachedIndex, 1); cachedEnd--; newEnd--; reorderAndUpdateNodeInUpdateChildren( newChildren[newEnd]!, cachedChildren, cachedEnd, cachedLength, createBefore, element, deepness ); continue; } } break; } if (cachedIndex === cachedEnd) { if (newIndex === newEnd) { return cachedChildren; } // Only work left is to add new nodes while (newIndex < newEnd) { cachedChildren.splice( cachedIndex, 0, createNode( newChildren[newIndex]!, parentNode, element, findNextNode(cachedChildren, cachedIndex - 1, cachedLength, createBefore) ) ); cachedIndex++; cachedEnd++; cachedLength++; newIndex++; } return cachedChildren; } if (newIndex === newEnd) { // Only work left is to remove old nodes while (cachedIndex < cachedEnd) { cachedEnd--; removeNode(cachedChildren[cachedEnd]!); cachedChildren.splice(cachedEnd, 1); } return cachedChildren; } // order of keyed nodes ware changed => reorder keyed nodes first var cachedKeys: { [keyName: string]: number } = newHashObj(); var newKeys: { [keyName: string]: number } = newHashObj(); var key: string | undefined; var node: IBobrilNode; var backupNewIndex = newIndex; var backupCachedIndex = cachedIndex; var deltaKeyless = 0; for (; cachedIndex < cachedEnd; cachedIndex++) { node = cachedChildren[cachedIndex]!; key = node.key; if (key != null) { assert(!(key in <any>cachedKeys)); cachedKeys[key] = cachedIndex; } else deltaKeyless--; } var keyLess = -deltaKeyless - deltaKeyless; for (; newIndex < newEnd; newIndex++) { node = newChildren[newIndex]!; key = node.key; if (key != null) { assert(!(key in <any>newKeys)); newKeys[key] = newIndex; } else deltaKeyless++; } keyLess += deltaKeyless; var delta = 0; newIndex = backupNewIndex; cachedIndex = backupCachedIndex; var cachedKey: string | undefined; while (cachedIndex < cachedEnd && newIndex < newEnd) { if (cachedChildren[cachedIndex] === null) { // already moved somewhere else cachedChildren.splice(cachedIndex, 1); cachedEnd--; cachedLength--; delta--; continue; } cachedKey = cachedChildren[cachedIndex]!.key; if (cachedKey == undefined) { cachedIndex++; continue; } key = newChildren[newIndex]!.key; if (key == undefined) { newIndex++; while (newIndex < newEnd) { key = newChildren[newIndex]!.key; if (key != undefined) break; newIndex++; } if (key == undefined) break; } var akPos = cachedKeys[key]; if (akPos === undefined) { // New key cachedChildren.splice( cachedIndex, 0, createNode( newChildren[newIndex]!, parentNode, element, findNextNode(cachedChildren, cachedIndex - 1, cachedLength, createBefore) ) ); delta++; newIndex++; cachedIndex++; cachedEnd++; cachedLength++; continue; } if (!(cachedKey in <any>newKeys)) { // Old key removeNode(cachedChildren[cachedIndex]!); cachedChildren.splice(cachedIndex, 1); delta--; cachedEnd--; cachedLength--; continue; } if (cachedIndex === akPos + delta) { // In-place update updateNodeInUpdateChildren( newChildren[newIndex]!, cachedChildren, cachedIndex, cachedLength, createBefore, element, deepness ); newIndex++; cachedIndex++; } else { // Move cachedChildren.splice(cachedIndex, 0, cachedChildren[akPos + delta]!); delta++; cachedChildren[akPos + delta] = null!; reorderAndUpdateNodeInUpdateChildren( newChildren[newIndex]!, cachedChildren, cachedIndex, cachedLength, createBefore, element, deepness ); cachedIndex++; cachedEnd++; cachedLength++; newIndex++; } } // remove old keyed cached nodes while (cachedIndex < cachedEnd) { if (cachedChildren[cachedIndex] === null) { // already moved somewhere else cachedChildren.splice(cachedIndex, 1); cachedEnd--; cachedLength--; continue; } if (cachedChildren[cachedIndex]!.key != null) { // this key is only in old removeNode(cachedChildren[cachedIndex]!); cachedChildren.splice(cachedIndex, 1); cachedEnd--; cachedLength--; continue; } cachedIndex++; } // add new keyed nodes while (newIndex < newEnd) { key = newChildren[newIndex]!.key; if (key != null) { cachedChildren.splice( cachedIndex, 0, createNode( newChildren[newIndex]!, parentNode, element, findNextNode(cachedChildren, cachedIndex - 1, cachedLength, createBefore) ) ); cachedEnd++; cachedLength++; delta++; cachedIndex++; } newIndex++; } // Without any keyless nodes we are done if (!keyLess) return cachedChildren; // calculate common (old and new) keyless keyLess = (keyLess - Math.abs(deltaKeyless)) >> 1; // reorder just nodes without keys newIndex = backupNewIndex; cachedIndex = backupCachedIndex; while (newIndex < newEnd) { if (cachedIndex < cachedEnd) { cachedKey = cachedChildren[cachedIndex]!.key; if (cachedKey != null) { cachedIndex++; continue; } } key = newChildren[newIndex]!.key; if (newIndex < cachedEnd && key === cachedChildren[newIndex]!.key) { if (key != null) { newIndex++; continue; } updateNodeInUpdateChildren( newChildren[newIndex]!, cachedChildren, newIndex, cachedLength, createBefore, element, deepness ); keyLess--; newIndex++; cachedIndex = newIndex; continue; } if (key != null) { assert(newIndex === cachedIndex); if (keyLess === 0 && deltaKeyless < 0) { while (true) { removeNode(cachedChildren[cachedIndex]!); cachedChildren.splice(cachedIndex, 1); cachedEnd--; cachedLength--; deltaKeyless++; assert(cachedIndex !== cachedEnd, "there still need to exist key node"); if (cachedChildren[cachedIndex]!.key != null) break; } continue; } while (cachedChildren[cachedIndex]!.key == undefined) cachedIndex++; assert(key === cachedChildren[cachedIndex]!.key); cachedChildren.splice(newIndex, 0, cachedChildren[cachedIndex]!); cachedChildren.splice(cachedIndex + 1, 1); reorderInUpdateChildren(cachedChildren, newIndex, cachedLength, createBefore, element); // just moving keyed node it was already updated before newIndex++; cachedIndex = newIndex; continue; } if (cachedIndex < cachedEnd) { cachedChildren.splice(newIndex, 0, cachedChildren[cachedIndex]!); cachedChildren.splice(cachedIndex + 1, 1); reorderAndUpdateNodeInUpdateChildren( newChildren[newIndex]!, cachedChildren, newIndex, cachedLength, createBefore, element, deepness ); keyLess--; newIndex++; cachedIndex++; } else { cachedChildren.splice( newIndex, 0, createNode( newChildren[newIndex]!, parentNode, element, findNextNode(cachedChildren, newIndex - 1, cachedLength, createBefore) ) ); cachedEnd++; cachedLength++; newIndex++; cachedIndex++; } } while (cachedEnd > newIndex) { cachedEnd--; removeNode(cachedChildren[cachedEnd]!); cachedChildren.splice(cachedEnd, 1); } return cachedChildren; } var hasNativeRaf = false; var nativeRaf = window.requestAnimationFrame; if (nativeRaf) { nativeRaf((param) => { if (param === +param) hasNativeRaf = true; }); } const setTimeout = window.setTimeout; export const now = Date.now || (() => new Date().getTime()); var startTime = now(); var lastTickTime = 0; function requestAnimationFrame(callback: (time: number) => void) { if (hasNativeRaf) { nativeRaf(callback); } else { var delay = 50 / 3 + lastTickTime - now(); if (delay < 0) delay = 0; setTimeout(() => { lastTickTime = now(); callback(lastTickTime - startTime); }, delay); } } var ctxInvalidated = "$invalidated"; var ctxDeepness = "$deepness"; var fullRecreateRequested = true; var scheduled = false; var isInvalidated = true; let initializing = true; var uptimeMs = 0; var frameCounter = 0; var lastFrameDurationMs = 0; var renderFrameBegin = 0; var regEvents: { [name: string]: Array<(ev: any, target: Node | undefined, node: IBobrilCacheNode | undefined) => boolean>; } = newHashObj(); var registryEvents: | { [name: string]: Array<{ priority: number; callback: (ev: any, target: Node | undefined, node: IBobrilCacheNode | undefined) => boolean; }>; } | undefined; export function addEvent( name: string, priority: number, callback: (ev: any, target: Node | undefined, node: IBobrilCacheNode | undefined) => boolean ): void { if (registryEvents == undefined) registryEvents = newHashObj(); var list = registryEvents[name] || []; list.push({ priority: priority, callback: callback }); registryEvents[name] = list; } export function emitEvent( name: string, ev: any, target: Node | undefined, node: IBobrilCacheNode | undefined ): boolean { var events = regEvents[name]; if (events) for (var i = 0; i < events.length; i++) { if (events[i]!(ev, target, node)) return true; } return false; } var isPassiveEventHandlerSupported = false; try { var options = Object.defineProperty({}, "passive", { get: function () { isPassiveEventHandlerSupported = true; }, }); window.addEventListener("blur", options as any, options); window.removeEventListener("blur", options as any, options); } catch (err) { isPassiveEventHandlerSupported = false; } var listeningEventDeepness = 0; function addListener(el: EventTarget, name: string) { if (name[0] == "!") return; var capture = name[0] == "^"; var eventName = name; if (name[0] == "@") { eventName = name.slice(1); el = document; } if (capture) { eventName = name.slice(1); } function enhanceEvent(ev: Event) { ev = ev || window.event; var t = ev.target || el; var n = deref(<any>t); listeningEventDeepness++; emitEvent(name, ev, <Node>t, n); listeningEventDeepness--; if (listeningEventDeepness == 0 && deferSyncUpdateRequested) syncUpdate(); } if ("on" + eventName in window) el = window; el.addEventListener( eventName, enhanceEvent, isPassiveEventHandlerSupported ? { capture: capture, passive: false } : capture ); } function initEvents() { if (registryEvents === undefined) return; var eventNames = Object.keys(registryEvents); for (var j = 0; j < eventNames.length; j++) { var eventName = eventNames[j]!; var arr = registryEvents[eventName]!; arr = arr.sort((a, b) => a.priority - b.priority); regEvents[eventName] = arr.map((v) => v.callback); } registryEvents = undefined; var body = document.body; for (var i = 0; i < eventNames.length; i++) { addListener(body, eventNames[i]!); } } function selectedUpdate(cache: IBobrilCacheNode[], element: Element, createBefore: Node | null) { var len = cache.length; for (var i = 0; i < len; i++) { var node = cache[i]!; var ctx = node.ctx; if (ctx != null && (<any>ctx)[ctxInvalidated] >= frameCounter) { cache[i] = updateNode( node.orig, node, element, findNextNode(cache, i, len, createBefore), (<any>ctx)[ctxDeepness], true ); } else { ctx = node.ctxStyle; if (ctx != null && (<any>ctx)[ctxInvalidated] >= frameCounter) { updateNodeStyle(node.element as HTMLElement, ctx.data, undefined, node, inSvg); } if (isArray(node.children)) { var backupInSvg = inSvg; var backupInNotFocusable = inNotFocusable; if (inNotFocusable && focusRootTop === node) inNotFocusable = false; if (node.tag === "svg") inSvg = true; else if (inSvg && node.tag === "foreignObject") inSvg = false; var thisElement = node.element; if (thisElement != undefined) { selectedUpdate(node.children, <Element>thisElement, null); } else { selectedUpdate(node.children, element, findNextNode(cache, i, len, createBefore)); } pushUpdateEverytimeCallback(node); inSvg = backupInSvg; inNotFocusable = backupInNotFocusable; } } } } function isLogicalParent( parent: IBobrilCacheNode, child: IBobrilCacheNode | null | undefined, rootIds: string[] ): boolean { while (child != null) { if (parent === child) return true; let p = child.parent; if (p == undefined) { for (var i = 0; i < rootIds.length; i++) { var r = roots[rootIds[i]!]; if (!r) continue; if (r.n === child) { p = r.p; break; } } } child = p; } return false; } var deferSyncUpdateRequested = false; export function syncUpdate() { deferSyncUpdateRequested = false; internalUpdate(now() - startTime); } export function deferSyncUpdate() { if (listeningEventDeepness > 0) { deferSyncUpdateRequested = true; return; } syncUpdate(); } function update(time: number) { scheduled = false; internalUpdate(time); } var rootIds: string[] | undefined; const RootComponent = createVirtualComponent<IBobrilRoot>({ render(ctx: IBobrilCtx, me: IBobrilNode) { const r = ctx.data as IBobrilRoot; let c = r.f(r); if (c === undefined) { me.tag = "-"; // Skip render when root factory returns undefined } else { me.children = c; } }, }); let visitedComponentCounter = 0; function internalUpdate(time: number) { visitedComponentCounter = 0; isInvalidated = false; renderFrameBegin = now(); initEvents(); reallyBeforeFrameCallback(); frameCounter++; ignoringShouldChange = nextIgnoreShouldChange; nextIgnoreShouldChange = false; uptimeMs = time; beforeFrameCallback(); var fullRefresh = false; if (fullRecreateRequested) { fullRecreateRequested = false; fullRefresh = true; } listeningEventDeepness++; if (DEBUG && (measureComponentMethods || measureFullComponentDuration)) { var renderStartMark = `render ${frameCounter}`; window.performance.mark(renderStartMark); } for (let repeat = 0; repeat < 2; repeat++) { focusRootTop = focusRootStack.length === 0 ? null : focusRootStack[focusRootStack.length - 1]!; inNotFocusable = false; rootIds = Object.keys(roots); for (var i = 0; i < rootIds.length; i++) { var r = roots[rootIds[i]!]; if (!r) continue; var rc = r.n; var insertBefore: Node | null = null; for (var j = i + 1; j < rootIds.length; j++) { let rafter = roots[rootIds[j]!]; if (rafter === undefined) continue; insertBefore = getDomNode(rafter.n); if (insertBefore != null) break; } if (focusRootTop) inNotFocusable = !isLogicalParent(focusRootTop, r.p, rootIds); if (r.e === undefined) r.e = document.body; if (rc) { if (fullRefresh || (rc.ctx as any)[ctxInvalidated] >= frameCounter) { let node = RootComponent(r); updateNode(node, rc, r.e, insertBefore, fullRefresh ? 1e6 : (rc.ctx as any)[ctxDeepness]); } else { if (isArray(r.c)) selectedUpdate(r.c, r.e, insertBefore); } } else { let node = RootComponent(r); rc = createNode(node, undefined, r.e, insertBefore); r.n = rc; } r.c = rc.children; } rootIds = undefined; callPostCallbacks(); if (!deferSyncUpdateRequested) break; } callEffects(); deferSyncUpdateRequested = false; listeningEventDeepness--; let r0 = roots["0"]; afterFrameCallback(r0 ? r0.c : null); if (DEBUG && (measureComponentMethods || measureFullComponentDuration)) window.performance.measure("render", renderStartMark!); lastFrameDurationMs = now() - renderFrameBegin; } var nextIgnoreShouldChange = false; var ignoringShouldChange = false; export function ignoreShouldChange() { nextIgnoreShouldChange = true; invalidate(); } export function setInvalidate( inv: (ctx?: Object, deepness?: number) => void ): (ctx?: Object, deepness?: number) => void { let prev = invalidate; invalidate = inv; return prev; } export var invalidate = (ctx?: Object, deepness?: number) => { if (ctx != null) { if (deepness == undefined) deepness = 1e6; if ((<any>ctx)[ctxInvalidated] !== frameCounter + 1) { (<any>ctx)[ctxInvalidated] = frameCounter + 1; (<any>ctx)[ctxDeepness] = deepness; } else { if (deepness > (<any>ctx)[ctxDeepness]) (<any>ctx)[ctxDeepness] = deepness; } } else { fullRecreateRequested = true; } isInvalidated = true; if (scheduled || initializing) return; scheduled = true; requestAnimationFrame(update); }; var lastRootId = 0; export function addRoot( factory: (root: IBobrilRoot) => IBobrilChildren, element?: HTMLElement, parent?: IBobrilCacheNode ): string { lastRootId++; var rootId = "" + lastRootId; roots[rootId] = { f: factory, e: element, c: [], p: parent, n: undefined }; if (rootIds != null) { rootIds.push(rootId); } else { firstInvalidate(); } return rootId; } export function removeRoot(id: string): void { var root = roots[id]; if (!root) return; if (root.n) removeNode(root.n); delete roots[id]; } export function updateRoot(id: string, factory?: (root: IBobrilRoot) => IBobrilChildren) { assert(rootIds != null, "updateRoot could be called only from render"); var root = roots[id]!; assert(root != null); if (factory != null) root.f = factory; let rootNode = root.n; if (rootNode == undefined) return; let ctx = rootNode.ctx; (<any>ctx)[ctxInvalidated] = frameCounter; (<any>ctx)[ctxDeepness] = 1e6; } export function getRoots(): IBobrilRoots { return roots; } function finishInitialize() { initializing = false; invalidate(); } var beforeInit: () => void = finishInitialize; function firstInvalidate() { initializing = true; beforeInit(); beforeInit = finishInitialize; } export function init(factory: () => IBobrilChildren, element?: HTMLElement) { assert(rootIds == undefined, "init should not be called from render"); removeRoot("0"); roots["0"] = { f: factory, e: element, c: [], p: undefined, n: undefined }; firstInvalidate(); } export function setBeforeInit(callback: (cb: () => void) => void): void { let prevBeforeInit = beforeInit; beforeInit = () => { callback(prevBeforeInit); }; } let currentCtxWithEvents: IBobrilCtx | undefined; export function callWithCurrentCtxWithEvents<T>(call: () => T, ctx: IBobrilCtx): T { var backup = currentCtxWithEvents; currentCtxWithEvents = ctx; try { return call(); } finally { currentCtxWithEvents = backup; } } export type AllEvents = IBobrilEvents | IBubblingAndBroadcastEvents | ICapturableEvents; export type EventNames = keyof ICapturableEvents; export type EventParam<T extends EventNames> = T extends keyof ICapturableEvents ? NonNullable<ICapturableEvents[T]> extends (p: infer P) => any ? P : any : any; export function bubble<T extends EventNames>( node: IBobrilCacheNode | null | undefined, name: T, param?: Omit<EventParam<T>, "target"> | { target?: IBobrilCacheNode } ): IBobrilCtx | undefined { if (param == undefined) { param = { target: node! }; } else if (isObject(param) && (param as any).target == undefined) { (param as any).target = node; } let res: IBobrilCtx | undefined = captureBroadcast(name, param!); if (res != undefined) return res; const prevCtx = currentCtxWithEvents; while (node) { var c = node.component; var ctx = node.ctxStyle; if (ctx) { currentCtxWithEvents = ctx; if ((((ctx as IBobrilCtxInternal).$hookFlags | 0) & hasEvents) === hasEvents) { var hooks = (ctx as IBobrilCtxInternal).$hooks!; for (var i = 0, l = hooks.length; i < l; i++) { var h = hooks[i]; if (h instanceof EventsHook) { var m = (h.events as any)[name]; if (m !== undefined) { const eventResult = +m.call(ctx, param) as EventResult; if (eventResult == EventResult.HandledPreventDefault) { currentCtxWithEvents = prevCtx; return ctx; } if (eventResult == EventResult.HandledButRunDefault) { currentCtxWithEvents = prevCtx; return undefined; } if (eventResult == EventResult.NotHandledPreventDefault) { res = ctx; } } } } } } if (c) { ctx = node.ctx!; currentCtxWithEvents = ctx; if ((((ctx as IBobrilCtxInternal).$hookFlags | 0) & hasEvents) === hasEvents) { var hooks = (ctx as IBobrilCtxInternal).$hooks!; for (var i = 0, l = hooks.length; i < l; i++) { var h = hooks[i]; if (h instanceof EventsHook) { var m = (h.events as any)[name]; if (m !== undefined) { const eventResult = +m.call(ctx, param) as EventResult; if (eventResult == EventResult.HandledPreventDefault) { currentCtxWithEvents = prevCtx; return ctx; } if (eventResult == EventResult.HandledButRunDefault) { currentCtxWithEvents = prevCtx; return undefined; } if (eventResult == EventResult.NotHandledPreventDefault) { res = ctx; } } } } } var m = (<any>c)[name]; if (m) { const eventResult = +m.call(c, ctx, param) as EventResult; if (eventResult == EventResult.HandledPreventDefault) { currentCtxWithEvents = prevCtx; return ctx; } if (eventResult == EventResult.HandledButRunDefault) { currentCtxWithEvents = prevCtx; return undefined; } if (eventResult == EventResult.NotHandledPreventDefault) { res = ctx; } } m = (<any>c).shouldStopBubble; if (m) { if (m.call(c, ctx, name, param)) break; } } node = node.parent; } currentCtxWithEvents = prevCtx; return res; } function broadcastEventToNode( node: IBobrilCacheNode | null | undefined, name: string, param: any ): IBobrilCtx | undefined { if (!node) return undefined; let res: IBobrilCtx | undefined; var c = node.component; if (c) { var ctx = node.ctx!; var prevCtx = currentCtxWithEvents; currentCtxWithEvents = ctx; if ((((ctx as IBobrilCtxInternal).$hookFlags | 0) & hasEvents) === hasEvents) { var hooks = (ctx as IBobrilCtxInternal).$hooks!; for (var i = 0, l = hooks.length; i < l; i++) { var h = hooks[i]; if (h instanceof EventsHook) { var m = (h.events as any)[name]; if (m !== undefined) { const eventResult = +m.call(ctx, param) as EventResult; if (eventResult == EventResult.HandledPreventDefault) { currentCtxWithEvents = prevCtx; return ctx; } if (eventResult == EventResult.HandledButRunDefault) { currentCtxWithEvents = prevCtx; return undefined; } if (eventResult == EventResult.NotHandledPreventDefault) { res = ctx; } } } } } var m = (<any>c)[name]; if (m) { const eventResult = +m.call(c, ctx, param) as EventResult; if (eventResult == EventResult.HandledPreventDefault) { currentCtxWithEvents = prevCtx; return ctx; } if (eventResult == EventResult.HandledButRunDefault) { currentCtxWithEvents = prevCtx; return undefined; } if (eventResult == EventResult.NotHandledPreventDefault) { res = ctx; } } m = c.shouldStopBroadcast; if (m) { if (m.call(c, ctx, name, param)) { currentCtxWithEvents = prevCtx; return res; } } currentCtxWithEvents = prevCtx; } var ch = node.children; if (isArray(ch)) { for (var i = 0; i < (<IBobrilCacheNode[]>ch).length; i++) { var res2 = broadcastEventToNode((<IBobrilCacheNode[]>ch)[i], name, param); if (res2 != undefined) return res2; } } return res; } function broadcastCapturedEventToNode( node: IBobrilCacheNode | null | undefined, name: string, param: any ): IBobrilCtx | undefined { if (!node) return undefined; let res: IBobrilCtx | undefined; var c = node.component; var ctx = node.ctxStyle; if (ctx) { if (((ctx as IBobrilCtxInternal).$hookFlags & hasCaptureEvents) === hasCaptureEvents) { var hooks = (ctx as IBobrilCtxInternal).$hooks!; var prevCtx = currentCtxWithEvents; currentCtxWithEvents = ctx; for (var i = 0, l = hooks.length; i < l; i++) { var h = hooks[i]; if (h instanceof CaptureEventsHook) { var m = (h.events as any)[name]; if (m !== undefined) { const eventResult = +m.call(ctx, param) as EventResult; if (eventResult == EventResult.HandledPreventDefault) { currentCtxWithEvents = prevCtx; return ctx; } if (eventResult == EventResult.HandledButRunDefault) { currentCtxWithEvents = prevCtx; return undefined; } if (eventResult == EventResult.NotHandledPreventDefault) { res = ctx; } } } } currentCtxWithEvents = prevCtx; } } if (c) { ctx = node.ctx!; if (((ctx as IBobrilCtxInternal).$hookFlags & hasCaptureEvents) === hasCaptureEvents) { var hooks = (ctx as IBobrilCtxInternal).$hooks!; var prevCtx = currentCtxWithEvents; currentCtxWithEvents = ctx; for (var i = 0, l = hooks.length; i < l; i++) { var h = hooks[i]; if (h instanceof CaptureEventsHook) { var m = (h.events as any)[name]; if (m !== undefined) { const eventResult = +m.call(ctx, param) as EventResult; if (eventResult == EventResult.HandledPreventDefault) { currentCtxWithEvents = prevCtx; return ctx; } if (eventResult == EventResult.HandledButRunDefault) { currentCtxWithEvents = prevCtx; return undefined; } if (eventResult == EventResult.NotHandledPreventDefault) { res = ctx; } } } } currentCtxWithEvents = prevCtx; } } var ch = node.children; if (isArray(ch)) { for (var i = 0, l = (<IBobrilCacheNode[]>ch).length; i < l; i++) { var res2 = broadcastCapturedEventToNode((<IBobrilCacheNode[]>ch)[i], name, param); if (res2 != undefined) return res2; } } return res; } export function captureBroadcast<T extends EventNames>( name: T, param: Omit<EventParam<T>, "target"> | { target?: IBobrilCacheNode } ): IBobrilCtx | undefined { var k = Object.keys(roots); for (var i = 0; i < k.length; i++) { var ch = roots[k[i]!]!.n; if (ch != null) { var res = broadcastCapturedEventToNode(ch, name, param); if (res != null) return res; } } return undefined; } export function broadcast<T extends EventNames>( name: T, param: Omit<EventParam<T>, "target"> | { target?: IBobrilCacheNode } ): IBobrilCtx | undefined { var res = captureBroadcast(name, param); if (res != null) return res; var k = Object.keys(roots); for (var i = 0; i < k.length; i++) { var ch = roots[k[i]!]!.n; if (ch != null) { res = broadcastEventToNode(ch, name, param); if (res != null) return res; } } return undefined; } export function runMethodFrom(ctx: IBobrilCtx | undefined, methodId: MethodId, param?: Object): boolean { var done = false; if (DEBUG && ctx == undefined) throw new Error("runMethodFrom ctx is undefined"); var currentRoot: IBobrilCacheNode | undefined = ctx!.me; var previousRoot: IBobrilCacheNode | undefined; while (currentRoot != undefined) { var children = currentRoot.children; if (isArray(children)) loopChildNodes(<IBobrilCacheNode[]>children); if (done) return true; var comp: any = currentRoot.component; if (comp && comp.runMethod) { if ( callWithCurrentCtxWithEvents( () => comp.runMethod(currentCtxWithEvents, methodId, param), currentRoot.ctx! ) ) return true; } previousRoot = currentRoot; currentRoot = currentRoot.parent; } function loopChildNodes(children: IBobrilCacheNode[]) { for (var i = children.length - 1; i >= 0; i--) { var child: IBobrilCacheNode = children[i]!; if (child === previousRoot) continue; isArray(child.children) && loopChildNodes(child.children); if (done) return; var comp: any = child.component; if (comp && comp.runMethod) { if ( callWithCurrentCtxWithEvents( () => comp.runMethod(currentCtxWithEvents, methodId, param), child.ctx! ) ) { done = true; return; } } } } return done; } export function getCurrentCtxWithEvents(): IBobrilCtx | undefined { if (currentCtxWithEvents != undefined) return currentCtxWithEvents; return currentCtx; } export function tryRunMethod(methodId: MethodId, param?: Object): boolean { return runMethodFrom(getCurrentCtxWithEvents(), methodId, param); } export function runMethod(methodId: MethodId, param?: Object): void { if (!runMethodFrom(getCurrentCtxWithEvents(), methodId, param)) throw Error("runMethod didn't found " + methodId); } let lastMethodId = 0; export function allocateMethodId(): number { return lastMethodId++; } function merge(f1: Function, f2: Function): Function { return function (this: any, ...params: any[]) { var result = f1.apply(this, params); if (result) return result; return f2.apply(this, params); }; } function mergeComponents(c1: IBobrilComponent, c2: IBobrilComponent): IBobrilComponent { let res: IBobrilComponent = Object.create(c1)!; res.super = c1; for (var i in c2) { if (!(i in <any>emptyObject)) { var m = (<any>c2)[i]; var origM = (<any>c1)[i]; if (i === "id") { (<any>res)[i] = (origM != null ? origM : "") + "/" + m; } else if (isFunction(m) && origM != null && isFunction(origM)) { (<any>res)[i] = merge(origM, m); } else { (<any>res)[i] = m; } } } return res; } function overrideComponents(originalComponent: IBobrilComponent, overridingComponent: IBobrilComponent) { let res: IBobrilComponent = Object.create(originalComponent)!; res.super = originalComponent; for (let i in overridingComponent) { if (!(i in <any>emptyObject)) { let m = (<any>overridingComponent)[i]; let origM = (<any>originalComponent)[i]; if (i === "id") { (<any>res)[i] = (origM != null ? origM : "") + "/" + m; } else { (<any>res)[i] = m; } } } return res; } export function preEnhance(node: IBobrilNode, methods: IBobrilComponent): IBobrilNode { var comp = node.component; if (!comp) { node.component = methods; return node; } node.component = mergeComponents(methods, comp); return node; } export function postEnhance(node: IBobrilNode, methods: IBobrilComponent): IBobrilNode { var comp = node.component; if (!comp) { node.component = methods; return node; } node.component = mergeComponents(comp, methods); return node; } export function preventDefault(event: Event) { event.preventDefault(); } function cloneNodeArray(a: IBobrilChildArray): IBobrilChildArray { a = a.slice(0); for (var i = 0; i < a.length; i++) { var n = a[i]; if (isArray(n)) { a[i] = cloneNodeArray(n); } else if (isObject(n)) { a[i] = cloneNode(n); } } return a; } export function cloneNode(node: IBobrilNode): IBobrilNode { var r = <IBobrilNode>assign({}, node); if (r.attrs) { r.attrs = <IBobrilAttributes>assign({}, r.attrs); } var style = r.style; if (isObject(style) && !isFunction(style)) { r.style = assign({}, style); } var ch = r.children; if (ch) { if (isArray(ch)) { r.children = cloneNodeArray(ch); } else if (isObject(ch)) { r.children = cloneNode(ch); } } return r; } // PureFuncs: uptime, lastFrameDuration, frame, invalidated export function uptime() { return uptimeMs; } export function lastFrameDuration() { return lastFrameDurationMs; } export function frame() { return frameCounter; } export function invalidated() { return isInvalidated; } // Bobril.OnChange export interface IInputEvent<T = string | boolean | string[]> extends IEventParam { value: T; } var bValue = "b$value"; var bSelectionStart = "b$selStart"; var bSelectionEnd = "b$selEnd"; var tValue = "value"; function isCheckboxLike(el: HTMLInputElement) { var t = el.type; return t === "checkbox" || t === "radio"; } function stringArrayEqual(a1: string[] | undefined, a2?: string[] | undefined): boolean { if (a1 === a2) return true; if (a1 == undefined || a2 == undefined) return false; var l = a1.length; if (l !== a2.length) return false; for (var j = 0; j < l; j++) { if (a1[j] !== a2[j]) return false; } return true; } function stringArrayContains(a: string[] | undefined, v: string): boolean { if (a == undefined) return false; for (var j = 0; j < a.length; j++) { if (a[j] === v) return true; } return false; } function selectedArray(options: HTMLOptionsCollection): string[] { var res: string[] = []; for (var j = 0; j < options.length; j++) { if (options[j]!.selected) res.push(options[j]!.value); } return res; } function emitOnChange(ev: Event | undefined, target: Node | undefined, node: IBobrilCacheNodeUnsafe | undefined) { if (target && target.nodeName === "OPTION") { target = document.activeElement!; node = deref(target); } if (!node) { return false; } if (node.ctx === undefined) { node.ctx = new BobrilCtx(undefined, node); node.component = emptyObject; } var ctx = node.ctx; var tagName = (<Element>target).tagName; var isSelect = tagName === "SELECT"; var isMultiSelect = isSelect && (<HTMLSelectElement>target).multiple; if (isMultiSelect) { var vs = selectedArray((<HTMLSelectElement>target).options); if (!stringArrayEqual((<any>ctx)[bValue], vs)) { (<any>ctx)[bValue] = vs; emitOnInput(node, vs); } } else if (isCheckboxLike(<HTMLInputElement>target)) { // Postpone change event so onClick will be processed before it if (ev && ev.type === "change") { setTimeout(() => { emitOnChange(undefined, target, node); }, 10); return false; } if ((<HTMLInputElement>target).type === "radio") { var radios = document.getElementsByName((<HTMLInputElement>target).name); for (var j = 0; j < radios.length; j++) { var radio = radios[j]; var radioNode = deref(radio); if (!radioNode) continue; var radioCtx = radioNode.ctx; var vrb = (<HTMLInputElement>radio).checked; if ((<any>radioCtx)[bValue] !== vrb) { (<any>radioCtx)[bValue] = vrb; emitOnInput(radioNode, vrb); } } } else { var vb = (<HTMLInputElement>target).checked; if ((<any>ctx)[bValue] !== vb) { (<any>ctx)[bValue] = vb; emitOnInput(node, vb); } } } else { var v = (<HTMLInputElement>target).value; if ((<any>ctx)[bValue] !== v) { (<any>ctx)[bValue] = v; emitOnInput(node, v); } let sStart = (<HTMLInputElement>target).selectionStart!; let sEnd = (<HTMLInputElement>target).selectionEnd!; let sDir = (<any>target).selectionDirection; let swap = false; let oStart = (<any>ctx)[bSelectionStart]; if (sDir == undefined) { if (sEnd === oStart) swap = true; } else if (sDir === "backward") { swap = true; } if (swap) { let s = sStart; sStart = sEnd; sEnd = s; } emitOnSelectionChange(node, sStart, sEnd); } return false; } function emitOnInput(node: IBobrilCacheNode, value: any) { var prevCtx = currentCtxWithEvents; var ctx = node.ctx; var component = node.component; currentCtxWithEvents = ctx; const hasProp = node.attrs && node.attrs[bValue]; if (isFunction(hasProp)) hasProp(value); const hasOnChange = component && component.onChange; if (isFunction(hasOnChange)) hasOnChange(ctx, value); currentCtxWithEvents = prevCtx; bubble(node, "onInput", { target: node, value }); } function emitOnSelectionChange(node: IBobrilCacheNode, start: number, end: number) { let c = node.component; let ctx = node.ctx; if (c && ((<any>ctx)[bSelectionStart] !== start || (<any>ctx)[bSelectionEnd] !== end)) { (<any>ctx)[bSelectionStart] = start; (<any>ctx)[bSelectionEnd] = end; bubble(node, "onSelectionChange", { target: node, startPosition: start, endPosition: end, }); } } export function select(node: IBobrilCacheNode, start: number, end = start): void { (node.element as HTMLInputElement).setSelectionRange( Math.min(start, end), Math.max(start, end), start > end ? "backward" : "forward" ); emitOnSelectionChange(node, start, end); } function emitOnMouseChange( ev: Event | undefined, _target: Node | undefined, _node: IBobrilCacheNode | undefined ): boolean { let f = focused(); if (f) emitOnChange(ev, <Node>f.element, f); return false; } // click here must have lower priority (higher number) over mouse handlers var events = ["input", "cut", "paste", "keydown", "keypress", "keyup", "click", "change"]; for (var i = 0; i < events.length; i++) addEvent(events[i]!, 10, emitOnChange); var mouseEvents = ["!PointerDown", "!PointerMove", "!PointerUp", "!PointerCancel"]; for (var i = 0; i < mouseEvents.length; i++) addEvent(mouseEvents[i]!, 2, emitOnMouseChange); // Bobril.Focus let currentActiveElement: Element | undefined = undefined; let currentFocusedNode: IBobrilCacheNode | undefined = undefined; let nodeStack: IBobrilCacheNode[] = []; let focusChangeRunning = false; const focusedHookSet = new Set<CommonUseIsHook>(); export let useIsFocused = buildUseIsHook(focusedHookSet); function emitOnFocusChange(inFocus: boolean): boolean { if (focusChangeRunning) return false; focusChangeRunning = true; while (true) { const newActiveElement = document.hasFocus() || inFocus ? document.activeElement! : undefined; if (newActiveElement === currentActiveElement) break; currentActiveElement = newActiveElement; var newStack = vdomPath(currentActiveElement); var common = 0; while (common < nodeStack.length && common < newStack.length && nodeStack[common] === newStack[common]) common++; var i = nodeStack.length - 1; var n: IBobrilCacheNode | null; var c: IBobrilComponent; if (i >= common) { n = nodeStack[i]!; bubble(n, "onBlur"); i--; } while (i >= common) { n = nodeStack[i]!; c = n.component; if (c && c.onFocusOut) c.onFocusOut(n.ctx!); i--; } i = common; while (i + 1 < newStack.length) { n = newStack[i]!; c = n.component; if (c && c.onFocusIn) c.onFocusIn(n.ctx!); i++; } if (i < newStack.length) { n = newStack[i]!; bubble(n, "onFocus"); } nodeStack = newStack; currentFocusedNode = nodeStack.length == 0 ? undefined : nodeStack[nodeStack.length - 1]; focusedHookSet.forEach((v) => v.update(newStack)); } focusChangeRunning = false; return false; } function emitOnFocusChangeDelayed(): boolean { setTimeout(() => emitOnFocusChange(false), 10); return false; } addEvent("^focus", 50, () => emitOnFocusChange(true)); addEvent("^blur", 50, emitOnFocusChangeDelayed); export function focused(): IBobrilCacheNode | undefined { return currentFocusedNode; } export function focus(node: IBobrilCacheNode, backwards?: boolean): boolean { if (node == undefined) return false; if (isString(node)) return false; var style = node.style as unknown as CSSStyleDeclaration | undefined; if (style != undefined) { if (style.visibility === "hidden") return false; if (style.display === "none") return false; } var attrs = node.attrs; if (attrs != undefined) { var ti = attrs.tabindex; if (ti !== undefined || isNaturallyFocusable(node.tag, attrs)) { var el = node.element; (<HTMLElement>el).focus(); emitOnFocusChange(false); return true; } } var children = node.children; if (isArray(children)) { for (var i = 0; i < children.length; i++) { if (focus(children[backwards ? children.length - 1 - i : i]!, backwards)) return true; } return false; } return false; } // Bobril.Scroll var callbacks: Array<(info: IBobrilScroll) => void> = []; function emitOnScroll(_ev: Event, _target: Node | undefined, node: IBobrilCacheNode | undefined) { let info: IBobrilScroll = { node, }; for (var i = 0; i < callbacks.length; i++) { callbacks[i]!(info); } captureBroadcast("onScroll", info); return false; } // capturing event to hear everything addEvent("^scroll", 10, emitOnScroll); export function addOnScroll(callback: (info?: IBobrilScroll) => void): void { callbacks.push(callback); } export function removeOnScroll(callback: (info?: IBobrilScroll) => void): void { for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { callbacks.splice(i, 1); return; } } } const isHtml = /^(?:html)$/i; const isScrollOrAuto = /^(?:auto)$|^(?:scroll)$/i; // inspired by https://github.com/litera/jquery-scrollintoview/blob/master/jquery.scrollintoview.js export function isScrollable(el: Element): [boolean, boolean] { var styles: any = window.getComputedStyle(el); var res: [boolean, boolean] = [true, true]; if (!isHtml.test(el.nodeName)) { res[0] = isScrollOrAuto.test(styles.overflowX); res[1] = isScrollOrAuto.test(styles.overflowY); } res[0] = res[0] && el.scrollWidth > el.clientWidth; res[1] = res[1] && el.scrollHeight > el.clientHeight; return res; } // returns standard X,Y order export function getWindowScroll(): [number, number] { var left = window.pageXOffset; var top = window.pageYOffset; return [left, top]; } // returns node offset on page in standard X,Y order export function nodePagePos(node: IBobrilCacheNode): [number, number] { let rect = (<Element>getDomNode(node)).getBoundingClientRect(); let res = getWindowScroll(); res[0] += rect.left; res[1] += rect.top; return res; } type Point = [number, number]; type Number16 = [ number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number ]; class CSSMatrix { data: Number16; constructor(data: Number16) { this.data = data; } static fromString(s: string): CSSMatrix { var c = s.match(/matrix3?d?\(([^\)]+)\)/i)![1]!.split(","); if (c.length === 6) { c = [c[0]!, c[1]!, "0", "0", c[2]!, c[3]!, "0", "0", "0", "0", "1", "0", c[4]!, c[5]!, "0", "1"]; } return new CSSMatrix([ parseFloat(c[0]!), parseFloat(c[4]!), parseFloat(c[8]!), parseFloat(c[12]!), parseFloat(c[1]!), parseFloat(c[5]!), parseFloat(c[9]!), parseFloat(c[13]!), parseFloat(c[2]!), parseFloat(c[6]!), parseFloat(c[10]!), parseFloat(c[14]!), parseFloat(c[3]!), parseFloat(c[7]!), parseFloat(c[11]!), parseFloat(c[15]!), ]); } static identity(): CSSMatrix { return new CSSMatrix([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); } multiply(m: CSSMatrix): CSSMatrix { var a = this.data; var b = m.data; return new CSSMatrix([ a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12], a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13], a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14], a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15], a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12], a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13], a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14], a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15], a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12], a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13], a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14], a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15], a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12], a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13], a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14], a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15], ]); } translate(tx: number, ty: number, tz: number): CSSMatrix { var z = new CSSMatrix([1, 0, 0, tx, 0, 1, 0, ty, 0, 0, 1, tz, 0, 0, 0, 1]); return this.multiply(z); } inverse(): CSSMatrix { var m = this.data; var a = m[0]; var b = m[1]; var c = m[2]; var d = m[4]; var e = m[5]; var f = m[6]; var g = m[8]; var h = m[9]; var k = m[10]; var A = e * k - f * h; var B = f * g - d * k; var C = d * h - e * g; var D = c * h - b * k; var E = a * k - c * g; var F = b * g - a * h; var G = b * f - c * e; var H = c * d - a * f; var K = a * e - b * d; var det = a * A + b * B + c * C; var X = new CSSMatrix([ A / det, D / det, G / det, 0, B / det, E / det, H / det, 0, C / det, F / det, K / det, 0, 0, 0, 0, 1, ]); var Y = new CSSMatrix([1, 0, 0, -m[3], 0, 1, 0, -m[7], 0, 0, 1, -m[11], 0, 0, 0, 1]); return X.multiply(Y); } transformPoint(x: number, y: number): Point { var m = this.data; return [m[0] * x + m[1] * y + m[3], m[4] * x + m[5] * y + m[7]]; } } function getTransformationMatrix(element: Node) { var identity = CSSMatrix.identity(); var transformationMatrix = identity; var x: Node | null = element; var doc = x.ownerDocument!.documentElement; while (x != undefined && x !== doc && x.nodeType != 1) x = x.parentNode; while (x != undefined && x !== doc) { var computedStyle = <any>window.getComputedStyle(<HTMLElement>x, undefined); var c = CSSMatrix.fromString( ( computedStyle.transform || computedStyle.OTransform || computedStyle.WebkitTransform || computedStyle.msTransform || computedStyle.MozTransform || "none" ).replace(/^none$/, "matrix(1,0,0,1,0,0)") ); transformationMatrix = c.multiply(transformationMatrix); x = x.parentNode; } var w: number; var h: number; if ((element.nodeName + "").toLowerCase() === "svg") { var cs = getComputedStyle(<Element>element, undefined); w = parseFloat(cs.getPropertyValue("width")) || 0; h = parseFloat(cs.getPropertyValue("height")) || 0; } else { w = (<HTMLElement>element).offsetWidth; h = (<HTMLElement>element).offsetHeight; } var i = 4; var left = +Infinity; var top = +Infinity; while (--i >= 0) { var p = transformationMatrix.transformPoint(i === 0 || i === 1 ? 0 : w, i === 0 || i === 3 ? 0 : h); if (p[0] < left) { left = p[0]; } if (p[1] < top) { top = p[1]; } } var rect = (<HTMLElement>element).getBoundingClientRect(); transformationMatrix = identity.translate(rect.left - left, rect.top - top, 0).multiply(transformationMatrix); return transformationMatrix; } export function convertPointFromClientToNode(node: IBobrilCacheNode, pageX: number, pageY: number): [number, number] { let element = getDomNode(node); if (element == undefined) element = document.body; return getTransformationMatrix(element).inverse().transformPoint(pageX, pageY); } export declare class Tagged<N extends string> { protected _nominal_: N; } export type Nominal<T, N extends string> = T & Tagged<N>; /// definition for Bobril defined class export type IBobrilStyleDef = Nominal<string, "IBobrilStyleDef"> | ColorlessSprite; export type ColorlessSprite = Nominal<string, "ColorlessSprite">; /// object case if for inline style declaration, undefined, null, true and false values are ignored export type IBobrilStyle = Readonly<CSSInlineStyles> | IBobrilStyleDef | "" | 0 | boolean | undefined | null; /// place inline styles at end for optimal speed export type IBobrilStyles = IBobrilStyle | IBobrilStyleArray; export interface IBobrilStyleArray extends ReadonlyArray<IBobrilStyles> { fill: any; pop: any; push: any; concat: any; reverse: any; shift: any; slice: any; sort: any; splice: any; unshift: any; indexOf: any; lastIndexOf: any; every: any; some: any; forEach: any; map: any; filter: any; reduce: any; reduceRight: any; find: any; findIndex: any; [Symbol.iterator]: any; entries: any; values: any; readonly [index: number]: IBobrilStyles; } // PureFuncs: asset export let asset: (path: string) => string = (<any>window)["bobrilBAsset"] || function (path: string): string { return path; }; export function setAsset(fn: (path: string) => string) { asset = fn; } // Bobril.helpers export function withKey(content: IBobrilChildren, key: string): IBobrilNodeWithKey { if (isObject(content) && !isArray(content)) { content.key = key; return content as IBobrilNodeWithKey; } return { key, children: content, }; } export function withRef(node: IBobrilNode, ctx: IBobrilCtx, name: string): IBobrilNode { node.ref = [ctx, name]; return node; } export function extendCfg(ctx: IBobrilCtx, propertyName: string, value: any): void { var c = ctx.me.cfg; if (c !== undefined) { c[propertyName] = value; } else { c = Object.assign({}, ctx.cfg); c[propertyName] = value; (ctx.me as IBobrilCacheNodeUnsafe).cfg = c; } } // PureFuncs: createVirtualComponent, createComponent, createDerivedComponent, createOverridingComponent, prop, propi, propa, propim, getValue export type ChildrenType<TData extends { [name: string]: any }> = "children" extends keyof TData ? TData["children"] : never; export interface IComponentFactory<TData extends object | never> { (data?: TData, children?: ChildrenType<TData>): IBobrilNode<TData>; } export function createVirtualComponent<TData extends object | never, TCtx extends IBobrilCtx<TData> = any>( component: IBobrilComponent<TData, TCtx> ): IComponentFactory<TData> { return (data?: TData, children?: ChildrenType<TData>): IBobrilNode => { if (children !== undefined) { if (data == undefined) data = {} as TData; (data as any).children = children; } return { data, component: component }; }; } export function createOverridingComponent<TData extends object | never, TDataOriginal = any>( original: (data?: TDataOriginal, children?: ChildrenType<TDataOriginal>) => IBobrilNode, after: IBobrilComponent ): IComponentFactory<TData> { const originalComponent = original().component!; const overriding = overrideComponents(originalComponent, after); return createVirtualComponent<TData>(overriding); } export function createComponent<TData extends object | never, TCtx extends IBobrilCtx<TData> = any>( component: IBobrilComponent<TData, TCtx> ): IComponentFactory<TData> { const originalRender = component.render; if (originalRender) { component.render = function (ctx: IBobrilCtx<TData>, me: IBobrilNode, oldMe?: IBobrilCacheNode) { me.tag = "div"; return originalRender.call(component, ctx, me, oldMe); }; } else { component.render = (_ctx: IBobrilCtx<TData>, me: IBobrilNode) => { me.tag = "div"; }; } return createVirtualComponent<TData>(component); } export function createDerivedComponent<TData extends object | never, TDataOriginal extends object | never>( original: (data?: TDataOriginal, children?: ChildrenType<TDataOriginal>) => IBobrilNode<TDataOriginal>, after: IBobrilComponent<TData> ): IComponentFactory<TData & TDataOriginal> { const originalComponent = original().component!; const merged = mergeComponents(originalComponent, after); return createVirtualComponent<TData & TDataOriginal>(merged); } export type IProp<T> = (value?: T) => T; export type IPropAsync<T> = (value?: T | PromiseLike<T>) => T; export interface IValueData<T> { value: T | IProp<T>; onChange?: (value: T) => void; } export function prop<T>(value: T, onChange?: (value: T, old: T) => void): IProp<T> { return (val?: T) => { if (val !== undefined) { if (onChange !== undefined) onChange(val, value); value = val; } return value; }; } export function propi<T>(value: T): IProp<T> { return (val?: T) => { if (val !== undefined) { value = val; invalidate(); } return value; }; } export function propa<T>(prop: IProp<T>): IPropAsync<T> { return (val?: T | PromiseLike<T>) => { if (val !== undefined) { if (typeof val === "object" && isFunction((<PromiseLike<T>>val).then)) { (<PromiseLike<T>>val).then( (v) => { prop(v); }, (err) => { if (window["console"] && console.error) console.error(err); } ); } else { return prop(<T>val); } } return prop(); }; } export function propim<T>(value: T, ctx?: IBobrilCtx, onChange?: (value: T, old: T) => void): IProp<T> { return (val?: T) => { if (val !== undefined && !is(val, value)) { const oldVal = val; value = val; if (onChange !== undefined) onChange(val, oldVal); invalidate(ctx); } return value; }; } export function debounceProp<T>(from: IProp<T>, delay = 500): IProp<T> { let current = from(); let lastSet = current; let timer: number | undefined; function clearTimer() { if (timer !== undefined) { clearTimeout(timer); timer = undefined; } } return (value?: T): T => { if (value === undefined) { let origin = from(); if (origin === lastSet) return current; current = origin; lastSet = origin; clearTimer(); return origin; } else { clearTimer(); // setting same value means flush if (current === value) { lastSet = value; from(value); } else { current = value; timer = setTimeout(() => { lastSet = current; from(current); timer = undefined; }, delay); } return value; } }; } export function getValue<T>(value: T | IProp<T> | IPropAsync<T>): T { if (isFunction(value)) { return (<IProp<T>>value)(); } return <T>value; } export function emitChange<T>(data: IValueData<T>, value: T) { if (isFunction(data.value)) { (<IProp<T>>data.value)(value); } if (data.onChange !== undefined) { data.onChange(value); } } export function shallowEqual(a: any, b: any): boolean { if (is(a, b)) { return true; } if (!isObject(a) || !isObject(b)) { return false; } const kA = Object.keys(a); const kB = Object.keys(b); if (kA.length !== kB.length) { return false; } for (let i = 0; i < kA.length; i++) { if (!hOP.call(b, kA[i]!) || !is(a[kA[i]!], b[kA[i]!])) { return false; } } return true; } // TSX reactNamespace emulation // PureFuncs: createElement, getAllPropertyNames, component, buildUseIsHook const jsxFactoryCache = new Map<IComponentClass<any> | IComponentFunction<any>, Function>(); function getStringPropertyDescriptors(obj: any): Map<string, PropertyDescriptor> { var props = new Map<string, PropertyDescriptor>(); do { Object.getOwnPropertyNames(obj).forEach(function (this: Map<string, PropertyDescriptor>, prop: string) { if (!this.has(prop)) this.set(prop, Object.getOwnPropertyDescriptor(obj, prop)!); }, props); } while ((obj = Object.getPrototypeOf(obj))); return props; } const jsxSimpleProps = new Set("key className component data children".split(" ")); export function createElement<T>( name: string | ((data?: T, children?: any) => IBobrilNode) | IComponentClass<T> | IComponentFunction<T>, data?: T, ...children: IBobrilChildren[] ): IBobrilNode<T>; export function createElement(name: any, props: any): IBobrilNode { let children: IBobrilChildren; const argumentsCount = arguments.length - 2; if (argumentsCount === 0) { } else if (argumentsCount === 1) { children = arguments[2]; } else { children = new Array(argumentsCount); for (let i = 0; i < argumentsCount; i++) { children[i] = arguments[i + 2]; } } if (isString(name)) { var res: IBobrilNode = argumentsCount === 0 ? { tag: name } : { tag: name, children: children }; if (props == undefined) { return res; } var attrs: IBobrilAttributes | undefined; var component: IBobrilComponent | undefined; for (var n in props) { if (!hOP.call(props, n)) continue; var propValue = props[n]; if (jsxSimpleProps.has(n)) { (res as any)[n] = propValue; } else if (n === "style") { if (isFunction(propValue)) { (res as any)[n] = propValue; } else { style(res, propValue); } } else if (n === "ref") { if (isString(propValue)) { assert(getCurrentCtx() != undefined); res.ref = [getCurrentCtx()!, propValue]; } else res.ref = propValue; } else if (n.startsWith("on") && isFunction(propValue)) { if (component == undefined) { component = newHashObj(); res.component = component; } (component as any)[n] = propValue.call.bind(propValue); continue; } else { if (attrs == undefined) { attrs = newHashObj(); res.attrs = attrs; } attrs[n] = propValue; } } return res; } else { let res: IBobrilNode; let factory = jsxFactoryCache.get(name); if (factory === undefined) { factory = createFactory(name); jsxFactoryCache.set(name, factory); } if (argumentsCount == 0) { res = factory(props); } else { if (factory.length == 1) { if (props == undefined) props = { children }; else props.children = children; res = factory(props); } else { res = factory(props, children); } } if (props != undefined) { if (props.ref !== undefined) { res.ref = props.ref; delete props.ref; } if (props.key !== undefined) { res.key = props.key; delete props.key; } } return res; } } export const skipRender = { tag: "-" } as IBobrilNode; export interface IFragmentData extends IDataWithChildren {} export function Fragment(data: IFragmentData): IBobrilNode { return { children: data.children }; } export interface IFragmentWithEventsData extends IFragmentData, IBobrilEvents {} export function FragmentWithEvents(data: IFragmentWithEventsData): IBobrilNode { var res: IBobrilNode = { children: data.children }; var component: IBobrilComponent; for (var n in data) { if (!hOP.call(data, n)) continue; var propValue = (data as any)[n]; if (n.startsWith("on") && isFunction(propValue)) { component ??= newHashObj(); res.component = component; (component as any)[n] = propValue.call.bind(propValue); } } return res; } export interface IPortalData extends IDataWithChildren { element?: Element; } export function Portal(data: IPortalData): IBobrilNode { return { tag: "@", data: data.element ?? document.body, children: data.children }; } export enum EventResult { /// event propagation will continue. It's like returning falsy value. NotHandled = 0, /// event propagation will stop and default handing will be prevented. returning true has same meaning HandledPreventDefault = 1, /// event propagation will stop but default handing will still run HandledButRunDefault = 2, /// event propagation will continue but default handing will be prevented NotHandledPreventDefault = 3, } export type GenericEventResult = EventResult | boolean | void; export class Component<TData = IDataWithChildren> extends BobrilCtx<TData> implements IBobrilEvents { constructor(data?: TData, me?: IBobrilCacheNode) { super(data, me); } init?(data: TData): void; render?(data: TData): IBobrilChildren; destroy?(me: IBobrilCacheNode): void; shouldChange?(newData: TData, oldData: TData): boolean; /// called from children to parents order for new nodes postInitDom?(me: IBobrilCacheNode): void; /// called from children to parents order for updated nodes postUpdateDom?(me: IBobrilCacheNode): void; /// called from children to parents order for updated nodes but in every frame even when render was not run postUpdateDomEverytime?(me: IBobrilCacheNode): void; /// called from children to parents order for new and updated nodes (combines postInitDom and postUpdateDom) postRenderDom?(me: IBobrilCacheNode): void; /// declared here to remove "no properties in common" your component can `implements b.IBobrilEvents` onChange?(value: any): void; //static canActivate?(transition: IRouteTransition): IRouteCanResult; //canDeactivate?(transition: IRouteTransition): IRouteCanResult; } export interface IComponentClass<TData extends Object = {}> { new (data?: any, me?: IBobrilCacheNode): Component<TData>; } export class PureComponent<TData = IDataWithChildren> extends Component<TData> { shouldChange(newData: TData, oldData: TData): boolean { return !shallowEqual(newData, oldData); } } export interface IComponentFunction<TData extends Object = {}> extends Function { (this: IBobrilCtx, data: TData): IBobrilChildren; } function forwardRender(m: Function) { return (ctx: IBobrilCtx, me: IBobrilNode, _oldMe?: IBobrilCacheNode) => { var res = m.call(ctx, ctx.data); if (res === skipRender) { me.tag = "-"; return; } var resComponent = res?.component?.src; if (resComponent === Fragment) { res = res.data?.children; } me.children = res; }; } function forwardInit(m: Function) { return (ctx: IBobrilCtx) => { m.call(ctx, ctx.data); }; } function forwardShouldChange(m: Function) { return (ctx: IBobrilCtx, me: IBobrilNode, oldMe: IBobrilNode) => { return m.call(ctx, me.data, oldMe.data); }; } function forwardMe(m: Function) { return m.call.bind(m); } type PostLikeMethod = (ctx: IBobrilCtx, me: IBobrilCacheNode) => void; function combineWithForwardMe( component: IBobrilComponent, name: keyof IBobrilComponent, func: (me: IBobrilCacheNode) => void ) { const existing = component[name] as PostLikeMethod; if (existing != undefined) { (component[name] as PostLikeMethod) = (ctx: IBobrilCtx, me: IBobrilCacheNode) => { existing(ctx, me); func.call(ctx, me); }; } else { (component[name] as PostLikeMethod) = forwardMe(func); } } const postInitDom = "postInitDom"; const postUpdateDom = "postUpdateDom"; const postUpdateDomEverytime = "postUpdateDomEverytime"; const methodsWithMeParam = ["destroy", postInitDom, postUpdateDom, postUpdateDomEverytime]; export function component<TData extends object>( component: IComponentClass<TData> | IComponentFunction<TData>, name?: string ): IComponentFactory<TData> { const bobrilComponent = {} as IBobrilComponent; if (component.prototype instanceof Component) { const proto = component.prototype as any; const protoStatic = proto.constructor; bobrilComponent.id = getId(name, protoStatic); const protoMap = getStringPropertyDescriptors(proto); protoMap.forEach((descriptor, key) => { const value = descriptor.value; if (value == undefined) return; let set = undefined as any; if (key === "render") { set = forwardRender(value); } else if (key === "init") { set = forwardInit(value); } else if (key === "shouldChange") { set = forwardShouldChange(value); } else if (methodsWithMeParam.indexOf(key) >= 0) { combineWithForwardMe(bobrilComponent, key as any, value); } else if (key === "postRenderDom") { combineWithForwardMe(bobrilComponent, methodsWithMeParam[1] as any, value); combineWithForwardMe(bobrilComponent, methodsWithMeParam[2] as any, value); } else if (isFunction(value) && /^(?:canDeactivate$|on[A-Z])/.test(key)) { set = forwardMe(value); } if (set !== undefined) { (bobrilComponent as any)[key] = set; } }); bobrilComponent.ctxClass = component as unknown as ICtxClass; (bobrilComponent as any).canActivate = protoStatic.canActivate; // for router } else { bobrilComponent.id = getId(name, component); bobrilComponent.render = forwardRender(component); } bobrilComponent.src = component; return (data?: TData): IBobrilNode => { return { data, component: bobrilComponent }; }; } function getId(name: string | undefined, classOrFunction: any): string { return name || classOrFunction.id || classOrFunction.name + "_" + allocateMethodId(); } function createFactory(comp: IComponentClass<any> | IComponentFunction<any>): Function { if (comp.prototype instanceof Component) { return component(comp); } else if (comp.length == 2) { // classic bobril factory method return comp; } else { return component(comp); } } function checkCurrentRenderCtx() { assert(currentCtx != undefined && hookId >= 0, "Hooks could be used only in Render method"); } export function _getHooks() { checkCurrentRenderCtx(); let hooks = (currentCtx as IBobrilCtxInternal).$hooks; if (hooks === undefined) { hooks = []; (currentCtx as IBobrilCtxInternal).$hooks = hooks; } return hooks; } export function _allocHook() { return hookId++; } export function useState<T>(initValue: T | (() => T)): IProp<T> & [T, (value: T | ((value: T) => T)) => void] { const myHookId = hookId++; const hooks = _getHooks(); const ctx = currentCtx; let hook = hooks[myHookId]; if (hook === undefined) { if (isFunction(initValue)) { initValue = initValue(); } hook = (value?: T) => { if (value !== undefined && !is(value, hook[0])) { hook[0] = value; invalidate(ctx); } return hook[0]; }; hook[0] = initValue; hook[1] = (value: T | ((value: T) => T)) => { if (isFunction(value)) { value = value(hook[0]); } if (!is(value, hook[0])) { hook[0] = value; invalidate(ctx); } }; hooks[myHookId] = hook; } return hook; } export type Dispatch<A> = (value: A) => void; export type Reducer<S, A> = (prevState: S, action: A) => S; export type ReducerState<R extends Reducer<any, any>> = R extends Reducer<infer S, any> ? S : never; export type ReducerAction<R extends Reducer<any, any>> = R extends Reducer<any, infer A> ? A : never; export function useReducer<R extends Reducer<any, any>, I>( reducer: R, initializerArg: I & ReducerState<R>, initializer: (arg: I & ReducerState<R>) => ReducerState<R> ): [ReducerState<R>, Dispatch<ReducerAction<R>>]; export function useReducer<R extends Reducer<any, any>, I>( reducer: R, initializerArg: I, initializer: (arg: I) => ReducerState<R> ): [ReducerState<R>, Dispatch<ReducerAction<R>>]; export function useReducer<R extends Reducer<any, any>>( reducer: R, initialState: ReducerState<R>, initializer?: undefined ): [ReducerState<R>, Dispatch<ReducerAction<R>>]; export function useReducer<R extends Reducer<any, any>, I>( reducer: R, initializerArg: I, initializer?: (arg: I) => ReducerState<R> ): [ReducerState<R>, Dispatch<ReducerAction<R>>] { const myHookId = hookId++; const hooks = _getHooks(); const ctx = currentCtx; let hook = hooks[myHookId] as [ReducerState<R>, Dispatch<ReducerAction<R>>]; if (hook === undefined) { var initValue = isFunction(initializer) ? initializer(initializerArg) : (initializerArg as ReducerState<R>); hook = [ initValue, (action: ReducerAction<R>) => { let currentValue = hook[0]; let newValue = reducer(currentValue, action); if (!is(newValue, currentValue)) { hook[0] = newValue; invalidate(ctx); } }, ]; hooks[myHookId] = hook; } return hook; } export interface IContext<T> { id: string; dv: T; } export function createContext<T = unknown>(defaultValue: T, id?: string): IContext<T> { if (id === undefined) { id = "__b#" + allocateMethodId(); } return { id, dv: defaultValue }; } export function context<T>(key: IContext<T>): (target: object, propertyKey: string) => void { return (target: object, propertyKey: string): void => { Object.defineProperty(target, propertyKey, { configurable: true, get(this: IBobrilCtxInternal): T { const cfg = this.me.cfg || this.cfg; if (cfg == undefined || !(key.id in cfg)) return key.dv; return cfg[key.id]; }, set(this: IBobrilCtxInternal, value: T) { extendCfg(this, key.id, value); }, }); }; } export function useContext<T>(key: IContext<T>): T; export function useContext<T = unknown>(key: string): T | undefined; export function useContext<T>(key: string | IContext<T>): T | undefined { checkCurrentRenderCtx(); const cfg = currentCtx!.me.cfg || currentCtx!.cfg; if (isString(key)) { if (cfg == undefined) return undefined; return cfg[key]; } else { if (cfg == undefined || !(key.id in cfg)) return key.dv; return cfg[key.id]; } } export function useProvideContext(key: string, value: any): void; export function useProvideContext<T>(key: IContext<T>, value: T): void; export function useProvideContext<T = any>(key: string | IContext<T>, value: T): void { checkCurrentRenderCtx(); extendCfg(currentCtx!, isString(key) ? key : key.id, value); } export function useRef<T = unknown>(initialValue?: T): IProp<T> & { current: T } { const myHookId = hookId++; const hooks = _getHooks(); let hook = hooks[myHookId]; if (hook === undefined) { hook = (value?: T) => { if (value !== undefined) { hook.current = value; } return hook.current; }; hook.current = initialValue; hooks[myHookId] = hook; } return hook; } export function useStore<T>(factory: () => T): T { const myHookId = hookId++; const hooks = _getHooks(); let hook = hooks[myHookId]; if (hook === undefined) { hook = factory(); if (isDisposable(hook)) { addDisposable(currentCtx!, hook); } hooks[myHookId] = hook; } return hook; } function hookPostInitDom(ctx: IBobrilCtxInternal) { const hooks = ctx.$hooks!; const len = hooks.length; for (let i = 0; i < len; i++) { const hook = hooks[i]; const fn = hook[postInitDom]; if (fn !== undefined) { fn.call(hook, ctx); } } } function hookPostUpdateDom(ctx: IBobrilCtxInternal) { const hooks = ctx.$hooks!; const len = hooks.length; for (let i = 0; i < len; i++) { const hook = hooks[i]; const fn = hook[postUpdateDom]; if (fn !== undefined) { fn.call(hook, ctx); } } } function hookPostUpdateDomEverytime(ctx: IBobrilCtxInternal) { const hooks = ctx.$hooks!; const len = hooks.length; for (let i = 0; i < len; i++) { const hook = hooks[i]; const fn = hook[postUpdateDomEverytime]; if (fn !== undefined) { fn.call(hook, ctx); } } } type EffectCallback = () => void | (() => void | undefined); type DependencyList = ReadonlyArray<unknown>; export function bind(target: any, propertyKey?: string, descriptor?: PropertyDescriptor): any { if (propertyKey != undefined && descriptor != undefined) { const fn = descriptor.value; assert(isFunction(fn), `Only methods can be decorated with @bind. '${propertyKey}' is not a method!`); let definingProperty = false; return { configurable: true, get() { if (definingProperty) { return fn; } let value = fn!.bind(this); definingProperty = true; Object.defineProperty(this, propertyKey, { value, configurable: true, writable: true, }); definingProperty = false; return value; }, }; } const proto = target.prototype; const keys = Object.getOwnPropertyNames(proto); keys.forEach((key) => { if (key === "constructor") { return; } const descriptor = Object.getOwnPropertyDescriptor(proto, key); if (isFunction(descriptor!.value)) { Object.defineProperty(proto, key, bind(target, key, descriptor)); } }); return target; } class DepsChangeDetector { deps?: DependencyList; detectChange(deps?: DependencyList): boolean { let changed = false; if (deps != undefined) { const lastDeps = this.deps; if (lastDeps == undefined) { changed = true; } else { const depsLen = deps.length; if (depsLen != lastDeps.length) changed = true; else { for (let i = 0; i < depsLen; i++) { if (!is(deps[i], lastDeps[i])) { changed = true; break; } } } } } else changed = true; this.deps = deps; return changed; } } class MemoHook<T> extends DepsChangeDetector { current: T | undefined; memoize(factory: () => T, deps: DependencyList): T { if (this.detectChange(deps)) { this.current = factory(); } return this.current!; } } export function useMemo<T>(factory: () => T, deps: DependencyList): T { const myHookId = hookId++; const hooks = _getHooks(); let hook = hooks[myHookId]; if (hook === undefined) { hook = new MemoHook(); hooks[myHookId] = hook; } return hook.memoize(factory, deps); } export function useCallback<T>(callback: T, deps: DependencyList): T { return useMemo(() => callback, deps); } class CommonEffectHook extends DepsChangeDetector implements IDisposable { callback?: EffectCallback; lastDisposer?: () => void; shouldRun = false; update(callback: EffectCallback, deps?: DependencyList) { this.callback = callback; if (this.detectChange(deps)) { this.doRun(); } } doRun() { this.shouldRun = true; } run() { const c = this.callback; if (c != undefined) { this.dispose(); this.lastDisposer = c() as any; } } dispose() { this.callback = undefined; if (isFunction(this.lastDisposer)) this.lastDisposer(); this.lastDisposer = undefined; } } class EffectHook extends CommonEffectHook { useEffect() { if (this.shouldRun) { this.shouldRun = false; this.run(); } } } export function useEffect(callback: EffectCallback, deps?: DependencyList): void { const myHookId = hookId++; const hooks = _getHooks(); let hook = hooks[myHookId]; if (hook === undefined) { (currentCtx as IBobrilCtxInternal).$hookFlags! |= hasUseEffect; hook = new EffectHook(); addDisposable(currentCtx!, hook); hooks[myHookId] = hook; } hook.update(callback, deps); } class LayoutEffectHook extends CommonEffectHook { postInitDom(ctx: IBobrilCtxInternal) { this[postUpdateDomEverytime].call(this, ctx); } postUpdateDomEverytime(ctx: IBobrilCtxInternal) { if (this.shouldRun) { this.shouldRun = false; this.run(); if ((<any>ctx)[ctxInvalidated] > frameCounter) { deferSyncUpdate(); } } } } export function useLayoutEffect(callback: EffectCallback, deps?: DependencyList): void { const myHookId = hookId++; const hooks = _getHooks(); let hook = hooks[myHookId]; if (hook === undefined) { (currentCtx as IBobrilCtxInternal).$hookFlags! |= hasPostInitDom | hasPostUpdateDomEverytime; hook = new LayoutEffectHook(); addDisposable(currentCtx!, hook); hooks[myHookId] = hook; } hook.update(callback, deps); } class EventsHook { events!: IHookableEvents; } export function useEvents(events: IHookableEvents) { const myHookId = hookId++; const hooks = _getHooks(); let hook = hooks[myHookId]; if (hook === undefined) { (currentCtx as IBobrilCtxInternal).$hookFlags! |= hasEvents; hook = new EventsHook(); hooks[myHookId] = hook; } else { assert(hook instanceof EventsHook); } hook.events = events; } class CaptureEventsHook { events!: ICapturableEvents; } export function useCaptureEvents(events: ICapturableEvents) { const myHookId = hookId++; const hooks = _getHooks(); let hook = hooks[myHookId]; if (hook === undefined) { (currentCtx as IBobrilCtxInternal).$hookFlags! |= hasCaptureEvents; hook = new CaptureEventsHook(); hooks[myHookId] = hook; } else { assert(hook instanceof CaptureEventsHook); } hook.events = events; } export class CommonUseIsHook implements IDisposable { Value: boolean; private _owner: Set<CommonUseIsHook>; private _ctx: IBobrilCtx; constructor(owner: Set<CommonUseIsHook>, ctx: IBobrilCtx) { this.Value = false; this._owner = owner; this._ctx = ctx; owner.add(this); addDisposable(ctx, this); } update(path: IBobrilCacheNode[]) { let newValue = path.indexOf(this._ctx.me) >= 0; if (this.Value == newValue) return; this.Value = newValue; invalidate(this._ctx); } dispose() { this._owner.delete(this); } } export function buildUseIsHook(owner: Set<CommonUseIsHook>): () => boolean { return () => { const myHookId = hookId++; const hooks = _getHooks(); let hook = hooks[myHookId]; if (hook === undefined) { hook = new CommonUseIsHook(owner, currentCtx!); hooks[myHookId] = hook; } return hook.Value; }; } export interface IDataWithChildren { children?: IBobrilChildren; } interface IGenericElementAttributes extends IBobrilEvents { children?: IBobrilChildren; style?: IBobrilStyles | (() => IBobrilStyles); [name: string]: any; } declare global { namespace JSX { type Element = IBobrilNode<any>; interface ElementAttributesProperty { data: {}; } interface ElementChildrenAttribute { children: IBobrilChildren; } interface IntrinsicAttributes { key?: string; ref?: RefType; } interface IntrinsicClassAttributes<T> { key?: string; ref?: RefType; } interface IntrinsicElements { [name: string]: IGenericElementAttributes; } } }
the_stack
import type { Token } from "@saberhq/token-utils"; import { Fraction, ONE, TokenAmount, ZERO } from "@saberhq/token-utils"; import JSBI from "jsbi"; import mapValues from "lodash.mapvalues"; import type { IExchangeInfo } from "../entities/exchange"; import type { Fees } from "../state/fees"; import { computeD, computeY } from "./curve"; /** * Calculates the current virtual price of the exchange. * @param exchange * @returns */ export const calculateVirtualPrice = ( exchange: IExchangeInfo ): Fraction | null => { const amount = exchange.lpTotalSupply; if (amount === undefined || amount.equalTo(0)) { // pool has no tokens return null; } const price = new Fraction( computeD( exchange.ampFactor, exchange.reserves[0].amount.raw, exchange.reserves[1].amount.raw ), amount.raw ); return price; }; /** * Calculates the estimated output amount of a swap. * @param exchange * @param fromAmount * @returns */ export const calculateEstimatedSwapOutputAmount = ( exchange: IExchangeInfo, fromAmount: TokenAmount ): { [K in | "outputAmountBeforeFees" | "outputAmount" | "fee" | "lpFee" | "adminFee"]: TokenAmount; } => { const [fromReserves, toReserves] = fromAmount.token.equals( exchange.reserves[0].amount.token ) ? [exchange.reserves[0], exchange.reserves[1]] : [exchange.reserves[1], exchange.reserves[0]]; if (fromAmount.equalTo(0)) { const zero = new TokenAmount(toReserves.amount.token, ZERO); return { outputAmountBeforeFees: zero, outputAmount: zero, fee: zero, lpFee: zero, adminFee: zero, }; } const amp = exchange.ampFactor; const amountBeforeFees = JSBI.subtract( toReserves.amount.raw, computeY( amp, JSBI.add(fromReserves.amount.raw, fromAmount.raw), computeD(amp, fromReserves.amount.raw, toReserves.amount.raw) ) ); const outputAmountBeforeFees = new TokenAmount( toReserves.amount.token, amountBeforeFees ); const fee = new TokenAmount( toReserves.amount.token, exchange.fees.trade.asFraction.multiply(amountBeforeFees).toFixed(0) ); const adminFee = new TokenAmount( toReserves.amount.token, exchange.fees.adminTrade.asFraction.multiply(fee.raw).toFixed(0) ); const lpFee = fee.subtract(adminFee); const outputAmount = new TokenAmount( toReserves.amount.token, JSBI.subtract(amountBeforeFees, fee.raw) ); return { outputAmountBeforeFees, outputAmount, fee: fee, lpFee, adminFee, }; }; const N_COINS = JSBI.BigInt(2); export interface IWithdrawOneResult { withdrawAmount: TokenAmount; withdrawAmountBeforeFees: TokenAmount; swapFee: TokenAmount; withdrawFee: TokenAmount; lpSwapFee: TokenAmount; lpWithdrawFee: TokenAmount; adminSwapFee: TokenAmount; adminWithdrawFee: TokenAmount; } /** * Calculates the amount of tokens withdrawn if only withdrawing one token. * @returns */ export const calculateEstimatedWithdrawOneAmount = ({ exchange, poolTokenAmount, withdrawToken, }: { exchange: IExchangeInfo; poolTokenAmount: TokenAmount; withdrawToken: Token; }): IWithdrawOneResult => { if (poolTokenAmount.equalTo(0)) { // final quantities const quantities = { withdrawAmount: ZERO, withdrawAmountBeforeFees: ZERO, swapFee: ZERO, withdrawFee: ZERO, lpSwapFee: ZERO, lpWithdrawFee: ZERO, adminSwapFee: ZERO, adminWithdrawFee: ZERO, }; return mapValues(quantities, (q) => new TokenAmount(withdrawToken, q)); } const { ampFactor, fees } = exchange; const [baseReserves, quoteReserves] = [ exchange.reserves.find((r) => r.amount.token.equals(withdrawToken))?.amount .raw ?? ZERO, exchange.reserves.find((r) => !r.amount.token.equals(withdrawToken))?.amount .raw ?? ZERO, ]; const d_0 = computeD(ampFactor, baseReserves, quoteReserves); const d_1 = JSBI.subtract( d_0, JSBI.divide( JSBI.multiply(poolTokenAmount.raw, d_0), exchange.lpTotalSupply.raw ) ); const new_y = computeY(ampFactor, quoteReserves, d_1); // expected_base_amount = swap_base_amount * d_1 / d_0 - new_y; const expected_base_amount = JSBI.subtract( JSBI.divide(JSBI.multiply(baseReserves, d_1), d_0), new_y ); // expected_quote_amount = swap_quote_amount - swap_quote_amount * d_1 / d_0; const expected_quote_amount = JSBI.subtract( quoteReserves, JSBI.divide(JSBI.multiply(quoteReserves, d_1), d_0) ); // new_base_amount = swap_base_amount - expected_base_amount * fee / fee_denominator; const new_base_amount = new Fraction(baseReserves.toString(), 1).subtract( normalizedTradeFee(fees, N_COINS, expected_base_amount) ); // new_quote_amount = swap_quote_amount - expected_quote_amount * fee / fee_denominator; const new_quote_amount = new Fraction(quoteReserves.toString(), 1).subtract( normalizedTradeFee(fees, N_COINS, expected_quote_amount) ); const dy = new_base_amount.subtract( computeY( ampFactor, JSBI.BigInt(new_quote_amount.toFixed(0)), d_1 ).toString() ); const dy_0 = JSBI.subtract(baseReserves, new_y); // lp fees const swapFee = new Fraction(dy_0.toString(), 1).subtract(dy); const withdrawFee = dy.multiply(fees.withdraw.asFraction); // admin fees const adminSwapFee = swapFee.multiply(fees.adminTrade.asFraction); const adminWithdrawFee = withdrawFee.multiply(fees.adminWithdraw.asFraction); // final LP fees const lpSwapFee = swapFee.subtract(adminSwapFee); const lpWithdrawFee = withdrawFee.subtract(adminWithdrawFee); // final withdraw amount const withdrawAmount = dy.subtract(withdrawFee).subtract(swapFee); // final quantities const quantities = { withdrawAmount, withdrawAmountBeforeFees: dy, swapFee, withdrawFee, lpSwapFee, lpWithdrawFee, adminSwapFee, adminWithdrawFee, }; return mapValues( quantities, (q) => new TokenAmount(withdrawToken, q.toFixed(0)) ); }; /** * Compute normalized fee for symmetric/asymmetric deposits/withdraws */ export const normalizedTradeFee = ( { trade }: Fees, n_coins: JSBI, amount: JSBI ): Fraction => { const adjustedTradeFee = new Fraction( n_coins, JSBI.multiply(JSBI.subtract(n_coins, ONE), JSBI.BigInt(4)) ); return new Fraction(amount, 1).multiply(trade).multiply(adjustedTradeFee); }; export const calculateEstimatedWithdrawAmount = ({ poolTokenAmount, reserves, fees, lpTotalSupply, }: { /** * Amount of pool tokens to withdraw */ poolTokenAmount: TokenAmount; } & Pick<IExchangeInfo, "reserves" | "lpTotalSupply" | "fees">): { withdrawAmounts: readonly [TokenAmount, TokenAmount]; withdrawAmountsBeforeFees: readonly [TokenAmount, TokenAmount]; fees: readonly [TokenAmount, TokenAmount]; } => { if (lpTotalSupply.equalTo(0)) { const zero = reserves.map((r) => new TokenAmount(r.amount.token, ZERO)) as [ TokenAmount, TokenAmount ]; return { withdrawAmounts: zero, withdrawAmountsBeforeFees: zero, fees: zero, }; } const share = poolTokenAmount.divide(lpTotalSupply); const withdrawAmounts = reserves.map(({ amount }) => { const baseAmount = share.multiply(amount.raw); const fee = baseAmount.multiply(fees.withdraw.asFraction); return [ new TokenAmount( amount.token, JSBI.BigInt(baseAmount.subtract(fee).toFixed(0)) ), { beforeFees: JSBI.BigInt(baseAmount.toFixed(0)), fee: JSBI.BigInt(fee.toFixed(0)), }, ]; }) as [ [TokenAmount, { beforeFees: JSBI; fee: JSBI }], [TokenAmount, { beforeFees: JSBI; fee: JSBI }] ]; return { withdrawAmountsBeforeFees: withdrawAmounts.map( ([amt, { beforeFees }]) => new TokenAmount(amt.token, beforeFees) ) as [TokenAmount, TokenAmount], withdrawAmounts: [withdrawAmounts[0][0], withdrawAmounts[1][0]], fees: withdrawAmounts.map( ([amt, { fee }]) => new TokenAmount(amt.token, fee) ) as [TokenAmount, TokenAmount], }; }; /** * Calculate the estimated amount of LP tokens minted after a deposit. * @param exchange * @param depositAmountA * @param depositAmountB * @returns */ export const calculateEstimatedMintAmount = ( exchange: IExchangeInfo, depositAmountA: JSBI, depositAmountB: JSBI ): { mintAmountBeforeFees: TokenAmount; mintAmount: TokenAmount; fees: TokenAmount; } => { if (JSBI.equal(depositAmountA, ZERO) && JSBI.equal(depositAmountB, ZERO)) { const zero = new TokenAmount(exchange.lpTotalSupply.token, ZERO); return { mintAmountBeforeFees: zero, mintAmount: zero, fees: zero, }; } const amp = exchange.ampFactor; const [reserveA, reserveB] = exchange.reserves; const d0 = computeD(amp, reserveA.amount.raw, reserveB.amount.raw); const d1 = computeD( amp, JSBI.add(reserveA.amount.raw, depositAmountA), JSBI.add(reserveB.amount.raw, depositAmountB) ); if (JSBI.lessThan(d1, d0)) { throw new Error("New D cannot be less than previous D"); } const oldBalances = exchange.reserves.map((r) => r.amount.raw) as [ JSBI, JSBI ]; const newBalances = [ JSBI.add(reserveA.amount.raw, depositAmountA), JSBI.add(reserveB.amount.raw, depositAmountB), ] as const; const adjustedBalances = newBalances.map((newBalance, i) => { const oldBalance = oldBalances[i] as JSBI; const idealBalance = new Fraction(d1, d0).multiply(oldBalance); const difference = idealBalance.subtract(newBalance); const diffAbs = difference.greaterThan(0) ? difference : difference.multiply(-1); const fee = normalizedTradeFee( exchange.fees, N_COINS, JSBI.BigInt(diffAbs.toFixed(0)) ); return JSBI.subtract(newBalance, JSBI.BigInt(fee.toFixed(0))); }) as [JSBI, JSBI]; const d2 = computeD(amp, adjustedBalances[0], adjustedBalances[1]); const lpSupply = exchange.lpTotalSupply; const mintAmountRaw = JSBI.divide( JSBI.multiply(lpSupply.raw, JSBI.subtract(d2, d0)), d0 ); const mintAmount = new TokenAmount( exchange.lpTotalSupply.token, mintAmountRaw ); const mintAmountRawBeforeFees = JSBI.divide( JSBI.multiply(lpSupply.raw, JSBI.subtract(d1, d0)), d0 ); const fees = new TokenAmount( exchange.lpTotalSupply.token, JSBI.subtract(mintAmountRawBeforeFees, mintAmountRaw) ); const mintAmountBeforeFees = new TokenAmount( exchange.lpTotalSupply.token, mintAmountRawBeforeFees ); return { mintAmount, mintAmountBeforeFees, fees, }; };
the_stack
import { Component, OnInit, Input } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { MetadataService } from '../../../services/metadata.service'; import { CommandService } from '../../../services/command.service'; import { MessageService } from '../../../message/message.service'; import { DeviceResponse,MultiDeviceResponse } from '../../../contracts/v2/responses/device-response'; import { Device } from '../../../contracts/v2/device'; import { CoreCommand } from '../../../contracts/v2/core-command'; import { AutoEvent } from '../../../contracts/v2/auto-event'; import { DeviceProfile } from '../../../contracts/v2/device-profile'; import { DeviceProfileResponse,MultiDeviceProfileResponse } from '../../../contracts/v2/responses/device-profile-response'; import { DeviceCoreCommandResponse } from '../../../contracts/v2/responses/device-core-command-response'; import { EventResponse } from '../../../contracts/v2/responses/event-response'; import { BaseReading } from '../../../contracts/v2/reading'; import { CoreCommandParameter } from '../../../contracts/v2/core-command'; import { BaseResponse } from '../../../contracts/v2/common/base-response'; @Component({ selector: 'app-device-list', templateUrl: './device-list.component.html', styleUrls: ['./device-list.component.css'] }) export class DeviceListComponent implements OnInit { @Input() toolbars: boolean = true; @Input() enableSelectAll: boolean = true; deviceList: Device[] = []; associatedSvcName: string = ''; associatedProfileName: string = ''; selectedDevice: Device[] = []; associateDeviceProfile?: DeviceProfile; autoEvents?: AutoEvent[]; associatedAutoEventsDeviceName?: string; deviceCoreCommand?: CoreCommand[]; associatedCmdDeviceName?: string; associatedCmdDeviceId?: string; selectedCmd: CoreCommand = {} as CoreCommand; selectedCmdSetParams: CoreCommandParameter[] = []; cmdBinaryResponse: any; cmdBinaryResponseURL?: string; cmdGetResponse: any; cmdGetResponseRaw: any; cmdSetResponse: any; cmdSetResponseRaw: any; pagination: number = 1; pageLimit: number = 5; pageOffset: number = (this.pagination - 1) * this.pageLimit; constructor( private metaSvc: MetadataService, private cmdSvc: CommandService, private msgSvc: MessageService, private route: ActivatedRoute, private router: Router ) { } ngOnInit(): void { this.route.queryParams.subscribe(params => { if (params['svcName']) { this.associatedSvcName = params['svcName']; this.getDeviceListByAssociatedSvc(this.associatedSvcName); return } else if (params['profileName']) { this.associatedProfileName = params['profileName']; this.getDeviceListByAssociatedProfile(this.associatedProfileName); return } else { this.associatedSvcName = ''; this.associatedProfileName = ''; this.getDeviceListPagination(); } }); } renderPopoverComponent() { setTimeout(() => { $('[data-toggle="popover"]').popover({ trigger: 'hover' }); }, 250); } getDeviceList() { if (this.associatedSvcName !== '') { this.getDeviceListByAssociatedSvc(this.associatedSvcName); return } if (this.associatedProfileName !== '') { this.getDeviceListByAssociatedProfile(this.associatedSvcName); return } this.getDeviceListPagination(); } getDeviceListByAssociatedSvc(svcName: string) { this.metaSvc.findDevicesByServiceName(this.pageOffset, this.pageLimit, svcName).subscribe((data: MultiDeviceResponse) => this.deviceList = data.devices); } getDeviceListByAssociatedProfile(profileName: string) { this.metaSvc.findDevicesByProfileName(this.pageOffset, this.pageLimit, profileName).subscribe((data: MultiDeviceResponse) => this.deviceList = data.devices); } getDeviceListPagination() { this.metaSvc.allDevicesPagination(this.pageOffset, this.pageLimit).subscribe((data: MultiDeviceResponse) => { this.deviceList = data.devices; }); } refresh() { this.associatedProfileName = ''; this.associatedSvcName = ''; this.metaSvc.allDevicesPagination(0, this.pageLimit).subscribe((data: MultiDeviceResponse) => { this.deviceList = data.devices; this.msgSvc.success('refresh'); this.resetPagination(); }); } edit() { this.router.navigate(['../edit-device'], { relativeTo: this.route, queryParams: { 'deviceName': this.selectedDevice[0].name } }) } deleteConfirm() { $("#deleteConfirmDialog").modal('show'); } delete() { this.selectedDevice.forEach((d,i) => { this.metaSvc.deleteOneDeviceByName(d.name).subscribe(() => { this.selectedDevice.splice(i,1); this.deviceList.forEach((device: Device, index) => { if (device.id === d.id) { this.deviceList.splice(index, 1); this.msgSvc.success('remove device ', ` Name: ${device.name}`); return } }); }); }); //reset coreCommand to hide coreCommand card this.associatedCmdDeviceName = undefined; //reset to hide autoEvents card this.associatedAutoEventsDeviceName = undefined; $("#deleteConfirmDialog").modal('hide'); } checkAutoEvent(device: Device) { this.associatedAutoEventsDeviceName = device.name; this.autoEvents = device.autoEvents; //hide commands list when check auto evnets this.associatedCmdDeviceName = ""; } isCheckedAll(): boolean { let checkedAll = true; if (this.deviceList && this.deviceList.length === 0) { checkedAll = false } this.deviceList.forEach(device => { if (this.selectedDevice.findIndex(d => d.name === device.name) === -1) { checkedAll = false } }); return checkedAll } selectAll(event: any) { const checkbox = event.target; if (checkbox.checked) { this.deviceList.forEach(device => { if (this.selectedDevice.findIndex(d => d.name === device.name) !== -1) { return } this.selectedDevice.push(device); }); } else { this.deviceList.forEach(device => { this.selectedDevice.forEach((deviceSelected, index) => { if (deviceSelected.name === device.name) { this.selectedDevice.splice(index,1); } }) }); } } isChecked(id: string): boolean { return this.selectedDevice.findIndex(device => device.id === id) >= 0; } selectOne(event: any, device: Device) { const checkbox = event.target; if (checkbox.checked) { this.selectedDevice.push(device); return } this.selectedDevice.forEach((d,i) => { if (d.name === device.name) { this.selectedDevice.splice(i, 1); } }) } checkDeviceCommand(device: Device) { this.resetResponse(); this.metaSvc .findProfileByName(device.profileName) .subscribe((data:DeviceProfileResponse) => this.associateDeviceProfile = data.profile); this.cmdSvc.findDeviceAssociatedCommnadsByDeviceName(device.name).subscribe((data: DeviceCoreCommandResponse) => { //hide auto events list when check a new one device command this.associatedAutoEventsDeviceName = ""; this.associatedCmdDeviceName = data.deviceCoreCommand.deviceName; this.associatedCmdDeviceId = device.id; this.deviceCoreCommand = data.deviceCoreCommand.coreCommands; //init selectedCmd for first one this.selectedCmd = this.deviceCoreCommand[0]; this.selectedCmdSetParams = this.selectedCmd.parameters; }) } selectCmd(cmd: CoreCommand) { // this.renderPopoverComponent(); this.selectedCmd = cmd; this.selectedCmdSetParams = this.selectedCmd.parameters; this.resetResponse(); } resetResponse() { this.cmdGetResponse = ""; this.cmdGetResponseRaw = ""; this.cmdSetResponse = ""; this.cmdSetResponseRaw = ""; this.cmdBinaryResponse = true; this.cmdBinaryResponseURL = ""; } issueGetCmd() { let isBinary = false; // this.associateDeviceProfile?.deviceResources.forEach(resource => { // if (resource.name === this.selectedCmd?.name) { // this.associateDeviceProfile?.deviceCommands.forEach(dc => { // if (command.name === dc.name) { // this.associateDeviceProfile?.deviceResources.forEach(dr => { // if (dc.get[0].deviceResource == dr.name) { // if (dr.properties.value.type === 'Binary') { // isBinary = true; // return // } // } // return // }); // } // return // }); // } // }); if (isBinary) { this.cmdGetResponse = "no supported preview"; this.cmdGetResponseRaw = "no supported preview"; // this.cmdSvc.issueGetBinaryCmd(this.associatedCmdDeviceId as string, this.selectedCmd?.id as string) // .subscribe((data: any) => { // let result = CBOR.decode(data) // if (result.mediaType === "image/jpeg" || // result.mediaType === "image/jpg" || // result.mediaType === "image/png" // ) { // this.cmdBinaryResponse = result.binaryValue; // this.cmdBinaryResponseURL = URL.createObjectURL(this.cmdBinaryResponse); // } else { // this.cmdBinaryResponse = false; // } // }) return } // this.cmdSvc // .issueGetCmd(this.associatedCmdDeviceId as string, this.selectedCmd?.id as string) // .subscribe((data: any) => { // this.cmdGetResponseRaw = JSON.stringify(data, null, 3); // let result: any[] = []; // data.readings.forEach(function (reading: any) { // result.push(reading.value); // }); // this.cmdGetResponse = result.join(','); // }); this.cmdSvc .issueGetCmd(this.associatedCmdDeviceName as string, this.selectedCmd?.name as string) .subscribe((resp: EventResponse) => { this.cmdGetResponseRaw = JSON.stringify(resp.event.readings, null, 3); let result: any[] = []; resp.event.readings.forEach((reading: BaseReading) => { result.push(reading.value); }); this.cmdGetResponse = result.join(','); }) } issueSetCmd() { let self = this; let params: any = {}; this.selectedCmdSetParams?.forEach(function (p) { if ($(`#${p.resourceName}`).val().trim() !== "") { params[p.resourceName] = $(`#${p.resourceName}`).val().trim(); } }); this.cmdSvc .issueSetCmd(this.associatedCmdDeviceName as string, this.selectedCmd?.name as string, params) .subscribe((resp: BaseResponse) => { this.cmdSetResponseRaw = JSON.stringify(resp, null, 3); this.cmdSetResponse = resp.message }) } onPageSelected() { this.resetPagination(); this.getDeviceList(); } prePage() { this.setPagination(-1); this.getDeviceList(); } nextPage() { this.setPagination(1); this.getDeviceList(); } setPagination(n?: number) { if (n === 1) { this.pagination += 1; } else if (n === -1) { this.pagination -= 1; } this.pageOffset = (this.pagination - 1) * this.pageLimit; } resetPagination() { this.pagination = 1; this.pageOffset = (this.pagination - 1) * this.pageLimit; } }
the_stack
* @module DisplayStyles */ import { Id64, Id64String, NonFunctionPropertiesOf } from "@itwin/core-bentley"; import { ColorDef, ColorDefProps } from "./ColorDef"; import { TextureImageSpec } from "./RenderTexture"; /** Supported types of [[SkyBox]] images. * @see [[SkyBoxImageProps]]. * @public * @extensions */ export enum SkyBoxImageType { /** No image, indicating a [[SkyGradient]] should be displayed. */ None = 0, /** A single image mapped to the surface of a sphere. * @see [[SkySphere]]. */ Spherical = 1, /** @internal not yet supported */ Cylindrical = 2, /** Six images mapped to the faces of a cube. * @see [[SkyCube]]. */ Cube = 3, } /** JSON representation of the six images used by a [[SkyCube]]. * Each property specifies the image for a face of the cube as either an image URL, or the Id of a [Texture]($backend) element. * Each image must be square and have the same dimensions as all the other images. * @public * @extensions */ export interface SkyCubeProps { front: TextureImageSpec; back: TextureImageSpec; top: TextureImageSpec; bottom: TextureImageSpec; right: TextureImageSpec; left: TextureImageSpec; } /** JSON representation of the image used for a [[SkySphere]]. * @see [[SkyBoxProps.image]]. * @public */ export interface SkySphereImageProps { type: SkyBoxImageType.Spherical; texture: TextureImageSpec; /** @internal */ textures?: never; } /** JSON representation of the images used for a [[SkyCube]]. * @see [[SkyBoxProps.image]]. * @public */ export interface SkyCubeImageProps { type: SkyBoxImageType.Cube; textures: SkyCubeProps; /** @internal */ texture?: never; } /** JSON representation of the image(s) to be mapped to the surfaces of a [[SkyBox]]. * @see [[SkyBoxProps.image]]. * @public * @extensions */ export type SkyBoxImageProps = SkySphereImageProps | SkyCubeImageProps | { type?: SkyBoxImageType, texture?: never, textures?: never }; /** JSON representation of a [[SkyBox]] that can be drawn as the background of a [ViewState3d]($frontend). * An object of this type can describe one of several types of sky box: * - A cube with a texture image mapped to each face; or * - A sphere with a single texture image mapped to its surface; or * - A sphere with a two- or four-color vertical [[Gradient]] mapped to its surface. * * Whether cuboid or spherical, the skybox is drawn as if the viewer and the contents of the view are contained within its interior. * * For a two-color gradient, the gradient transitions smoothly from the nadir color at the bottom of the sphere to the zenith color at the top of the sphere. * The sky and ground colors are unused, as are the sky and ground exponents. * * For a four-color gradient, a "horizon" is produced on the equator of the sphere, where the ground color and sky color meet. The lower half of the sphere transitions * smoothly from the ground color at the equator to the nadir color at the bottom, and the upper half transitions from the sky color at the equator to the zenith color at * the top of the sphere. * * The color and exponent properties are unused if one or more texture images are supplied. * * @see [[DisplayStyle3dSettings.environment]] to define the skybox for a display style. * @public * @extensions */ export interface SkyBoxProps { /** Whether or not the skybox should be displayed. * Default: false. */ display?: boolean; /** For a [[SkyGradient]], if true, a 2-color gradient skybox is used instead of a 4-color. * Default: false. */ twoColor?: boolean; /** The color of the sky at the horizon. Unused unless this is a four-color [[SkyGradient]]. * Default: (143, 205, 255). */ skyColor?: ColorDefProps; /** The color of the ground at the horizon. Unused unless this is a four-color [[SkyGradient]]. * Default: (120, 143, 125). */ groundColor?: ColorDefProps; /** The color of the top of the sphere. * Default: (54, 117, 255). */ zenithColor?: ColorDefProps; /** The color of the bottom of the sphere. * Default: (40, 15, 0). */ nadirColor?: ColorDefProps; /** For a 4-color [[SkyGradient]], controls speed of change from sky color to zenith color; otherwise unused. * Default: 4.0. */ skyExponent?: number; /** For a 4-color [[SkyGradient]], controls speed of change from ground color to nadir color; otherwise unused. * Default: 4.0. */ groundExponent?: number; /** The image(s), if any, to be mapped to the surfaces of the sphere or cube. If undefined, the skybox will be displayed as a gradient instead. * Default: undefined. */ image?: SkyBoxImageProps; } const defaultGroundColor = ColorDef.from(143, 205, 125); const defaultZenithColor = ColorDef.from(54, 117, 255); const defaultNadirColor = ColorDef.from(40, 125, 0); const defaultSkyColor = ColorDef.from(142, 205, 255); const defaultExponent = 4.0; function colorDefFromJson(props?: ColorDefProps): ColorDef | undefined { return undefined !== props ? ColorDef.fromJSON(props) : undefined; } /** A type containing all of the properties and none of the methods of [[SkyGradient]] with `readonly` modifiers removed. * @see [[SkyGradient.create]] and [[SkyGradient.clone]]. * @public */ export type SkyGradientProperties = NonFunctionPropertiesOf<SkyGradient>; /** Describes how to map a two- or four-color [[Gradient]] to the interior of a sphere to produce a [[SkyBox]]. * @see [[SkyBox.gradient]]. * @public */ export class SkyGradient { public readonly twoColor: boolean; public readonly skyColor: ColorDef; public readonly groundColor: ColorDef; public readonly zenithColor: ColorDef; public readonly nadirColor: ColorDef; public readonly skyExponent: number; public readonly groundExponent: number; private constructor(args: Partial<SkyGradientProperties>) { this.twoColor = args.twoColor ?? false; this.skyColor = args.skyColor ?? defaultSkyColor; this.groundColor = args.groundColor ?? defaultGroundColor; this.nadirColor = args.nadirColor ?? defaultNadirColor; this.zenithColor = args.zenithColor ?? defaultZenithColor; this.skyExponent = args.skyExponent ?? defaultExponent; this.groundExponent = args.groundExponent ?? defaultExponent; } /** Default settings for a four-color gradient. */ public static readonly defaults = new SkyGradient({}); /** Create a new gradient. Any properties not specified by `props` are initialized to their default values. */ public static create(props?: Partial<SkyGradientProperties>): SkyGradient { return props ? new this(props) : this.defaults; } /** Create from JSON representation. */ public static fromJSON(props?: SkyBoxProps): SkyGradient { if (!props) return this.defaults; return new this({ twoColor: props.twoColor, skyExponent: props.skyExponent, groundExponent: props.groundExponent, skyColor: colorDefFromJson(props.skyColor), groundColor: colorDefFromJson(props.groundColor), nadirColor: colorDefFromJson(props.nadirColor), zenithColor: colorDefFromJson(props.zenithColor), }); } /** Create ea copy of this gradient, identical except for any properties explicitly specified by `changedProps`. * Any properties of `changedProps` explicitly set to `undefined` will be reset to their default values. */ public clone(changedProps: SkyGradientProperties): SkyGradient { return new SkyGradient({ ...this, ...changedProps }); } /** Convert to JSON representation. */ public toJSON(): SkyBoxProps { const props: SkyBoxProps = { skyColor: this.skyColor.toJSON(), groundColor: this.groundColor.toJSON(), nadirColor: this.nadirColor.toJSON(), zenithColor: this.zenithColor.toJSON(), }; if (this.groundExponent !== defaultExponent) props.groundExponent = this.groundExponent; if (this.skyExponent !== defaultExponent) props.skyExponent = this.skyExponent; if (this.twoColor) props.twoColor = this.twoColor; return props; } /** Returns true if this gradient is equivalent to the supplied gradient. */ public equals(other: SkyGradient): boolean { if (this === other) return true; return this.twoColor === other.twoColor && this.skyColor.equals(other.skyColor) && this.groundColor.equals(other.groundColor) && this.zenithColor.equals(other.zenithColor) && this.nadirColor.equals(other.nadirColor); } } /** Describes how to draw a representation of a sky, as part of an [[Environment]]. * @see [[SkyBoxProps]]. * @public */ export class SkyBox { /** The gradient settings, used if no cube or sphere images are supplied, or if the images cannot be loaded. */ public readonly gradient: SkyGradient; protected constructor(gradient: SkyGradient) { this.gradient = gradient; } /** Default settings for a four-color gradient. */ public static readonly defaults = new SkyBox(SkyGradient.defaults); /** Create a skybox that displays the specified gradient, or the default gradient if none is supplied. */ public static createGradient(gradient?: SkyGradient): SkyBox { return gradient ? new this(gradient) : this.defaults; } /** Create from JSON representation. */ public static fromJSON(props?: SkyBoxProps): SkyBox { const gradient = SkyGradient.fromJSON(props); if (props?.image) { switch (props.image.type) { case SkyBoxImageType.Spherical: if (undefined !== props.image.texture) return new SkySphere(props.image.texture, gradient); break; case SkyBoxImageType.Cube: { const tx = props.image.textures; if (tx && undefined !== tx.top && undefined !== tx.bottom && undefined !== tx.right && undefined !== tx.left && undefined !== tx.front && undefined !== tx.back) return new SkyCube(tx, gradient); break; } } } return this.createGradient(gradient); } /** Convert to JSON representation. * @param display If defined, the value to use for [[SkyBoxProps.display]]; otherwise, that property will be left undefined. */ public toJSON(display?: boolean): SkyBoxProps { const props = this.gradient.toJSON(); if (undefined !== display) props.display = display; return props; } /** @internal */ public get textureIds(): Iterable<Id64String> { return []; } } /** Describes how to draw a representation of a sky by mapping a single image to the interior of a sphere. * @public */ export class SkySphere extends SkyBox { /** The image to map to the interior of the sphere. */ public readonly image: TextureImageSpec; /** Create a new sky sphere using the specified image. * @param image The image to map to the interior of the sphere. * @param gradient Optionally overrides the default gradient settings used if the image cannot be obtained. */ public constructor(image: TextureImageSpec, gradient?: SkyGradient) { super(gradient ?? SkyGradient.defaults); this.image = image; } /** @internal override */ public override toJSON(display?: boolean): SkyBoxProps { const props = super.toJSON(display); props.image = { type: SkyBoxImageType.Spherical, texture: this.image, }; return props; } /** @internal */ public override get textureIds(): Iterable<Id64String> { return Id64.isValidId64(this.image) ? [this.image] : []; } } /** Describes how to draw a representation of a sky by mapping images to the interior faces of a cube. * The images are required to be *square*, and each image must have the same dimensions as the other images. * @public */ export class SkyCube extends SkyBox { /** The images to map to each face of the cube. */ public readonly images: SkyCubeProps; /** Create a new sky cube using the specified images. * @param images The images to map to each face of the cube. * @param Optionally overrides the default gradient settings used if the images cannot be obtained. */ public constructor(images: SkyCubeProps, gradient?: SkyGradient) { super(gradient ?? SkyGradient.defaults); this.images = { ...images }; } /** @internal override */ public override toJSON(display?: boolean): SkyBoxProps { const props = super.toJSON(display); props.image = { type: SkyBoxImageType.Cube, textures: { ...this.images }, }; return props; } /** @internal */ public override get textureIds(): Iterable<Id64String> { const imgs = this.images; return [imgs.front, imgs.back, imgs.top, imgs.bottom, imgs.left, imgs.right].filter((x) => Id64.isValidId64(x)); } }
the_stack
import { render } from '@testing-library/react'; import * as React from 'react'; import { act } from 'react-dom/test-utils'; // import { mount } from 'enzyme'; import { Transition } from '@uirouter/core'; import { makeTestRouter, muteConsoleErrors } from '../../__tests__/util'; import { TransitionPropCollisionError, UIRouter, UIView } from '../../components'; import { ReactStateDeclaration } from '../../interface'; const states: ReactStateDeclaration[] = [ { name: 'parent', component: () => ( <div> <span>parent</span> <UIView /> </div> ), }, { name: 'parent.child', component: () => <span>child</span>, }, { name: 'namedParent', component: () => ( <div> <span>namedParent</span> <UIView name="child1" /> <UIView name="child2" /> </div> ), }, { name: 'namedParent.namedChild', views: { child1: (() => <span>child1</span>) as any, child2: { component: () => <span>child2</span> }, }, }, { name: 'withrenderprop', component: ({ foo }) => ( <div> <span>withrenderprop</span> {foo} </div> ), }, ]; describe('<UIView>', () => { describe('(unmounted)', () => { let { router, routerGo, mountInRouter } = makeTestRouter([]); beforeEach(() => ({ router, routerGo, mountInRouter } = makeTestRouter(states))); it('renders an empty <div>', () => { const rendered = mountInRouter(<UIView />); expect(rendered.container.innerHTML).toBe('<div></div>'); }); it('renders its child if provided', () => { let rendered = mountInRouter( <UIView> <span /> </UIView> ); expect(rendered.container.innerHTML).toBe('<span></span>'); }); it('injects props correctly', () => { let rendered = mountInRouter( <UIView className="myClass" style={{ margin: 5 }}> <span /> </UIView> ); expect(rendered.container.innerHTML).toBe('<span class="myClass" style="margin: 5px;"></span>'); }); }); describe('(mounted)', () => { let { router, routerGo, mountInRouter } = makeTestRouter([]); beforeEach(() => ({ router, routerGo, mountInRouter } = makeTestRouter(states))); it('renders its State Component', async () => { const rendered = mountInRouter(<UIView />); await routerGo('parent'); expect(rendered.container.innerHTML).toEqual(`<div><span>parent</span><div></div></div>`); }); describe('injects the right props:', () => { let lastProps = undefined; const Comp = (props) => { lastProps = props; return <span>component</span>; }; beforeEach(() => { lastProps = undefined; router.stateRegistry.register({ name: '__state', component: Comp, resolve: [ { resolveFn: () => 'resolveval', token: 'myresolve' }, { resolveFn: () => true, token: 'otherresolve' }, { resolveFn: () => true, token: {} }, ], } as ReactStateDeclaration); }); it('injects the transition', async () => { await routerGo('__state'); mountInRouter(<UIView />); expect(lastProps.transition).toEqual(expect.any(Transition)); }); it('injects custom resolves if the token is a string', async () => { await routerGo('__state'); mountInRouter(<UIView />); expect(lastProps.myresolve).toBe('resolveval'); expect(lastProps.otherresolve).toBe(true); }); it('injects className and style props', async () => { await routerGo('__state'); mountInRouter(<UIView className="foo" style={{ color: 'red' }} />); expect(lastProps.className).toBe('foo'); expect(lastProps.style).toEqual({ color: 'red' }); }); // TODO: Can these tests be reimplemented? Is it worth trying or should they be deleted? // it('provides a stable key prop', async () => { // await routerGo('__state'); // const rendered = mountInRouter(<UIView />); // const initialKey = rendered.find(Comp).key(); // rendered.setProps({ otherProp: 123 }); // rendered.update(); // expect(rendered.find(Comp).key()).toBe(initialKey); // }); // it('updates the key prop on reload', async () => { // await routerGo('__state'); // const rendered = mountInRouter(<UIView />); // const initialKey = rendered.find(Comp).key(); // rendered.setProps({ otherProp: 123 }); // expect(rendered.find(Comp).key()).toBe(initialKey); // await act(() => router.stateService.reload()); // rendered.update(); // expect(rendered.find(Comp).key()).not.toBe(initialKey); // }); }); it('throws if a resolve uses the token `transition`', async () => { const Comp = () => <span>component</span>; router.stateRegistry.register({ name: '__state', component: Comp, resolve: [{ token: 'transition', resolveFn: () => null }], } as ReactStateDeclaration); await routerGo('__state'); muteConsoleErrors(); expect(() => mountInRouter(<UIView />)).toThrow(TransitionPropCollisionError); }); it('renders nested State Components', async () => { await routerGo('parent.child'); const rendered = mountInRouter(<UIView />); expect(rendered.container.innerHTML).toEqual(`<div><span>parent</span><span>child</span></div>`); }); it('renders multiple nested unmounted <UIView>', async () => { await routerGo('namedParent'); const rendered = mountInRouter(<UIView />); expect(rendered.container.innerHTML).toEqual(`<div><span>namedParent</span><div></div><div></div></div>`); }); it('renders multiple nested mounted <UIView>', async () => { await routerGo('namedParent.namedChild'); const rendered = mountInRouter(<UIView />); expect(rendered.container.innerHTML).toEqual( `<div><span>namedParent</span><span>child1</span><span>child2</span></div>` ); }); it('unmounts State Component when changing state', async () => { const rendered = mountInRouter(<UIView />); await routerGo('parent.child'); expect(rendered.container.innerHTML).toEqual(`<div><span>parent</span><span>child</span></div>`); await routerGo('parent'); expect(rendered.container.innerHTML).toEqual(`<div><span>parent</span><div></div></div>`); }); describe('uiCanExit', () => { function makeSpyComponent(uiCanExitSpy) { return class Comp extends React.Component<any, any> { uiCanExit() { return uiCanExitSpy(); } render() { return <span>UiCanExitHookComponent</span>; } }; } it('calls the uiCanExit function of a Class Component when unmounting', async () => { const uiCanExitSpy = jest.fn(); router.stateRegistry.register({ name: '__state', component: makeSpyComponent(uiCanExitSpy) } as any); await routerGo('__state'); const rendered = mountInRouter(<UIView />); expect(rendered.container.innerHTML).toEqual('<span>UiCanExitHookComponent</span>'); await routerGo('parent'); expect(rendered.container.innerHTML).toContain('parent'); expect(uiCanExitSpy).toBeCalled(); }); it('calls uiCanExit function of a React.forwardRef() Class Component when unmounting', async () => { const uiCanExitSpy = jest.fn(); const Comp = makeSpyComponent(uiCanExitSpy); const ForwardRef = React.forwardRef((props, ref: any) => <Comp {...props} ref={ref} />); router.stateRegistry.register({ name: '__state', component: ForwardRef } as ReactStateDeclaration); await routerGo('__state'); const rendered = mountInRouter(<UIView />); expect(rendered.container.innerHTML).toEqual('<span>UiCanExitHookComponent</span>'); await routerGo('parent'); expect(rendered.container.innerHTML).toContain('parent'); expect(uiCanExitSpy).toBeCalled(); }); it('does not transition if uiCanExit function of its State Component returns false', async () => { let uiCanExitSpy = jest.fn().mockImplementation(() => false); router.stateRegistry.register({ name: '__state', component: makeSpyComponent(uiCanExitSpy) } as any); await routerGo('__state'); const rendered = mountInRouter(<UIView />); expect(rendered.container.innerHTML).toEqual('<span>UiCanExitHookComponent</span>'); try { await routerGo('parent'); } catch (error) {} expect(rendered.container.innerHTML).toEqual('<span>UiCanExitHookComponent</span>'); expect(uiCanExitSpy).toBeCalled(); }); }); it('deregisters the UIView when unmounted', () => { const Component = (props) => <UIRouter router={router}>{props.show ? <UIView /> : <div />}</UIRouter>; const deregisterSpy = jest.fn(); jest.spyOn(router.viewService, 'registerUIView').mockImplementation(() => deregisterSpy); const rendered = render(<Component show={true} />); rendered.rerender(<Component show={false} />); expect(deregisterSpy).toHaveBeenCalled(); }); it('renders the component using the render prop', async () => { const rendered = render( <UIRouter router={router}> <UIView render={(Comp, props) => <Comp {...props} foo={<span>bar</span>} />} /> </UIRouter> ); await routerGo('withrenderprop'); expect(rendered.container.innerHTML).toEqual(`<div><span>withrenderprop</span><span>bar</span></div>`); }); it('unmounts the State Component when calling stateService.reload(true)', async () => { const componentDidMountSpy = jest.fn(); const componentWillUnmountSpy = jest.fn(); class TestUnmountComponent extends React.Component { componentDidMount = componentDidMountSpy; componentWillUnmount = componentWillUnmountSpy; render() { return <div />; } } const testState = { name: 'testunmount', component: TestUnmountComponent, } as ReactStateDeclaration; router.stateRegistry.register(testState); await routerGo('testunmount'); const rendered = mountInRouter(<UIView />); expect(componentDidMountSpy).toHaveBeenCalledTimes(1); await act(() => router.stateService.reload('testunmount') as any); expect(componentWillUnmountSpy).toHaveBeenCalledTimes(1); expect(componentDidMountSpy).toHaveBeenCalledTimes(2); rendered.unmount(); }); }); });
the_stack
import path from "path"; import wretch from "wretch"; import {DOMParser} from "xmldom"; // @ts-ignore import domino from "domino-ext"; import tumblr from "tumblr.js"; import Snoowrap from "snoowrap"; import * as imgur from "imgur"; import * as Twitter from "twitter"; import {IgApiClient} from "instagram-private-api"; import {IF, RF, RT, ST, WF} from "../../data/const"; import Config from "../../data/Config"; import LibrarySource from "../../data/LibrarySource"; const pm = (object: any, resolve?: Function) => { if (object?.source && object?.data && object?.allURLs && object?.weight && object?.helpers) { const source = object.source; if (source.blacklist && source.blacklist.length > 0) { object.data = object.data.filter((url: string) => !source.blacklist.includes(url)); } object.allURLs = processAllURLs(object.data, object.allURLs, object.source, object.weight, object.helpers); } if (!!resolve) { resolve({data: object}); } else { // @ts-ignore postMessage(object); } } export const processAllURLs = (data: string[], allURLs: Map<string, string[]>, source: LibrarySource, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}): Map<string, string[]> => { let newAllURLs = new Map(allURLs); if (helpers.next != null && helpers.next <= 0) { if (weight == WF.sources) { newAllURLs.set(source.url, data); } else { for (let d of data) { newAllURLs.set(d, [source.url]); } } } else { if (weight == WF.sources) { let sourceURLs = newAllURLs.get(source.url); if (!sourceURLs) sourceURLs = []; newAllURLs.set(source.url, sourceURLs.concat(data.filter((u: string) => { const fileName = getFileName(u); const found = sourceURLs.map((u: string) => getFileName(u)).includes(fileName); return !found; }))); } else { for (let d of data.filter((u: string) => { const fileName = getFileName(u); const found = Array.from(newAllURLs.keys()).map((u: string) => getFileName(u)).includes(fileName); return !found; })) { newAllURLs.set(d, [source.url]); } } } return newAllURLs; } let redditAlerted = false; let tumblrAlerted = false; let tumblr429Alerted = false; let twitterAlerted = false; let instagramAlerted = false; let hydrusAlerted = false; let piwigoAlerted = false; export const reset = () => { redditAlerted = false; tumblrAlerted = false; tumblr429Alerted = false; twitterAlerted = false; instagramAlerted = false; hydrusAlerted = false; piwigoAlerted = false; } export const loadRemoteImageURLList = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const url = source.url; wretch(url) .get() .text(data => { const lines = data.match(/[^\r\n]+/g).filter((line) => line.startsWith("http://") || line.startsWith("https://") || line.startsWith("file:///")); if (lines.length > 0) { let convertedSource = Array<string>(); let convertedCount = 0; for (let url of lines) { convertURL(url).then((urls: Array<string>) => { convertedSource = convertedSource.concat(urls); convertedCount++; if (convertedCount == lines.length) { helpers.count = filterPathsToJustPlayable(IF.any, convertedSource, true).length; pm({ data: filterPathsToJustPlayable(filter, convertedSource, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: 0, }, resolve); } }) .catch ((error: any) => { convertedCount++; if (convertedCount == lines.length) { helpers.count = filterPathsToJustPlayable(IF.any, convertedSource, true).length; pm({ error: error.message, data: filterPathsToJustPlayable(filter, convertedSource, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: 0, }, resolve); } }); } } else { pm({ warning: "No lines in" + url + " are links or files", helpers: helpers, source: source, timeout: 0, }, resolve); } }) .catch((e) => { pm({ error: e.message, helpers: helpers, source: source, timeout: 0, }, resolve); }); } export const loadTumblr = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 3000; let configured = config.remoteSettings.tumblrOAuthToken != "" && config.remoteSettings.tumblrOAuthTokenSecret != ""; if (configured) { const url = source.url; const client = tumblr.createClient({ consumer_key: config.remoteSettings.tumblrKey, consumer_secret: config.remoteSettings.tumblrSecret, token: config.remoteSettings.tumblrOAuthToken, token_secret: config.remoteSettings.tumblrOAuthTokenSecret, }); // TumblrID takes the form of <blog_name>.tumblr.com let tumblrID = url.replace(/https?:\/\//, ""); tumblrID = tumblrID.replace("/", ""); if (tumblr429Alerted) { pm({ helpers: helpers, source: source, timeout: timeout, }, resolve); return; } client.blogPosts(tumblrID, {offset: helpers.next*20}, (err, data) => { if (err) { let systemMessage = undefined; if (err.message.includes("429 Limit Exceeded") && !tumblr429Alerted && helpers.next == 0) { if (!config.remoteSettings.silenceTumblrAlert) { systemMessage = "Tumblr has temporarily throttled your FlipFlip due to high traffic. Try again in a few minutes or visit Settings to try a different Tumblr API key."; } tumblr429Alerted = true; } pm({ error: err.message, systemMessage: systemMessage, helpers: helpers, source: source, timeout: timeout, }, resolve); return; } // End loop if we're at end of posts if (data.posts.length == 0) { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); return; } let images = []; for (let post of data.posts) { // Sometimes photos are listed separately if (post.photos) { for (let photo of post.photos) { images.push(photo.original_size.url); } } if (post.player) { for (let embed of post.player) { const regex = /<iframe[^(?:src|\/>)]*src=["']([^"']*)[^(?:\/>)]*\/?>/g; let imageSource; while ((imageSource = regex.exec(embed.embed_code)) !== null) { images.push(imageSource[1]); } } } if (post.body) { const regex = /<img[^(?:src|\/>)]*src=["']([^"']*)[^>]*>/g; let imageSource; while ((imageSource = regex.exec(post.body)) !== null) { images.push(imageSource[1]); } const regex2 = /<source[^(?:src|\/>)]*src=["']([^"']*)[^>]*>/g; while ((imageSource = regex2.exec(post.body)) !== null) { images.push(imageSource[1]); } } if (post.video_url) { images.push(post.video_url); } } if (images.length > 0) { let convertedSource = Array<string>(); let convertedCount = 0; for (let url of images) { convertURL(url).then((urls: Array<string>) => { convertedSource = convertedSource.concat(urls); convertedCount++; if (convertedCount == images.length) { helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, convertedSource, true).length; pm({ data: filterPathsToJustPlayable(filter, convertedSource, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) .catch ((error: any) => { convertedCount++; if (convertedCount == images.length) { helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, convertedSource, true).length; pm({ error: error.message, data: filterPathsToJustPlayable(filter, convertedSource, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } else { let systemMessage = undefined; if (!tumblrAlerted) { systemMessage = "You haven't authorized FlipFlip to work with Tumblr yet.\nVisit Settings to authorize Tumblr."; tumblrAlerted = true; } pm({ systemMessage: systemMessage, helpers: helpers, source: source, timeout: timeout, }, resolve); } } export const loadReddit = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 3000; let configured = config.remoteSettings.redditRefreshToken != ""; if (configured) { const url = source.url; const reddit = new Snoowrap({ userAgent: config.remoteSettings.redditUserAgent, clientId: config.remoteSettings.redditClientID, clientSecret: "", refreshToken: config.remoteSettings.redditRefreshToken, }); if (url.includes("/r/")) { const handleSubmissions = (submissionListing: any) => { if (submissionListing.length > 0) { let convertedListing = Array<string>(); let convertedCount = 0; for (let s of submissionListing) { convertURL(s.url).then((urls: Array<string>) => { convertedListing = convertedListing.concat(urls); convertedCount++; if (convertedCount == submissionListing.length) { helpers.next = submissionListing[submissionListing.length - 1].name; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, convertedListing, true).length; pm({ data: filterPathsToJustPlayable(filter, convertedListing, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) .catch ((error: any) => { convertedCount++; if (convertedCount == submissionListing.length) { helpers.next = submissionListing[submissionListing.length - 1].name; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, convertedListing, true).length; pm({ error: error.message, data: filterPathsToJustPlayable(filter, convertedListing, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }; const errorSubmission = (error: any) => { pm({ error: error.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }; switch (source.redditFunc) { default: case RF.hot: reddit.getSubreddit(getFileGroup(url)).getHot({after: helpers.next}) .then(handleSubmissions) .catch(errorSubmission); break; case RF.new: reddit.getSubreddit(getFileGroup(url)).getNew({after: helpers.next}) .then(handleSubmissions) .catch(errorSubmission); break; case RF.top: const time = source.redditTime == null ? RT.day : source.redditTime; reddit.getSubreddit(getFileGroup(url)).getTop({time: time, after: helpers.next}) .then(handleSubmissions) .catch(errorSubmission); break; case RF.controversial: reddit.getSubreddit(getFileGroup(url)).getControversial({after: helpers.next}) .then(handleSubmissions) .catch(errorSubmission); break; case RF.rising: reddit.getSubreddit(getFileGroup(url)).getRising({after: helpers.next}) .then(handleSubmissions) .catch(errorSubmission); break; } } else if (url.includes("/saved")) { reddit.getUser(getFileGroup(url)).getSavedContent({after: helpers.next}) .then((submissionListing: any) => { if (submissionListing.length > 0) { let convertedListing = Array<string>(); let convertedCount = 0; for (let s of submissionListing) { convertURL(s.url).then((urls: Array<string>) => { convertedListing = convertedListing.concat(urls); convertedCount++; if (convertedCount == submissionListing.length) { helpers.next = submissionListing[submissionListing.length - 1].name; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, convertedListing, true).length; pm({ data: filterPathsToJustPlayable(filter, convertedListing, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) .catch ((error: any) => { convertedCount++; if (convertedCount == submissionListing.length) { helpers.next = submissionListing[submissionListing.length - 1].name; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, convertedListing, true).length; pm({ error: error.message, data: filterPathsToJustPlayable(filter, convertedListing, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }).catch((err: any) => { pm({ error: err.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }); } else if (url.includes("/user/") || url.includes("/u/")) { reddit.getUser(getFileGroup(url)).getSubmissions({after: helpers.next}) .then((submissionListing: any) => { if (submissionListing.length > 0) { let convertedListing = Array<string>(); let convertedCount = 0; for (let s of submissionListing) { convertURL(s.url).then((urls: Array<string>) => { convertedListing = convertedListing.concat(urls); convertedCount++; if (convertedCount == submissionListing.length) { helpers.next = submissionListing[submissionListing.length - 1].name; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, convertedListing, true).length; pm({ data: filterPathsToJustPlayable(filter, convertedListing, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) .catch ((error: any) => { convertedCount++; if (convertedCount == submissionListing.length) { helpers.next = submissionListing[submissionListing.length - 1].name; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, convertedListing, true).length; pm({ error: error.message, data: filterPathsToJustPlayable(filter, convertedListing, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }).catch((err: any) => { pm({ error: err.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }); } } else { let systemMessage = undefined if (!redditAlerted) { systemMessage = "You haven't authorized FlipFlip to work with Reddit yet.\nVisit Settings to authorize Reddit."; redditAlerted = true; } pm({ systemMessage: systemMessage, helpers: helpers, source: source, timeout: timeout, }, resolve); } } export const loadImageFap = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; const url = source.url; if (url.includes("/pictures/")) { wretch("https://www.imagefap.com/gallery/" + getFileGroup(url) + "?view=2") .get() .setTimeout(15000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { let imageEls = domino.createWindow(html).document.querySelectorAll(".expp-container > form > table > tbody > tr > td"); let images = Array<string>(); if (imageEls.length > 0) { helpers.count = imageEls.length; let imageCount = helpers.next > 0 ? helpers.next : 0; const imageLoop = () => { const image = imageEls.item(imageCount++); wretch("https://www.imagefap.com/photo/" + image.id + "/") .get() .text((html) => { let captcha = undefined; let contentURL = html.match("\"contentUrl\": \"(.*?)\","); if (contentURL != null) { images.push(contentURL[1]); } else { captcha = "https://www.imagefap.com/photo/" + image.id + "/"; } if (imageCount == imageEls.length || captcha != null) { helpers.next = imageCount == imageEls.length ? null : imageCount; pm({ captcha: captcha, data: filterPathsToJustPlayable(filter, images, false), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else { setTimeout(imageLoop, 200); } }); } imageLoop(); } else { let captcha = undefined; if (html.includes("Enter the captcha")) { helpers.count = source.count; captcha = "https://www.imagefap.com/gallery/" + getFileGroup(url) + "?view=2"; images = allURLs.get(url); pm({warning: source.url + " - blocked due to captcha"}, resolve); } else { helpers.next = null; } pm({ captcha: captcha, data: images, allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } else if (url.includes("/organizer/")) { if (helpers.next == 0) { helpers.next = [0, 0, 0]; } wretch(url + "?page=" + helpers.next[0]) .get() .setTimeout(10000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { let albumEls = domino.createWindow(html).document.querySelectorAll("td.blk_galleries > font > a.blk_galleries"); if (albumEls.length == 0) { let captcha = undefined; if (html.includes("Enter the captcha")) { helpers.count = source.count; captcha = "https://www.imagefap.com/gallery/" + getFileGroup(url) + "?view=2"; pm({warning: source.url + " - blocked due to captcha"}, resolve); } helpers.next = null; pm({ captcha: captcha, data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else if (albumEls.length > helpers.next[1]) { let albumEl = albumEls[helpers.next[1]]; let albumID = albumEl.getAttribute("href").substring(albumEl.getAttribute("href").lastIndexOf("/") + 1); wretch("https://www.imagefap.com/gallery/" + albumID + "?view=2") .get() .setTimeout(15000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { let imageEls = domino.createWindow(html).document.querySelectorAll(".expp-container > form > table > tbody > tr > td"); let images = Array<string>(); if (imageEls.length > 0) { let imageCount = helpers.next[2]; const imageLoop = () => { const image = imageEls.item(imageCount++); wretch("https://www.imagefap.com/photo/" + image.id + "/") .get() .text((html) => { let captcha = undefined; let contentURL = html.match("\"contentUrl\": \"(.*?)\","); if (contentURL != null) { images.push(contentURL[1]); } else { captcha = "https://www.imagefap.com/photo/" + image.id + "/"; } if (imageCount == imageEls.length || captcha != null) { if (imageCount == imageEls.length) { helpers.next[2] = 0; helpers.next[1] += 1; helpers.count += imageEls.length; } else { helpers.next = imageCount; } pm({ captcha: captcha, data: filterPathsToJustPlayable(filter, images, false), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else { setTimeout(imageLoop, 200); } }); } imageLoop(); } else { let captcha = undefined; if (html.includes("Enter the captcha")) { helpers.count = source.count; captcha = "https://www.imagefap.com/gallery/" + getFileGroup(url) + "?view=2"; pm({warning: source.url + " - blocked due to captcha"}, resolve); } else { helpers.next[1] += 1; } pm({ captcha: captcha, data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } else { let images = Array<string>(); let captcha = undefined; if (html.includes("Enter the captcha")) { helpers.count = source.count; captcha = "https://www.imagefap.com/gallery/" + getFileGroup(url) + "?view=2"; images = allURLs.get(url); pm({warning: source.url + " - blocked due to captcha"}, resolve); } else { helpers.next[0] += 1; helpers.next[1] = 0; } pm({ captcha: captcha, data: images, allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) .catch((e) => { pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }); } else if (url.includes("/video.php?vid=")) { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); // This doesn't work anymore due to src url requiring referer /*wretch(url) .get() .setTimeout(10000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { const findVideoURLs = /url: '(https:\/\/cdn-fck\.moviefap\.com\/moviefap\/.*)',/g.exec(html); if (findVideoURLs) { let videoURLs = Array<string>(); for (let v of findVideoURLs) { if (!v.startsWith('url:')) { videoURLs.push(v); } } helpers.next = null; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, videoURLs, false).length; pm({ data: filterPathsToJustPlayable(filter, videoURLs, false), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } });*/ } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } } export const loadSexCom = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; const url = source.url; // This doesn't work anymore due to src url requiring referer helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); /*let requestURL; if (url.includes("/user/")) { requestURL = "https://www.sex.com/user/" + getFileGroup(url) + "?page=" + (helpers.next + 1); } else if (url.includes("/gifs/") || url.includes("/pics/") || url.includes("/videos/")) { requestURL = "https://www.sex.com/" + getFileGroup(url) + "?page=" + (helpers.next + 1); } wretch(requestURL) .get() .setTimeout(5000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { let imageEls = domino.createWindow(html).document.querySelectorAll(".small_pin_box > .image_wrapper > img"); if (imageEls.length > 0) { let videos = Array<string>(); let images = Array<string>(); for (let i = 0; i < imageEls.length; i++) { const image = imageEls.item(i); if (image.nextElementSibling || image.previousElementSibling) { videos.push(image.parentElement.getAttribute("href")); } else { images.push(image.getAttribute("data-src")); } } if (videos.length == 0) { helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, false).length; pm({ data: filterPathsToJustPlayable(filter, images, false), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else { const validImages = filterPathsToJustPlayable(filter, images, false); images = []; let count = 0; for (let videoURL of videos) { wretch("https://www.sex.com" + videoURL) .get() .setTimeout(5000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { count += 1; let vidID = null; const vidIDRegex = /\/video\/stream\/(\d+)/g; let regexResult = vidIDRegex.exec(html); if (regexResult != null) { vidID = regexResult[1]; } let date = null; const dateRegex = /\d{4}\/\d{2}\/\d{2}/g; regexResult = dateRegex.exec(html); if (regexResult != null) { date = regexResult[0]; } if (vidID != null && date != null) { images.push("https://videos1.sex.com/stream/" + date + "/" + vidID +".mp4"); } if (count == videos.length) { const validVideos = filterPathsToJustPlayable(IF.any, images, true); const filePaths = validImages.concat(validVideos); helpers.next = helpers.next + 1; helpers.count = helpers.count + filePaths.length; pm({ data: filePaths, allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } } } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } });*/ } export const loadImgur = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 3000; const url = source.url; imgur.getAlbumInfo(getFileGroup(url)) .then((json: any) => { const images = json.data.images.map((i: any) => i.link); helpers.next = null; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); }) .catch((err: any) => { pm({ error: err.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }); } export const loadTwitter = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 3000; let configured = config.remoteSettings.twitterAccessTokenKey != "" && config.remoteSettings.twitterAccessTokenSecret != ""; if (configured) { const includeRetweets = source.includeRetweets; const includeReplies = source.includeReplies; const url = source.url; const twitter = new Twitter({ consumer_key: config.remoteSettings.twitterConsumerKey, consumer_secret: config.remoteSettings.twitterConsumerSecret, access_token_key: config.remoteSettings.twitterAccessTokenKey, access_token_secret: config.remoteSettings.twitterAccessTokenSecret, }); twitter.get('statuses/user_timeline', helpers.next == 0 ? {screen_name: getFileGroup(url), count: 200, exclude_replies: !includeReplies, include_rts: includeRetweets, tweet_mode: 'extended'} : {screen_name: getFileGroup(url), count: 200, exclude_replies: !includeReplies, include_rts: includeRetweets, tweet_mode: 'extended', max_id: helpers.next}, (error: any, tweets: any) => { if (error) { pm({ error: error.message, helpers: helpers, source: source, timeout: timeout, }, resolve); return; } let images = Array<string>(); let lastID = ""; for (let t of tweets) { // Skip FanCentro/OnlyFans/ClipTeez posts if (/href="https?:\/\/(fancentro\.com|onlyfans\.com|mykink\.xxx)\/?"/.exec(t.source) != null) continue; if (t.extended_entities && t.extended_entities.media) { for (let m of t.extended_entities.media) { let url; if (m.video_info) { url = m.video_info.variants[0].url; } else { url = m.media_url; } if (url.includes("?")) { url = url.substring(0, url.lastIndexOf("?")); } images.push(url); } } else if (t.entities.media) { for (let m of t.entities.media) { images.push(m.media_url); } } lastID = t.id; } if (lastID == helpers.next) { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else { helpers.next = lastID; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) } else { let systemMessage = undefined; if (!twitterAlerted) { systemMessage = "You haven't authorized FlipFlip to work with Twitter yet.\nVisit Settings to authorize Twitter."; twitterAlerted = true; } pm({ systemMessage: systemMessage, helpers: helpers, source: source, timeout: timeout, }, resolve); } } export const loadDeviantArt = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 3000; const url = source.url; wretch("https://backend.deviantart.com/rss.xml?type=deviation&q=by%3A" + getFileGroup(url) + "+sort%3Atime+meta%3Aall" + (helpers.next != 0 ? "&offset=" + helpers.next : "")) .get() .setTimeout(5000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((text) => { const xml = new DOMParser().parseFromString(text, "text/xml"); let hasNextPage = false; const pages = xml.getElementsByTagName("atom:link"); for (let l = 0; l < pages.length; l++) { if (pages[l].getAttribute("rel") == "next") hasNextPage = true; } let images = Array<string>(); const items = xml.getElementsByTagName("item"); for (let i = 0; i < items.length; i++) { helpers.next+=1; const contents = items[i].getElementsByTagName("media:content"); for (let c = 0; c < contents.length; c++) { const content = contents[c]; if (content.getAttribute("medium") == "image") { images.push(content.getAttribute("url")); } } } if (!hasNextPage) { helpers.next = null; } helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, false).length; pm({ data: filterPathsToJustPlayable(filter, images, false), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); }); } let ig: IgApiClient = null; let session: any = null; export const loadInstagram = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 3000; const configured = config.remoteSettings.instagramUsername != "" && config.remoteSettings.instagramPassword != ""; if (configured) { const url = source.url; const processItems = (items: any, helpers: {next: any, count: number, retries: number, uuid: string}) => { let images = Array<string>(); for (let item of items) { if (item.carousel_media) { for (let media of item.carousel_media) { images.push(media.image_versions2.candidates[0].url); } } if (item.video_versions) { images.push(item.video_versions[0].url); } else if (item.image_versions2) { images.push(item.image_versions2.candidates[0].url); } } // Strict filter won't work because instagram media needs the extra parameters on the end helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, false).length; pm({ data: filterPathsToJustPlayable(filter, images, false), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); }; if (ig == null) { ig = new IgApiClient(); ig.state.generateDevice(config.remoteSettings.instagramUsername); ig.account.login(config.remoteSettings.instagramUsername, config.remoteSettings.instagramPassword).then((loggedInUser) => { ig.state.serializeCookieJar().then((cookies) => { session = JSON.stringify(cookies); ig.user.getIdByUsername(getFileGroup(url)).then((id) => { const userFeed = ig.feed.user(id); userFeed.items().then((items) => { helpers.next = [id, userFeed.serialize()]; processItems(items, helpers); }).catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); }).catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); }).catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); }).catch((e) => { pm({ error: e.message, systemMessage: e + "\n\nVisit Settings to authorize Instagram and attempt to resolve this issue.", helpers: helpers, source: source, timeout: timeout, }, resolve); ig = null; }); } else if (helpers.next == 0) { ig.user.getIdByUsername(getFileGroup(url)).then((id) => { const userFeed = ig.feed.user(id); userFeed.items().then((items) => { helpers.next = [id, userFeed.serialize()]; processItems(items, helpers); }).catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); }).catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } else { ig.state.deserializeCookieJar(JSON.parse(session)).then((data) => { const id = helpers.next[0]; const feedSession = helpers.next[1]; const userFeed = ig.feed.user(id); userFeed.deserialize(feedSession); if (!userFeed.isMoreAvailable()) { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); return; } userFeed.items().then((items) => { helpers.next = [id, userFeed.serialize()]; processItems(items, helpers); }).catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); }).catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } } else { let systemMessage = undefined; if (!instagramAlerted) { systemMessage = "You haven't authorized FlipFlip to work with Instagram yet.\nVisit Settings to authorize Instagram."; instagramAlerted = true; } pm({ systemMessage: systemMessage, helpers: helpers, source: source, timeout: timeout, }, resolve); } } export const loadE621 = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; const url = source.url; const hostRegex = /^(https?:\/\/[^\/]*)\//g; const thisHost = hostRegex.exec(url)[1]; let suffix = ""; if (url.includes("/pools/")) { suffix = "/pools.json?search[id]=" + url.substring(url.lastIndexOf("/") + 1); wretch(thisHost + suffix) .get() .setTimeout(5000) .badRequest((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .timeout((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .internalError((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .json((json: any) => { if (json.length == 0) { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); return; } const count = json[0].post_count; const images = Array<string>(); for (let postID of json[0].post_ids) { suffix = "/posts/" + postID + ".json"; wretch(thisHost + suffix) .get() .setTimeout(5000) .badRequest((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .timeout((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .internalError((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .json((json: any) => { if (json.post && json.post.file.url) { let fileURL = json.post.file.url; if (!fileURL.startsWith("http")) { fileURL = "https://" + fileURL; } images.push(fileURL); } if (images.length == count) { helpers.next = null; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) .catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } }) .catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } else { suffix = "/posts.json?limit=20&page=" + (helpers.next + 1); const tagRegex = /[?&]tags=(.*)&?/g; let tags; if ((tags = tagRegex.exec(url)) !== null) { suffix += "&tags=" + tags[1]; } wretch(thisHost + suffix) .get() .setTimeout(5000) .badRequest((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .timeout((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .internalError((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .json((json: any) => { if (json.length == 0) { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } let list = json.posts; const images = Array<string>(); for (let p of list) { if (p.file.url) { let fileURL = p.file.url; if (!fileURL.startsWith("http")) { fileURL = "https://" + fileURL; } images.push(fileURL); } } helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); }) .catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } } export const loadDanbooru = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; const url = source.url; const hostRegex = /^(https?:\/\/[^\/]*)\//g; const thisHost = hostRegex.exec(url)[1]; let suffix = ""; if (url.includes("/pool/")) { suffix = "/pool/show.json?page=" + (helpers.next + 1) + "&id=" + url.substring(url.lastIndexOf("/") + 1); } else { suffix = "/post/index.json?limit=20&page=" + (helpers.next + 1); const tagRegex = /[?&]tags=(.*)&?/g; let tags; if ((tags = tagRegex.exec(url)) !== null) { suffix += "&tags=" + tags[1]; } const titleRegex = /[?&]title=(.*)&?/g; let title; if ((title = titleRegex.exec(url)) !== null) { if (tags == null) { suffix += "&tags="; } else if (!suffix.endsWith("+")) { suffix += "+"; } suffix += title[1]; } } wretch(thisHost + suffix) .get() .setTimeout(5000) .badRequest((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .timeout((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .internalError((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .json((json: any) => { if (json.length == 0) { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } let list; if (json.posts) { list = json.posts; } else { list = json; } const images = Array<string>(); for (let p of list) { if (p.file_url) { let fileURL = p.file_url; if (!p.file_url.startsWith("http")) { fileURL = "https://" + p.file_url; } images.push(fileURL); } } helpers.next = url.includes("/pool/") ? null : helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); }) .catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } export const loadGelbooru1 = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; const url = source.url; const hostRegex = /^(https?:\/\/[^\/]*)\//g; const thisHost = hostRegex.exec(url)[1]; wretch(url + "&pid=" + (helpers.next * 10)) .get() .setTimeout(5000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .error(503, (e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { let imageEls = domino.createWindow(html).document.querySelectorAll("span.thumb > a"); if (imageEls.length > 0) { let imageCount = 0; let images = Array<string>(); const getImage = (index: number) => { let link = imageEls.item(index).getAttribute("href"); if (!link.startsWith("http")) { link = thisHost + "/" + link; } wretch(link) .get() .setTimeout(5000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .error(503, (e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { imageCount++; let contentURL = html.match("<img[^>]*id=\"?image\"?[^>]*src=\"([^\"]*)\""); if (contentURL != null) { let url = contentURL[1]; if (url.startsWith("//")) url = "http:" + url; images.push(url); } contentURL = html.match("<img[^>]*src=\"([^\"]*)\"[^>]*id=\"?image\"?"); if (contentURL != null) { let url = contentURL[1]; if (url.startsWith("//")) url = "http:" + url; images.push(url); } contentURL = html.match("<video[^>]*src=\"([^\"]*)\""); if (contentURL != null) { let url = contentURL[1]; if (url.startsWith("//")) url = "http:" + url; images.push(url); } if (imageCount == imageEls.length || imageCount == 10) { helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, false).length; pm({ data: filterPathsToJustPlayable(filter, images, false), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); if (index < imageEls.length - 1 && index < 9) { setTimeout(getImage.bind(null, index+1), 1000); } }; setTimeout(getImage.bind(null, 0), 1000); } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } export const loadGelbooru2 = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; const url = source.url; const hostRegex = /^(https?:\/\/[^\/]*)\//g; const thisHost = hostRegex.exec(url)[1]; let suffix = "/index.php?page=dapi&s=post&q=index&limit=20&json=1&pid=" + (helpers.next + 1); const tagRegex = /[?&]tags=(.*)&?/g; let tags; if ((tags = tagRegex.exec(url)) !== null) { suffix += "&tags=" + tags[1]; } wretch(thisHost + suffix) .get() .setTimeout(5000) .badRequest((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .timeout((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .internalError((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .json((json: any) => { if (json.length == 0) { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } const images = Array<string>(); for (let p of json) { if (p.file_url) { images.push(p.file_url); } else if (p.image) { images.push(thisHost + "//images/" + p.directory + "/" + p.image); } } helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); }) .catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } export const loadEHentai = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; const url = source.url; wretch(url + "?p=" + (helpers.next + 1)) .get() .setTimeout(5000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { let imageEls = domino.createWindow(html).document.querySelectorAll("#gdt > .gdtm > div > a"); if (imageEls.length > 0) { let imageCount = 0; let images = Array<string>(); for (let i = 0; i < imageEls.length; i++) { const image = imageEls.item(i) wretch(image.getAttribute("href")) .get() .setTimeout(5000) .onAbort((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .text((html) => { imageCount++; let contentURL = html.match("<img id=\"img\" src=\"(.*?)\""); if (contentURL != null) { images.push(contentURL[1]); } if (imageCount == imageEls.length) { helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) } } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } export const loadBDSMlr = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; let url = source.url; if (url.endsWith("/rss")) { url = url.substring(0, url.indexOf("/rss")) } const retry = () => { if (helpers.retries < 3) { helpers.retries += 1; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else { pm({ helpers: helpers, source: source, timeout: timeout, }, resolve); } } wretch(url + "/rss?page=" + (helpers.next + 1)) .get() .setTimeout(5000) .onAbort(retry) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .internalError(retry) .text((html) => { helpers.retries = 0; let itemEls = domino.createWindow(html).document.querySelectorAll("item"); if (itemEls.length > 0) { let imageCount = 0; let images = Array<string>(); for (let i = 0; i < itemEls.length; i++) { const item = itemEls.item(i); const embeddedImages = item.querySelectorAll("description > img"); if (embeddedImages.length > 0) { for (let image of embeddedImages) { imageCount++; images.push(image.getAttribute("src")); } } } helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }); } let piwigoLoggedIn: boolean = false; export const loadPiwigo = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; let url = source.url; const user = config.remoteSettings.piwigoUsername; const pass = config.remoteSettings.piwigoPassword; const host = config.remoteSettings.piwigoHost; const protocol = config.remoteSettings.piwigoProtocol; const configured = host != "" && protocol != "" && user != "" && pass != ""; if (configured) { const login = () => { return wretch(protocol + "://" + host + "/ws.php?format=json") .formUrl({method: "pwg.session.login", username: user, password: pass}) .post() .setTimeout(5000) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .internalError((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .json((json) => { if (json.stat == "ok") { piwigoLoggedIn = true; search(); } else { pm({ error: "Piwigo login failed.", helpers: helpers, source: source, timeout: timeout, }, resolve); } }) .catch((e) => { pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }); } const retry = () => { if (helpers.retries < 3) { helpers.retries += 1; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } else { pm({ helpers: helpers, source: source, timeout: timeout, }, resolve); } } const search = () => { return wretch(url + "&page=" + helpers.next) .get() .setTimeout(5000) .onAbort(retry) .notFound((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)) .internalError(retry) .json((json) => { if (json.stat != "ok") { helpers.next = null; pm({ data: [], allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); return; } const images = Array<string>(); if (json?.result?.images) { for (let o = 0; o < json.result.images.length; o++) { const image = json.result.images[o]; if (image.element_url) { images.push(image.element_url); } } } if (images.length > 0) { helpers.next = helpers.next + 1; helpers.count = helpers.count + filterPathsToJustPlayable(IF.any, images, true).length; } else { helpers.next = null; } pm({ data: filterPathsToJustPlayable(filter, images, true), allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); }); }; if (!piwigoLoggedIn) { login() } else { search(); } } else { let systemMessage = undefined; if (!piwigoAlerted) { systemMessage = "You haven't configured FlipFlip to work with Piwigo yet.\nVisit Settings to configure Piwigo."; hydrusAlerted = true; } pm({ systemMessage: systemMessage, helpers: helpers, source: source, timeout: timeout, }, resolve); } } export const loadHydrus = (allURLs: Map<string, Array<string>>, config: Config, source: LibrarySource, filter: string, weight: string, helpers: {next: any, count: number, retries: number, uuid: string}, resolve?: Function) => { const timeout = 8000; const apiKey = config.remoteSettings.hydrusAPIKey; const configured = apiKey != ""; if (configured) { const protocol = config.remoteSettings.hydrusProtocol; const domain = config.remoteSettings.hydrusDomain; const port = config.remoteSettings.hydrusPort; const hydrusURL = protocol + "://" + domain + ":" + port; if (!source.url.startsWith(hydrusURL)) { let systemMessage = undefined; if (!hydrusAlerted) { systemMessage = "Source url '" + source.url + "' does not match configured Hydrus server '" + hydrusURL; hydrusAlerted = true; } pm({ systemMessage: systemMessage, helpers: helpers, source: source, timeout: timeout, }, resolve); } const tagsRegex = /tags=([^&]*)&?.*$/.exec(source.url); let noTags = tagsRegex == null || tagsRegex.length <= 1; let pages = 0; const search = () => { const url = noTags ? hydrusURL + "/get_files/search_files" : hydrusURL + "/get_files/search_files?tags=" + tagsRegex[1]; wretch(url) .headers({"Hydrus-Client-API-Access-Key": apiKey}) .get() .setTimeout(15000) .notFound((e) => { pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }) .internalError((e) => { pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }) .json((json) => { const fileIDs = json.file_ids; const chunk = 1000; pages = Math.ceil(fileIDs.length / chunk); let page = 0; for (let i=0; i<fileIDs.length; i+=chunk) { const pageIDs = fileIDs.slice(i,i+chunk); // Stagger our getFileMetadata calls setTimeout(() => getFileMetadata(pageIDs, ++page), page*1000); } }) .catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } let images = Array<string>(); const getFileMetadata = (fileIDs: Array<number>, page: number) => { wretch(hydrusURL + "/get_files/file_metadata?file_ids=[" + fileIDs.toString() + "]") .headers({"Hydrus-Client-API-Access-Key": apiKey}) .get() .setTimeout(15000) .notFound((e) => { pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }) .internalError((e) => { pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve); }) .json((json) => { for (let metadata of json.metadata) { if ((filter == IF.any && isImageOrVideo(metadata.ext, true)) || (filter == IF.stills || filter == IF.images) && isImage(metadata.ext, true) || (filter == IF.animated && metadata.ext.toLowerCase().endsWith('.gif') || isVideo(metadata.ext, true)) || (filter == IF.videos && isVideo(metadata.ext, true))) { images.push(hydrusURL + "/get_files/file?file_id=" + metadata.file_id + "&Hydrus-Client-API-Access-Key=" + apiKey + "&ext=" + metadata.ext); } } if (page == pages) { pm({ data: images, allURLs: allURLs, weight: weight, helpers: helpers, source: source, timeout: timeout, }, resolve); } }) .catch((e) => pm({ error: e.message, helpers: helpers, source: source, timeout: timeout, }, resolve)); } search(); } else { let systemMessage = undefined; if (!hydrusAlerted) { systemMessage = "You haven't configured FlipFlip to work with Hydrus yet.\nVisit Settings to configure Hydrus."; hydrusAlerted = true; } pm({ systemMessage: systemMessage, helpers: helpers, source: source, timeout: timeout, }, resolve); } } export function filterPathsToJustPlayable(imageTypeFilter: string, paths: Array<string>, strict: boolean): Array<string> { switch (imageTypeFilter) { default: case IF.any: return paths.filter((p) => isImageOrVideo(p, strict)); case IF.stills: case IF.images: return paths.filter((p) => isImage(p, strict)); case IF.animated: return paths.filter((p) => p.toLowerCase().endsWith('.gif') || isVideo(p, strict)); case IF.videos: return paths.filter((p) => isVideo(p, strict)); } } export const isImageOrVideo = (path: string, strict: boolean): boolean => { return (isImage(path, strict) || isVideo(path, strict)); } export function isImage(path: string, strict: boolean): boolean { if (path == null) return false; const p = path.toLowerCase(); const acceptableExtensions = [".gif", ".png", ".jpeg", ".jpg", ".webp", ".tiff", ".svg"]; for (let ext of acceptableExtensions) { if (strict) { if (p.endsWith(ext)) return true; } else { if (p.includes(ext)) return true; } } return false; } export function isVideo(path: string, strict: boolean): boolean { if (path == null) return false; const p = path.toLowerCase(); const acceptableExtensions = [".mp4", ".mkv", ".webm", ".ogv", ".mov"]; for (let ext of acceptableExtensions) { if (strict) { if (p.endsWith(ext)) return true; } else { if (p.includes(ext)) return true; } } return false; } export function isVideoPlaylist(path: string, strict: boolean): boolean { if (path == null) return false; const p = path.toLowerCase(); const acceptableExtensions = [".asx", ".m3u8", ".pls", ".xspf"]; for (let ext of acceptableExtensions) { if (strict) { if (p.endsWith(ext)) return true; } else { if (p.includes(ext)) return true; } } return false; } export function isAudio(path: string, strict: boolean): boolean { if (path == null) return false; const p = path.toLowerCase(); const acceptableExtensions = [".mp3", ".m4a", ".wav", ".ogg"]; for (let ext of acceptableExtensions) { if (strict) { if (p.endsWith(ext)) return true; } else { if (p.includes(ext)) return true; } } return false; } export function getFileName(url: string, extension = true) { let sep; if (/^(https?:\/\/)|(file:\/\/)/g.exec(url) != null) { sep = "/" } else { sep = path.sep; } url = url.substring(url.lastIndexOf(sep) + 1); if (url.includes("?")) { url = url.substring(0, url.indexOf("?")); } if (!extension) { url = url.substring(0, url.lastIndexOf(".")); } return url; } async function convertURL(url: string): Promise<Array<string>> { // If this is a imgur image page, return image file let imgurMatch = url.match("^https?://(?:m\.)?imgur\.com/([\\w\\d]{7})$"); if (imgurMatch != null) { return ["https://i.imgur.com/" + imgurMatch[1] + ".jpg"]; } // If this is imgur album, return album images let imgurAlbumMatch = url.match("^https?://imgur\.com/a/([\\w\\d]{7})$"); if (imgurAlbumMatch != null) { let json = await imgur.getAlbumInfo(getFileGroup(url)); if (json) { return json.data.images.map((i: any) => i.link); } } // If this is gfycat page, return gfycat image let gfycatMatch = url.match("^https?://gfycat\.com/(?:ifr/)?(\\w*)$"); if (gfycatMatch != null) { // Only lookup CamelCase url if not already CamelCase if (/[A-Z]/.test(gfycatMatch[1])) { return ["https://giant.gfycat.com/" + gfycatMatch[1] + ".mp4"]; } let html = await wretch(url).get().notFound(() => {return [url]}).text(); let gfycat = domino.createWindow(html).document.querySelectorAll("#video-" + gfycatMatch[1].toLocaleLowerCase() + " > source"); if (gfycat.length > 0) { for (let source of gfycat) { if ((source as any).type == "video/webm") { return [(source as any).src]; } } // Fallback to MP4 for (let source of gfycat) { if ((source as any).type == "video/mp4" && !(source as any).src.endsWith("-mobile.mp4")) { return [(source as any).src]; } } // Fallback to MP4-mobile for (let source of gfycat) { if ((source as any).type == "video/mp4") { return [(source as any).src]; } } } } // If this is redgif page, return redgif image let redgifMatch = url.match("^https?://(?:www\.)?redgifs\.com/watch/(\\w*)$"); if (redgifMatch != null) { let fourOFour = false let html = await wretch(url).get().notFound(() => {fourOFour = true}).text(); if (fourOFour) { return [url]; } else if (html) { let redgif = /<meta property="og:video" content="([^"]*)">/g.exec(html); if (redgif != null) { return [redgif[1]]; } } } if (url.includes("redgifs") || url.includes("gfycat")) { pm({warning: "Possible missed file: " + url}); } return [url]; } export function getSourceType(url: string): string { if (isAudio(url, false)) { return ST.audio; } else if (isVideo(url, false)) { return ST.video; } else if (isVideoPlaylist(url, true)) { return ST.playlist; } else if (/^https?:\/\/([^.]*|(66\.media))\.tumblr\.com/.exec(url) != null) { return ST.tumblr; } else if (/^https?:\/\/(www\.)?reddit\.com\//.exec(url) != null) { return ST.reddit; } else if (/^https?:\/\/(www\.)?imagefap\.com\//.exec(url) != null) { return ST.imagefap; } else if (/^https?:\/\/(www\.)?imgur\.com\//.exec(url) != null) { return ST.imgur; } else if (/^https?:\/\/(www\.)?(cdn\.)?sex\.com\//.exec(url) != null) { return ST.sexcom; } else if (/^https?:\/\/(www\.)?twitter\.com\//.exec(url) != null) { return ST.twitter; } else if (/^https?:\/\/(www\.)?deviantart\.com\//.exec(url) != null) { return ST.deviantart; } else if (/^https?:\/\/(www\.)?instagram\.com\//.exec(url) != null) { return ST.instagram; } else if (/^https?:\/\/(www\.)?(lolibooru\.moe|hypnohub\.net|danbooru\.donmai\.us)\//.exec(url) != null) { return ST.danbooru; } else if (/^https?:\/\/(www\.)?(gelbooru\.com|furry\.booru\.org|rule34\.xxx|realbooru\.com)\//.exec(url) != null) { return ST.gelbooru2; } else if (/^https?:\/\/(www\.)?(e621\.net)\//.exec(url) != null) { return ST.e621; } else if (/^https?:\/\/(www\.)?(.*\.booru\.org|idol\.sankakucomplex\.com)\//.exec(url) != null) { return ST.gelbooru1; } else if (/^https?:\/\/(www\.)?e-hentai\.org\/g\//.exec(url) != null) { return ST.ehentai; } else if (/^https?:\/\/[^.]*\.bdsmlr\.com/.exec(url) != null) { return ST.bdsmlr; } else if (/^https?:\/\/[\w\\.]+:\d+\/get_files\/search_files/.exec(url) != null) { return ST.hydrus; } else if (/^https?:\/\/[^.]*\.[a-z0-9\.:]+\/ws.php/.exec(url) != null) { return ST.piwigo; } else if (/^https?:\/\/hypno\.nimja\.com\/visual\/\d+/.exec(url) != null) { return ST.nimja; } else if (/(^https?:\/\/)|(\.txt$)/.exec(url) != null) { // Arbitrary URL, assume image list return ST.list; } else { // Directory return ST.local; } } export function getFileGroup(url: string) { let sep; switch (getSourceType(url)) { case ST.tumblr: let tumblrID = url.replace(/https?:\/\//, ""); tumblrID = tumblrID.replace(/\.tumblr\.com\/?/, ""); return tumblrID; case ST.reddit: let redditID = url; if (redditID.endsWith("/")) redditID = redditID.slice(0, url.lastIndexOf("/")); if (redditID.endsWith("/saved")) redditID = redditID.replace("/saved", ""); redditID = redditID.substring(redditID.lastIndexOf("/") + 1); return redditID; case ST.imagefap: let imagefapID = url.replace(/https?:\/\/www.imagefap.com\//, ""); imagefapID = imagefapID.replace(/pictures\//, ""); imagefapID = imagefapID.replace(/organizer\//, ""); imagefapID = imagefapID.replace(/video\.php\?vid=/, ""); imagefapID = imagefapID.split("/")[0]; return imagefapID; case ST.sexcom: let sexcomID = url.replace(/https?:\/\/www.sex.com\//, ""); sexcomID = sexcomID.replace(/user\//, ""); sexcomID = sexcomID.split("?")[0]; if (sexcomID.endsWith("/")) { sexcomID = sexcomID.substring(0, sexcomID.length - 1); } return sexcomID; case ST.imgur: let imgurID = url.replace(/https?:\/\/imgur.com\//, ""); imgurID = imgurID.replace(/a\//, ""); return imgurID; case ST.twitter: let twitterID = url.replace(/https?:\/\/twitter.com\//, ""); if (twitterID.includes("?")) { twitterID = twitterID.substring(0, twitterID.indexOf("?")); } return twitterID; case ST.deviantart: let authorID = url.replace(/https?:\/\/www.deviantart.com\//, ""); if (authorID.includes("/")) { authorID = authorID.substring(0, authorID.indexOf("/")); } return authorID; case ST.instagram: let instagramID = url.replace(/https?:\/\/www.instagram.com\//, ""); if (instagramID.includes("/")) { instagramID = instagramID.substring(0, instagramID.indexOf("/")); } return instagramID; case ST.e621: const hostRegexE621 = /^https?:\/\/(?:www\.)?([^.]*)\./g; const hostE621 = hostRegexE621.exec(url)[1]; let E621ID = ""; if (url.includes("/pools/")) { E621ID = "pool" + url.substring(url.lastIndexOf("/")); } else { const tagRegex = /[?&]tags=(.*)&?/g; let tags; if ((tags = tagRegex.exec(url)) !== null) { E621ID = tags[1]; } if (E621ID.endsWith("+")) { E621ID = E621ID.substring(0, E621ID.length - 1); } } return hostE621 + "/" + decodeURIComponent(E621ID); case ST.danbooru: case ST.gelbooru1: case ST.gelbooru2: const hostRegex = /^https?:\/\/(?:www\.)?([^.]*)\./g; const host = hostRegex.exec(url)[1]; let danbooruID = ""; if (url.includes("/pool/")) { danbooruID = "pool" + url.substring(url.lastIndexOf("/")); } else { const tagRegex = /[?&]tags=(.*)&?/g; let tags; if ((tags = tagRegex.exec(url)) !== null) { danbooruID = tags[1]; } const titleRegex = /[?&]title=(.*)&?/g; let title; if ((title = titleRegex.exec(url)) !== null) { if (tags == null) { danbooruID = "" } else if (!danbooruID.endsWith("+")) { danbooruID += "+"; } danbooruID += title[1]; } if (danbooruID.endsWith("+")) { danbooruID = danbooruID.substring(0, danbooruID.length - 1); } } return host + "/" + decodeURIComponent(danbooruID); case ST.ehentai: const galleryRegex = /^https?:\/\/(?:www\.)?e-hentai\.org\/g\/([^\/]*)/g; const gallery = galleryRegex.exec(url); return gallery[1]; case ST.list: if (/^https?:\/\//g.exec(url) != null) { sep = "/" } else { sep = path.sep; } return url.substring(url.lastIndexOf(sep) + 1).replace(".txt", ""); case ST.local: if (url.endsWith(path.sep)) { url = url.substring(0, url.length - 1); return url.substring(url.lastIndexOf(path.sep)+1); } else { return url.substring(url.lastIndexOf(path.sep)+1); } case ST.video: case ST.playlist: case ST.nimja: if (/^https?:\/\//g.exec(url) != null) { sep = "/" } else { sep = path.sep; } let name = url.substring(0, url.lastIndexOf(sep)); return name.substring(name.lastIndexOf(sep)+1); case ST.bdsmlr: let bdsmlrID = url.replace(/https?:\/\//, ""); bdsmlrID = bdsmlrID.replace(/\/rss/, ""); bdsmlrID = bdsmlrID.replace(/\.bdsmlr\.com\/?/, ""); return bdsmlrID; case ST.hydrus: const tagsRegex = /tags=([^&]*)&?.*$/.exec(url); if (tagsRegex == null) return "hydrus"; let tags = tagsRegex[1]; if (!tags.startsWith("[")) { tags = decodeURIComponent(tags); } tags = tags.substring(1, tags.length - 1); tags = tags.replace(/"/g, ""); return tags; case ST.piwigo: const catRegex = /cat_id\[]=(\d*)/.exec(url); if (catRegex != null) return catRegex[1]; const tagRegex = /tag_id\[]=(\d*)/.exec(url); if (tagRegex != null) return tagRegex[1]; return "piwigo"; } }
the_stack
import TestCase from '../testcase'; import { RegisterTypes } from '../../src/assets/ts/register'; describe('yank', function() { describe('characters', function() { it('works in basic case', async function() { let t = new TestCase(['px']); t.sendKeys('xp'); t.expect(['xp']); t.expectRegisterType(RegisterTypes.CHARS); t.sendKeys('xp'); t.expect(['xp']); await t.done(); }); it('works with deleting words', async function() { let t = new TestCase(['one fish, two fish, red fish, blue fish']); t.sendKeys('dWWhp'); t.expect(['fish, one two fish, red fish, blue fish']); // undo doesn't move cursor, and paste still has stuff in register t.sendKeys('up'); t.expect(['fish, one two fish, red fish, blue fish']); await t.done(); t = new TestCase(['one fish, two fish, red fish, blue fish']); t.sendKeys('2dW2Whp'); t.expect(['two fish, one fish, red fish, blue fish']); // undo doesn't move cursor, and paste still has stuff in register t.sendKeys('up'); t.expect(['two fish, one fish, red fish, blue fish']); await t.done(); t = new TestCase(['one fish, two fish, red fish, blue fish']); t.sendKeys('d2W2Whp'); t.expect(['two fish, one fish, red fish, blue fish']); // undo doesn't move cursor, and paste still has stuff in register t.sendKeys('u'); // type hasnt changed t.expectRegisterType(RegisterTypes.CHARS); t.sendKeys('p'); t.expect(['two fish, one fish, red fish, blue fish']); await t.done(); }); it('works behind', async function() { let t = new TestCase(['one fish, two fish, red fish, blue fish']); t.sendKeys('$F,d$3bP'); t.expect(['one fish, two fish, blue fish, red fish']); // undo doesn't move cursor, and paste still has stuff in register t.sendKeys('uP'); t.expect(['one fish, two fish, blue fish, red fish']); await t.done(); }); it('works behind in an edge case with empty line, and repeat', async function() { let t = new TestCase(['word']); t.sendKeys('de'); t.expect(['']); t.sendKeys('P'); t.expect(['word']); t.sendKeys('u'); t.expect(['']); // repeat still knows what to do t.sendKeys('.'); t.expect(['word']); t.sendKeys('.'); t.expect(['worwordd']); await t.done(); }); it('works with motions', async function() { let t = new TestCase(['lol']); t.sendKeys('yllp'); t.expect(['loll']); await t.done(); t = new TestCase(['lol']); t.sendKeys('y$P'); t.expect(['lollol']); await t.done(); t = new TestCase(['lol']); t.sendKeys('$ybp'); t.expect(['lollo']); t.sendKeys('u'); t.expect(['lol']); t.sendKeys('P'); t.expect(['lolol']); await t.done(); t = new TestCase(['haha ... ha ... funny']); t.sendKeys('y3wP'); t.expect(['haha ... ha haha ... ha ... funny']); await t.done(); t = new TestCase(['haha ... ha ... funny']); t.sendKeys('yep'); t.expect(['hhahaaha ... ha ... funny']); // cursor ends at last character t.sendKeys('yffp'); t.expect(['hhahaaaha ... ha ... faha ... ha ... funny']); await t.done(); }); }); describe('rows', function() { it('works in a basic case', async function() { let t = new TestCase(['humpty', 'dumpty']); t.sendKeys('dd'); t.expectRegisterType(RegisterTypes.CLONED_ROWS); t.expect([ 'dumpty' ]); t.sendKeys('p'); t.expectRegisterType(RegisterTypes.CLONED_ROWS); t.expect([ 'dumpty', 'humpty' ]); t.sendKeys('u'); t.expect(['dumpty']); t.sendKeys('u'); t.expect(['humpty', 'dumpty']); // violates cloning constraints t.sendKeys('p'); t.expect(['humpty', 'dumpty']); await t.done(); }); it('works behind', async function() { let t = new TestCase(['humpty', 'dumpty']); t.sendKeys('jddP'); t.expect([ 'dumpty', 'humpty' ]); t.sendKeys('u'); t.expect(['humpty']); t.sendKeys('u'); t.expect(['humpty', 'dumpty']); await t.done(); }); it('pastes siblings, not children', async function() { let t = new TestCase([ { text: 'herpy', children: [ { text: 'derpy', children: [ 'burpy', ] }, ] }, ]); t.sendKeys('jjddp'); t.expect([ { text: 'herpy', children: [ 'derpy', 'burpy', ] }, ]); t.sendKeys('u'); t.expect([ { text: 'herpy', children: [ 'derpy', ] }, ]); t.sendKeys('kp'); t.expect([ { text: 'herpy', children: [ 'burpy', 'derpy', ] }, ]); t.sendKeys('u'); t.expect([ { text: 'herpy', children: [ 'derpy', ] }, ]); t.sendKeys('P'); t.expect([ 'burpy', { text: 'herpy', children: [ 'derpy', ] }, ]); t.sendKeys('u'); t.expect([ { text: 'herpy', children: [ 'derpy', ] }, ]); t.sendKeys('jP'); t.expect([ { text: 'herpy', children: [ 'burpy', 'derpy', ] }, ]); await t.done(); }); it('pastes register of recent action after undo', async function() { let t = new TestCase(['hey', 'yo', 'yo', 'yo', 'yo', 'yo']); t.sendKeys('yyjp'); t.expect(['hey', 'yo', 'hey', 'yo', 'yo', 'yo', 'yo']); t.sendKeys('jjP'); t.expect(['hey', 'yo', 'hey', 'yo', 'hey', 'yo', 'yo', 'yo']); // this should only affect one of the pasted lines (verify it's a copy!) t.sendKeys('x'); t.expect(['hey', 'yo', 'hey', 'yo', 'ey', 'yo', 'yo', 'yo']); t.sendKeys('uu'); t.expect(['hey', 'yo', 'hey', 'yo', 'yo', 'yo', 'yo']); t.sendKeys('u'); t.expect(['hey', 'yo', 'yo', 'yo', 'yo', 'yo']); t.sendKey('ctrl+r'); t.expect(['hey', 'yo', 'hey', 'yo', 'yo', 'yo', 'yo']); // the register still contains the 'h' from the 'x' t.sendKeys('jjjjjp'); t.expect(['hey', 'yo', 'hey', 'yo', 'yo', 'yo', 'yho']); await t.done(); // similar to above case t = new TestCase(['hey', 'yo', 'yo', 'yo', 'yo', 'yo']); t.sendKeys('yyjp'); t.expect(['hey', 'yo', 'hey', 'yo', 'yo', 'yo', 'yo']); t.sendKeys('jjP'); t.expect(['hey', 'yo', 'hey', 'yo', 'hey', 'yo', 'yo', 'yo']); t.sendKeys('ry'); t.expect(['hey', 'yo', 'hey', 'yo', 'yey', 'yo', 'yo', 'yo']); t.sendKeys('uu'); t.expect(['hey', 'yo', 'hey', 'yo', 'yo', 'yo', 'yo']); t.sendKeys('u'); t.expect(['hey', 'yo', 'yo', 'yo', 'yo', 'yo']); // splice does NOT replace register! t.sendKeys('jjjjjp'); t.expect(['hey', 'yo', 'yo', 'yo', 'yo', 'yo', 'hey']); await t.done(); }); it('works in basic case', async function() { let t = new TestCase([ { text: 'hey', children: [ 'yo', ] }, ]); t.sendKeys('yyp'); t.expect([ { text: 'hey', children: [ 'hey', 'yo', ] }, ]); await t.done(); }); it('works recursively', async function() { let t = new TestCase([ { text: 'hey', children: [ 'yo', ] }, ]); t.sendKeys('yrp'); t.expect([ { text: 'hey', children: [ { text: 'hey', children: [ 'yo', ] }, 'yo', ] }, ]); t.sendKeys('p'); t.expect([ { text: 'hey', children: [ { text: 'hey', children: [ { text: 'hey', children: [ 'yo', ] }, 'yo', ] }, 'yo', ] }, ]); t.sendKeys('u'); t.expect([ { text: 'hey', children: [ { text: 'hey', children: [ 'yo', ] }, 'yo', ] }, ]); t.sendKey('ctrl+r'); t.expect([ { text: 'hey', children: [ { text: 'hey', children: [ { text: 'hey', children: [ 'yo', ] }, 'yo', ] }, 'yo', ] }, ]); await t.done(); }); it("preserves collapsedness, and doesn't paste as child of collapsed", async function() { let t = new TestCase([ { text: 'hey', collapsed: true, children: [ 'yo', ] }, ]); t.sendKeys('yrp'); t.expect([ { text: 'hey', collapsed: true, children: [ 'yo', ] }, { text: 'hey', collapsed: true, children: [ 'yo', ] }, ]); await t.done(); }); it('preserves collapsedness', async function() { let t = new TestCase([ { text: 'hey', collapsed: true, children: [ 'yo', ] }, ]); t.sendKeys('yrzp'); t.expect([ { text: 'hey', children: [ { text: 'hey', collapsed: true, children: [ 'yo', ] }, 'yo', ] }, ]); await t.done(); }); it('pastes clones', async function() { let t = new TestCase([ { text: 'hey', collapsed: true, children: [ 'yo', ] }, 'yo', { text: 'what', children: [ 'up', ] }, ]); t.sendKeys('Vjd'); t.expect([ { text: 'what', children: [ 'up', ] }, ]); t.expectRegisterType(RegisterTypes.CLONED_ROWS); t.sendKeys('P'); t.expect([ { text: 'hey', collapsed: true, children: [ 'yo', ] }, 'yo', { text: 'what', children: [ 'up', ] }, ]); t.sendKeys('zryjrh'); t.expect([ { text: 'yey', children: [ 'ho', ] }, 'yo', { text: 'what', children: [ 'up', ] }, ]); // second paste should be changed thing t.sendKeys('GP'); t.expect([ { text: 'yey', id: 1, children: [ 'ho', ] }, { text: 'yo', id: 3 }, { text: 'what', children: [ { clone: 1 }, { clone: 3 }, 'up', ] }, ]); await t.done(); }); it('pastes clones at collapsed view root', async function() { let t = new TestCase([ 'blah', { text: 'herpy', children: [ { text: 'derpy', collapsed: true, children: [ 'burpy', ] }, ] }, ]); t.sendKeys('ycjj'); t.sendKey('enter'); t.sendKeys('p'); t.expect([ { id: 1, text: 'blah' }, { text: 'herpy', children: [ { text: 'derpy', collapsed: true, children: [ { clone: 1 }, 'burpy', ] }, ] }, ]); await t.done(); }); it('yanks serialized (not cloned)', async function() { let t = new TestCase([ { text: 'hey', collapsed: true, children: [ 'yo', ] }, 'yo', { text: 'what', children: [ 'up', ] }, ]); t.sendKeys('Vjy'); t.expectRegisterType(RegisterTypes.SERIALIZED_ROWS); t.sendKeys('gg'); t.sendKeys('zryjrh'); t.expect([ { text: 'yey', children: [ 'ho', ] }, 'yo', { text: 'what', children: [ 'up', ] }, ]); // second paste should be changed thing t.sendKeys('GP'); t.expect([ { text: 'yey', children: [ 'ho', ] }, 'yo', { text: 'what', children: [ { text: 'hey', collapsed: true, children: [ 'yo', ] }, 'yo', 'up', ] }, ]); await t.done(); }); it('works to end of line', async function() { let t = new TestCase(['humpty dumpty']); t.sendKeys('fpY0P'); t.expect([ 'pty dumptyhumpty dumpty' ]); await t.done(); }); it('works at collapsed view root', async function() { let t = new TestCase([ { text: 'herpy', children: [ { text: 'derpy', collapsed: true, children: [ 'burpy', ] }, ] }, ]); t.sendKey('j'); t.sendKey('enter'); t.sendKeys('yyp'); t.expect([ { text: 'herpy', children: [ { text: 'derpy', collapsed: true, children: [ 'derpy', 'burpy', ] }, ] }, ]); await t.done(); }); it('works at view root with no children', async function() { let t = new TestCase([ { text: 'herpy', children: [ 'derpy' ] }, ]); t.sendKey('j'); t.sendKey('enter'); t.sendKeys('yyp'); t.expect([ { text: 'herpy', children: [ { text: 'derpy', children: [ 'derpy', ] }, ] }, ]); await t.done(); }); it('works at collapsed view root with no children', async function() { let t = new TestCase([ { text: 'herpy', children: [ { text: 'derpy', collapsed: true }, ] }, ]); t.sendKey('j'); t.sendKey('enter'); t.sendKeys('yyp'); t.expect([ { text: 'herpy', children: [ { text: 'derpy', collapsed: true, children: [ 'derpy', ] }, ] }, ]); await t.done(); }); }); });
the_stack
import WarpAffine from './warpAffine'; class DetectProcess { private modelResult: any; private output_size: number; private anchor_num: number; private detectResult: any; private hasHand: number; private originCanvas: HTMLCanvasElement; private originImageData: ImageData; private maxIndex: number; private box: any; private feed: any; private anchors: any; private mtr: any; private source: any[][]; private imageData: ImageData; private pxmin: any; private pxmax: any; private pymin: any; private pymax: any; private kp: number[][]; private tw: number; private th: number; private triangle: any; private results: any; constructor(result, canvas) { this.modelResult = result; this.output_size = 10; this.anchor_num = 1920; this.detectResult = new Array(14).fill('').map(() => []); this.hasHand = 0; this.originCanvas = canvas; const ctx = this.originCanvas.getContext('2d'); this.originImageData = ctx.getImageData(0, 0, 256, 256); } async outputBox(results) { this.getMaxIndex(); if (this.maxIndex === -1) { this.hasHand = 0; return false; } this.hasHand = 1; await this.splitAnchors(results); this.decodeAnchor(); // 求关键点 this.decodeKp(); // 求手势框 this.decodeBox(); return this.box; } async outputFeed(paddle) { this.decodeTriangle(); this.decodeSource(); this.outputResult(); // 提取仿射变化矩阵 this.getaffinetransform(); // 对图片进行仿射变换 await this.warpAffine(); this.allReshapeToRGB(paddle); return this.feed; } async splitAnchors(results) { this.results = results; const anchors = new Array(this.anchor_num).fill('').map(() => []); const anchor_num = this.anchor_num; for (let i = 0; i < anchor_num; i++) { anchors[i] = []; const tmp0 = results[i * 4]; const tmp1 = results[i * 4 + 1]; const tmp2 = results[i * 4 + 2]; const tmp3 = results[i * 4 + 3]; anchors[i][0] = tmp0 - tmp2 / 2.0; anchors[i][1] = tmp1 - tmp3 / 2.0; anchors[i][2] = tmp0 + tmp2 / 2.0; anchors[i][3] = tmp1 + tmp3 / 2.0; if (anchors[i][0] < 0) { anchors[i][0] = 0; } if (anchors[i][0] > 1) { anchors[i][0] = 1; } if (anchors[i][1] < 0) { anchors[i][1] = 0; } if (anchors[i][1] > 1) { anchors[i][1] = 1; } if (anchors[i][2] < 0) { anchors[i][2] = 0; } if (anchors[i][2] > 1) { anchors[i][2] = 1; } if (anchors[i][3] < 0) { anchors[i][3] = 0; } if (anchors[i][3] > 1) { anchors[i][3] = 1; } } this.anchors = anchors; } getMaxIndex() { let maxIndex = -1; let maxConf = -1; let curConf = -2.0; const output_size = 10; for (let i = 0; i < this.anchor_num; i++) { curConf = sigm(this.modelResult[i * output_size + 1]); if (curConf > 0.55 && curConf > maxConf) { maxConf = curConf; maxIndex = i; } } this.maxIndex = maxIndex; function sigm(value) { return 1.0 / (1.0 + Math.exp(0.0 - value)); } } decodeAnchor() { const index = this.maxIndex; const anchors = this.anchors; this.pxmin = anchors[index][0]; this.pymin = anchors[index][1]; this.pxmax = anchors[index][2]; this.pymax = anchors[index][3]; } decodeKp() { const modelResult = this.modelResult; const index = this.maxIndex; const px = (this.pxmin + this.pxmax) / 2; const py = (this.pymin + this.pymax) / 2; const pw = this.pxmax - this.pxmin; const ph = this.pymax - this.pymin; const prior_var = 0.1; const kp = [[], [], []]; kp[0][0] = (modelResult[index * this.output_size + 6] * pw * prior_var + px) * 256; kp[0][1] = (modelResult[index * this.output_size + 8] * ph * prior_var + py) * 256; kp[2][0] = (modelResult[index * this.output_size + 7] * pw * prior_var + px) * 256; kp[2][1] = (modelResult[index * this.output_size + 9] * ph * prior_var + py) * 256; this.kp = kp; } decodeBox() { const modelResult = this.modelResult; const output_size = this.output_size || 10; const pw = this.pxmax - this.pxmin; const ph = this.pymax - this.pymin; const px = this.pxmin + pw / 2; const py = this.pymin + ph / 2; const prior_var = 0.1; const index = this.maxIndex; const ox = modelResult[output_size * index + 2]; const oy = modelResult[output_size * index + 3]; const ow = modelResult[output_size * index + 4]; const oh = modelResult[output_size * index + 5]; const tx = ox * prior_var * pw + px; const ty = oy * prior_var * ph + py; const tw = this.tw = Math.pow(2.71828182, prior_var * ow) * pw; const th = this.th = Math.pow(2.71828182, prior_var * oh) * ph; const box = [[], [], [], []]; box[0][0] = (tx - tw / 2) * 256; box[0][1] = (ty - th / 2) * 256; box[1][0] = (tx + tw / 2) * 256; box[1][1] = (ty - th / 2) * 256; box[2][0] = (tx + tw / 2) * 256; box[2][1] = (ty + th / 2) * 256; box[3][0] = (tx - tw / 2) * 256; box[3][1] = (ty + th / 2) * 256; this.box = box; } decodeTriangle() { const box_enlarge = 1.04; const side = Math.max(this.tw * 256, this.th * 256) * (box_enlarge); const dir_v = []; const kp = this.kp; const triangle = [[], [], []]; const dir_v_r = []; dir_v[0] = kp[2][0] - kp[0][0]; dir_v[1] = kp[2][1] - kp[0][1]; const sq = Math.sqrt(Math.pow(dir_v[0], 2) + Math.pow(dir_v[1], 2)) || 1; dir_v[0] = dir_v[0] / sq; dir_v[1] = dir_v[1] / sq; dir_v_r[0] = dir_v[0] * 0 + dir_v[1] * 1; dir_v_r[1] = dir_v[0] * -1 + dir_v[1] * 0; triangle[0][0] = kp[2][0]; triangle[0][1] = kp[2][1]; triangle[1][0] = kp[2][0] + dir_v[0] * side; triangle[1][1] = kp[2][1] + dir_v[1] * side; triangle[2][0] = kp[2][0] + dir_v_r[0] * side; triangle[2][1] = kp[2][1] + dir_v_r[1] * side; this.triangle = triangle; } decodeSource() { const kp = this.kp; const box_shift = 0.0; const tmp0 = (kp[0][0] - kp[2][0]) * box_shift; const tmp1 = (kp[0][1] - kp[2][1]) * box_shift; const source = [[], [], []]; for (let i = 0; i < 3; i++) { source[i][0] = this.triangle[i][0] - tmp0; source[i][1] = this.triangle[i][1] - tmp1; } this.source = source; } outputResult() { for (let i = 0; i < 4; i++) { this.detectResult[i][0] = this.box[i][0]; this.detectResult[i][1] = this.box[i][1]; } this.detectResult[4][0] = this.kp[0][0]; this.detectResult[4][1] = this.kp[0][1]; this.detectResult[6][0] = this.kp[2][0]; this.detectResult[6][1] = this.kp[2][1]; for (let i = 0; i < 3; i++) { this.detectResult[i + 11][0] = this.source[i][0]; this.detectResult[i + 11][1] = this.source[i][1]; } } getaffinetransform() { // 图像上的原始坐标点。需要对所有坐标进行归一化,_x = (x - 128) / 128, _y = (128 - y) / 128 // 坐标矩阵 // x1 x2 x3 // y1 y2 y3 // z1 z2 z3 const originPoints = [].concat(this.detectResult[11][0] / 128 - 1) .concat(this.detectResult[12][0] / 128 - 1) .concat(this.detectResult[13][0] / 128 - 1) .concat(1 - this.detectResult[11][1] / 128) .concat(1 - this.detectResult[12][1] / 128) .concat(1 - this.detectResult[13][1] / 128) .concat([1, 1, 1]); // originPoints = [0, 0, -1, .1, 1.1, 0.1, 1, 1, 1]; const matrixA = new Matrix(3, 3, originPoints); // 转化后的点[128, 128, 0, 128, 0, 128] [0, 0, -1, 0, 1, 0] const matrixB = new Matrix(2, 3, [0, 0, -1, 0, -1, 0]); // M * A = B => M = B * A逆 let _matrixA: any = inverseMatrix(matrixA.data); _matrixA = new Matrix(3, 3, _matrixA); const M = Matrix_Product(matrixB, _matrixA); this.mtr = M; } async warpAffine() { const ctx = this.originCanvas.getContext('2d'); this.originImageData = ctx.getImageData(0, 0, 256, 256); const imageDataArr = await WarpAffine.main({ imageData: this.originImageData, mtr: this.mtr.data, input: { width: 256, height: 256 }, output: { width: 224, height: 224 } }); this.imageData = new ImageData(Uint8ClampedArray.from(imageDataArr), 224, 224); } allReshapeToRGB(paddle) { const data = paddle.mediaProcessor.allReshapeToRGB(this.imageData, { gapFillWith: '#000', mean: [0, 0, 0], scale: 224, std: [1, 1, 1], targetShape: [1, 3, 224, 224], normalizeType: 1 }); this.feed = [{ data: new Float32Array(data), shape: [1, 3, 224, 224], name: 'image', canvas: this.originImageData }]; } } class Matrix { private row: any; private col: any; data: any[]; constructor(row, col, arr = []) { // 行 this.row = row; // 列 this.col = col; if (arr[0] && arr[0] instanceof Array) { this.data = arr; } else { this.data = []; const _arr = [].concat(arr); // 创建row个元素的空数组 const Matrix = new Array(row); // 对第一层数组遍历 for (let i = 0; i < row; i++) { // 每一行创建col列的空数组 Matrix[i] = new Array(col).fill(''); Matrix[i].forEach((_item, index, cur) => { cur[index] = _arr.shift() || 0; }); } // 将矩阵保存到this.data上 this.data = Matrix; } } } const Matrix_Product = (A, B) => { const tempMatrix = new Matrix(A.row, B.col); if (A.col === B.row) { for (let i = 0; i < A.row; i++) { for (let j = 0; j < B.col; j++) { tempMatrix.data[i][j] = 0; for (let n = 0; n < A.col; n++) { tempMatrix.data[i][j] += A.data[i][n] * B.data[n][j]; } tempMatrix.data[i][j] = tempMatrix.data[i][j].toFixed(5); } } return tempMatrix; } return false; }; // 求行列式 const determinant = matrix => { const order = matrix.length; let cofactor; let result = 0; if (order === 1) { return matrix[0][0]; } for (let i = 0; i < order; i++) { cofactor = []; for (let j = 0; j < order - 1; j++) { cofactor[j] = []; for (let k = 0; k < order - 1; k++) { cofactor[j][k] = matrix[j + 1][k < i ? k : k + 1]; } } result += matrix[0][i] * Math.pow(-1, i) * determinant(cofactor); } return result; }; // 矩阵数乘 function scalarMultiply(num, matrix) { const row = matrix.length; const col = matrix[0].length; const result = []; for (let i = 0; i < row; i++) { result[i] = []; for (let j = 0; j < col; j++) { result[i][j] = num * matrix[i][j]; } } return result; } // 求逆矩阵 function inverseMatrix(matrix) { if (determinant(matrix) === 0) { return false; } // 求代数余子式 function cofactor(matrix, row, col) { const order = matrix.length; const new_matrix = []; let _row; let _col; for (let i = 0; i < order - 1; i++) { new_matrix[i] = []; _row = i < row ? i : i + 1; for (let j = 0; j < order - 1; j++) { _col = j < col ? j : j + 1; new_matrix[i][j] = matrix[_row][_col]; } } return Math.pow(-1, row + col) * determinant(new_matrix); } const order = matrix.length; const adjoint = []; for (let i = 0; i < order; i++) { adjoint[i] = []; for (let j = 0; j < order; j++) { adjoint[i][j] = cofactor(matrix, j, i); } } return scalarMultiply(1 / determinant(matrix), adjoint); } export default DetectProcess;
the_stack
import { Injectable } from '@angular/core'; import { SidePreviewsConfig, SlideConfig } from '../model/slide-config.interface'; import { PlayConfig } from '../model/play-config.interface'; import { KS_DEFAULT_ACCESSIBILITY_CONFIG } from '../components/accessibility-default'; import { PreviewConfig } from '../model/preview-config.interface'; import { Size } from '../model/size.interface'; import { ButtonsConfig, ButtonsStrategy } from '../model/buttons-config.interface'; import { DotsConfig } from '../model/dots-config.interface'; import { AdvancedLayout, GridLayout, LineLayout, PlainGalleryConfig, PlainGalleryStrategy } from '../model/plain-gallery-config.interface'; import { CurrentImageConfig } from '../model/current-image-config.interface'; import { LoadingConfig, LoadingType } from '../model/loading-config.interface'; import { Description, DescriptionStrategy, DescriptionStyle } from '../model/description.interface'; import { CarouselConfig } from '../model/carousel-config.interface'; import { CarouselImageConfig } from '../model/carousel-image-config.interface'; import { BreakpointsConfig, CarouselPreviewConfig } from '../model/carousel-preview-config.interface'; import { KeyboardServiceConfig } from '../model/keyboard-service-config.interface'; import { LibConfig } from '../model/lib-config.interface'; export const DEFAULT_PREVIEW_SIZE: Size = { height: '50px', width: 'auto' }; export const DEFAULT_LAYOUT: LineLayout = new LineLayout(DEFAULT_PREVIEW_SIZE, { length: -1, wrap: false }, 'flex-start'); export const DEFAULT_PLAIN_CONFIG: PlainGalleryConfig = { strategy: PlainGalleryStrategy.ROW, layout: DEFAULT_LAYOUT, advanced: { aTags: false, additionalBackground: '50% 50%/cover' } }; export const DEFAULT_LOADING: LoadingConfig = { enable: true, type: LoadingType.STANDARD }; export const DEFAULT_DESCRIPTION_STYLE: DescriptionStyle = { bgColor: 'rgba(0, 0, 0, .5)', textColor: 'white', marginTop: '0px', marginBottom: '0px', marginLeft: '0px', marginRight: '0px' }; export const DEFAULT_DESCRIPTION: Description = { strategy: DescriptionStrategy.ALWAYS_VISIBLE, imageText: 'Image ', numberSeparator: '/', beforeTextDescription: ' - ', style: DEFAULT_DESCRIPTION_STYLE }; export const DEFAULT_CAROUSEL_DESCRIPTION: Description = { strategy: DescriptionStrategy.ALWAYS_HIDDEN, imageText: 'Image ', numberSeparator: '/', beforeTextDescription: ' - ', style: DEFAULT_DESCRIPTION_STYLE }; export const DEFAULT_CURRENT_IMAGE_CONFIG: CurrentImageConfig = { navigateOnClick: true, loadingConfig: DEFAULT_LOADING, description: DEFAULT_DESCRIPTION, downloadable: false, invertSwipe: false }; export const DEFAULT_CAROUSEL_IMAGE_CONFIG: CarouselImageConfig = { description: DEFAULT_CAROUSEL_DESCRIPTION, invertSwipe: false }; export const DEFAULT_CURRENT_CAROUSEL_CONFIG: CarouselConfig = { maxWidth: '100%', maxHeight: '400px', showArrows: true, objectFit: 'cover', keyboardEnable: true, modalGalleryEnable: false, legacyIE11Mode: false }; export const DEFAULT_CURRENT_CAROUSEL_PLAY: PlayConfig = { autoPlay: true, interval: 5000, pauseOnHover: true }; export const DEFAULT_CAROUSEL_BREAKPOINTS: BreakpointsConfig = { xSmall: 100, small: 100, medium: 150, large: 200, xLarge: 200 }; export const DEFAULT_CAROUSEL_PREVIEWS_CONFIG: CarouselPreviewConfig = { visible: true, number: 4, arrows: true, clickable: true, width: 100 / 4 + '%', maxHeight: '200px', breakpoints: DEFAULT_CAROUSEL_BREAKPOINTS }; export const DEFAULT_KEYBOARD_SERVICE_CONFIG: KeyboardServiceConfig = { shortcuts: ['ctrl+s', 'meta+s'], disableSsrWorkaround: false }; export const DEFAULT_SLIDE_CONFIG: SlideConfig = { infinite: false, playConfig: { autoPlay: false, interval: 5000, pauseOnHover: true } as PlayConfig, sidePreviews: { show: true, size: { width: '100px', height: 'auto' } } as SidePreviewsConfig }; export const DEFAULT_PREVIEW_CONFIG: PreviewConfig = { visible: true, number: 3, arrows: true, clickable: true, size: DEFAULT_PREVIEW_SIZE }; const DEFAULT_CONFIG: LibConfig = Object.freeze({ slideConfig: DEFAULT_SLIDE_CONFIG, accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG, previewConfig: DEFAULT_PREVIEW_CONFIG, buttonsConfig: { visible: true, strategy: ButtonsStrategy.DEFAULT } as ButtonsConfig, dotsConfig: { visible: true } as DotsConfig, plainGalleryConfig: DEFAULT_PLAIN_CONFIG, currentImageConfig: DEFAULT_CURRENT_IMAGE_CONFIG, keyboardConfig: undefined, // by default nothing, because the library uses default buttons automatically carouselConfig: DEFAULT_CURRENT_CAROUSEL_CONFIG, carouselImageConfig: DEFAULT_CAROUSEL_IMAGE_CONFIG, carouselPreviewsConfig: DEFAULT_CAROUSEL_PREVIEWS_CONFIG, carouselPlayConfig: DEFAULT_CURRENT_CAROUSEL_PLAY, carouselDotsConfig: { visible: true } as DotsConfig, enableCloseOutside: true, keyboardServiceConfig: DEFAULT_KEYBOARD_SERVICE_CONFIG }); /** * Service to handle library configuration in a unique place */ @Injectable({ providedIn: 'root' }) export class ConfigService { configMap: Map<number, LibConfig> = new Map<number, LibConfig>(); getConfig(id: number): LibConfig | undefined { this.initIfNotExists(id); return this.configMap.get(id); } setConfig(id: number, obj: LibConfig | undefined): void { this.initIfNotExists(id); if (!obj) { return; } if ( !DEFAULT_CONFIG || !DEFAULT_CONFIG.slideConfig || !DEFAULT_CONFIG.slideConfig.sidePreviews || !DEFAULT_CONFIG.previewConfig || !DEFAULT_CONFIG.previewConfig.size || !DEFAULT_CONFIG.previewConfig.number || !DEFAULT_CONFIG.plainGalleryConfig || !DEFAULT_CONFIG.currentImageConfig || !DEFAULT_CONFIG.currentImageConfig || !DEFAULT_CONFIG.currentImageConfig.description || !DEFAULT_CONFIG.carouselImageConfig || !DEFAULT_CONFIG.carouselImageConfig.description || !DEFAULT_CONFIG.carouselPreviewsConfig || !DEFAULT_CONFIG.carouselPreviewsConfig.breakpoints || !DEFAULT_CAROUSEL_PREVIEWS_CONFIG.number ) { throw new Error('Internal library error - DEFAULT_CONFIG must be fully initialized!!!'); } const newConfig: LibConfig = Object.assign({}, this.configMap.get(id)); if (obj.slideConfig) { let playConfig; let sidePreviews; let size; if (obj.slideConfig.playConfig) { playConfig = Object.assign({}, DEFAULT_CONFIG.slideConfig.playConfig, obj.slideConfig.playConfig); } else { playConfig = DEFAULT_CONFIG.slideConfig.playConfig; } if (obj.slideConfig.sidePreviews) { if (obj.slideConfig.sidePreviews.size) { size = Object.assign({}, DEFAULT_CONFIG.slideConfig.sidePreviews.size, obj.slideConfig.sidePreviews.size); } else { size = DEFAULT_CONFIG.slideConfig.sidePreviews.size; } sidePreviews = Object.assign({}, DEFAULT_CONFIG.slideConfig.sidePreviews, obj.slideConfig.sidePreviews); } else { sidePreviews = DEFAULT_CONFIG.slideConfig.sidePreviews; size = DEFAULT_CONFIG.slideConfig.sidePreviews.size; } const newSlideConfig: SlideConfig = Object.assign({}, DEFAULT_CONFIG.slideConfig, obj.slideConfig); newSlideConfig.playConfig = playConfig; newSlideConfig.sidePreviews = sidePreviews; newSlideConfig.sidePreviews.size = size; newConfig.slideConfig = newSlideConfig; } if (obj.accessibilityConfig) { newConfig.accessibilityConfig = Object.assign({}, DEFAULT_CONFIG.accessibilityConfig, obj.accessibilityConfig); } if (obj.previewConfig) { let size: Size; let num: number; if (obj.previewConfig.size) { size = Object.assign({}, DEFAULT_CONFIG.previewConfig.size, obj.previewConfig.size); } else { size = DEFAULT_CONFIG.previewConfig.size; } if (obj.previewConfig.number) { if (obj.previewConfig.number <= 0) { // if number is <= 0 reset to default num = DEFAULT_CONFIG.previewConfig.number; } else { num = obj.previewConfig.number; } } else { num = DEFAULT_CONFIG.previewConfig.number; } const newPreviewConfig: PreviewConfig = Object.assign({}, DEFAULT_CONFIG.previewConfig, obj.previewConfig); newPreviewConfig.size = size; newPreviewConfig.number = num; newConfig.previewConfig = newPreviewConfig; } if (obj.buttonsConfig) { newConfig.buttonsConfig = Object.assign({}, DEFAULT_CONFIG.buttonsConfig, obj.buttonsConfig); } if (obj.dotsConfig) { newConfig.dotsConfig = Object.assign({}, DEFAULT_CONFIG.dotsConfig, obj.dotsConfig); } if (obj.plainGalleryConfig) { let advanced; let layout; if (obj.plainGalleryConfig.advanced) { advanced = Object.assign({}, DEFAULT_CONFIG.plainGalleryConfig.advanced, obj.plainGalleryConfig.advanced); } else { advanced = DEFAULT_CONFIG.plainGalleryConfig.advanced; } if (obj.plainGalleryConfig.layout) { // it isn't mandatory to use assign, because obj.plainGalleryConfig.layout is an instance of class (LineaLayout, GridLayout, AdvancedLayout) layout = obj.plainGalleryConfig.layout; } else { layout = DEFAULT_CONFIG.plainGalleryConfig.layout; } const newPlainGalleryConfig: PlainGalleryConfig = Object.assign({}, DEFAULT_CONFIG.plainGalleryConfig, obj.plainGalleryConfig); newPlainGalleryConfig.layout = layout; newPlainGalleryConfig.advanced = advanced; newConfig.plainGalleryConfig = initPlainGalleryConfig(newPlainGalleryConfig); } if (obj.currentImageConfig) { let loading; let description; let descriptionStyle; if (obj.currentImageConfig.loadingConfig) { loading = Object.assign({}, DEFAULT_CONFIG.currentImageConfig.loadingConfig, obj.currentImageConfig.loadingConfig); } else { loading = DEFAULT_CONFIG.currentImageConfig.loadingConfig; } if (obj.currentImageConfig.description) { description = Object.assign({}, DEFAULT_CONFIG.currentImageConfig.description, obj.currentImageConfig.description); if (obj.currentImageConfig.description.style) { descriptionStyle = Object.assign({}, DEFAULT_CONFIG.currentImageConfig.description.style, obj.currentImageConfig.description.style); } else { descriptionStyle = DEFAULT_CONFIG.currentImageConfig.description.style; } } else { description = DEFAULT_CONFIG.currentImageConfig.description; descriptionStyle = DEFAULT_CONFIG.currentImageConfig.description.style; } const newCurrentImageConfig: CurrentImageConfig = Object.assign({}, DEFAULT_CONFIG.currentImageConfig, obj.currentImageConfig); newCurrentImageConfig.loadingConfig = loading; newCurrentImageConfig.description = description; newCurrentImageConfig.description.style = descriptionStyle; newConfig.currentImageConfig = newCurrentImageConfig; } if (obj.keyboardConfig) { newConfig.keyboardConfig = Object.assign({}, DEFAULT_CONFIG.keyboardConfig, obj.keyboardConfig); } // carousel if (obj.carouselConfig) { newConfig.carouselConfig = Object.assign({}, DEFAULT_CONFIG.carouselConfig, obj.carouselConfig); } if (obj.carouselImageConfig) { let description; let descriptionStyle; if (obj.carouselImageConfig.description) { description = Object.assign({}, DEFAULT_CONFIG.carouselImageConfig.description, obj.carouselImageConfig.description); if (obj.carouselImageConfig.description.style) { descriptionStyle = Object.assign({}, DEFAULT_CONFIG.carouselImageConfig.description.style, obj.carouselImageConfig.description.style); } else { descriptionStyle = DEFAULT_CONFIG.carouselImageConfig.description.style; } } else { description = DEFAULT_CONFIG.carouselImageConfig.description; descriptionStyle = DEFAULT_CONFIG.carouselImageConfig.description.style; } const newCarouselImageConfig: CarouselImageConfig = Object.assign({}, DEFAULT_CONFIG.carouselImageConfig, obj.carouselImageConfig); newCarouselImageConfig.description = description; newCarouselImageConfig.description.style = descriptionStyle; newConfig.carouselImageConfig = newCarouselImageConfig; } if (obj.carouselPlayConfig) { // check values if (obj.carouselPlayConfig.interval <= 0) { throw new Error(`Carousel's interval must be a number >= 0`); } newConfig.carouselPlayConfig = Object.assign({}, DEFAULT_CONFIG.carouselPlayConfig, obj.carouselPlayConfig); } if (obj.carouselPreviewsConfig) { // check values let num: number; let breakpoints: BreakpointsConfig; if (!obj.carouselPreviewsConfig.number || obj.carouselPreviewsConfig.number <= 0) { num = DEFAULT_CAROUSEL_PREVIEWS_CONFIG.number; } else { num = obj.carouselPreviewsConfig.number; } if (obj.carouselPreviewsConfig.breakpoints) { breakpoints = Object.assign({}, DEFAULT_CONFIG.carouselPreviewsConfig.breakpoints, obj.carouselPreviewsConfig.breakpoints); } else { breakpoints = DEFAULT_CONFIG.carouselPreviewsConfig.breakpoints; } newConfig.carouselPreviewsConfig = Object.assign({}, DEFAULT_CONFIG.carouselPreviewsConfig, obj.carouselPreviewsConfig); newConfig.carouselPreviewsConfig.number = num; newConfig.carouselPreviewsConfig.breakpoints = breakpoints; // Init preview image width based on the number of previews in PreviewConfig // Don't move this line above, because I need to be sure that both configPreview.number // and configPreview.size are initialized newConfig.carouselPreviewsConfig.width = 100 / newConfig.carouselPreviewsConfig.number + '%'; } if (obj.carouselDotsConfig) { newConfig.carouselDotsConfig = Object.assign({}, DEFAULT_CONFIG.carouselDotsConfig, obj.carouselDotsConfig); } if (obj.enableCloseOutside === undefined) { newConfig.enableCloseOutside = DEFAULT_CONFIG.enableCloseOutside; } else { newConfig.enableCloseOutside = obj.enableCloseOutside; } if (obj.keyboardServiceConfig) { newConfig.keyboardServiceConfig = Object.assign({}, DEFAULT_KEYBOARD_SERVICE_CONFIG, obj.keyboardServiceConfig); } this.configMap.set(id, newConfig); } private initIfNotExists(id: number): void { if (!this.configMap.has(id)) { this.configMap.set(id, DEFAULT_CONFIG); } } } /** * Function to build and return a `PlainGalleryConfig` object, proving also default values and validating the input object. * @param plainGalleryConfig object with the config requested by user * @returns PlainGalleryConfig the plain gallery configuration * @throws an Error if layout and strategy aren't compatible */ function initPlainGalleryConfig(plainGalleryConfig: PlainGalleryConfig): PlainGalleryConfig { const newPlayGalleryConfig: PlainGalleryConfig = Object.assign({}, DEFAULT_CONFIG.plainGalleryConfig, plainGalleryConfig); if (newPlayGalleryConfig.layout instanceof LineLayout) { if (newPlayGalleryConfig.strategy !== PlainGalleryStrategy.ROW && newPlayGalleryConfig.strategy !== PlainGalleryStrategy.COLUMN) { throw new Error('LineLayout requires either ROW or COLUMN strategy'); } if (!newPlayGalleryConfig.layout || !newPlayGalleryConfig.layout.breakConfig) { throw new Error('Both layout and breakConfig must be valid'); } } if (newPlayGalleryConfig.layout instanceof GridLayout) { if (newPlayGalleryConfig.strategy !== PlainGalleryStrategy.GRID) { throw new Error('GridLayout requires GRID strategy'); } if (!newPlayGalleryConfig.layout || !newPlayGalleryConfig.layout.breakConfig) { throw new Error('Both layout and breakConfig must be valid'); } // force wrap for grid layout newPlayGalleryConfig.layout.breakConfig.wrap = true; } if (newPlayGalleryConfig.layout instanceof AdvancedLayout) { if (newPlayGalleryConfig.strategy !== PlainGalleryStrategy.CUSTOM) { throw new Error('AdvancedLayout requires CUSTOM strategy'); } } return newPlayGalleryConfig; }
the_stack
import {AUTH_MESSAGE} from "./authentication-component"; /** * Created by frank.zickert on 28.02.19. */ declare var require: any; import jwt from 'jsonwebtoken'; import {getBasename} from '../libs/iso-libs'; /** * token handed over to the user's browser, serves as password to encrypt/decrypt the Medium-access token * @type {string} */ export const IC_WEB_TOKEN = "IC_WEB_TOKEN"; /** * unique id of the user, comes from the provider (GitHub, Medium, etc) * @type {string} */ export const IC_USER_ID = 'IC_USER_ID'; export const EMAIL_CONFIRMATION_PARAM = "confirmationtoken"; export const EMAIL_PARAM = "email"; export const PASSWORD_PARAM = "password"; export const AUTH_STATUS = { PENDING: "pending", // the authentication is pending, e.g. e-mail waitung for the confirmation ACTIVE: "active" // the authentication is active } /** * This is an Express middleware that checks whether there is a cookie in the header that contains valid login * data * * @param req * @param res * @param next * @returns if successful, it calls the next middleware, if not, it throws an exception that causes the * next error handler to be called */ export const createAuthMiddleware = (clientSecret, onAuthenticated: (userid:string) => void) => (req, res, next) => { //console.log("createAuthMiddleware", req.universalCookies); const webtoken = req.universalCookies.get(IC_WEB_TOKEN); const userId = req.universalCookies.get(IC_USER_ID); if (webtoken !== undefined && userId !== undefined) { //console.log("webtoken: ", webtoken); //console.log("userId: ", userId); try { const decoded = jwt.verify(webtoken, clientSecret); if (decoded !== undefined) { const { id } = decoded; //console.log("id: ", id); // we might have numbers... then the "===" comparison does not work if (id.toString() === userId.toString()) { // the token contains the correct id //console.log("token matches :-)") onAuthenticated(id.toString()); return next(); } } return next(AUTH_MESSAGE.FAILED); //throw new Error("UserId in Token does not match UserId in cookie"); } catch(err) { return next(AUTH_MESSAGE.FAILED); //throw new Error(err); } } else { return next(AUTH_MESSAGE.NOTLOGGEDIN); //throw new Error('No token present!'); } }; export interface IUserData { id: string | undefined, name: string | undefined, username: string | undefined, imageUrl: string | undefined, email: string | undefined, access_token: string | undefined, encrypted_password?: string, status?: string } const getEncryptedAccessToken = (id, clientSecret, access_token) => { const today = new Date(); const expirationDate = new Date(today); expirationDate.setDate(today.getDate() + 60); // we use the clientSecret to sign the webtoken const webtoken = jwt.sign({ id: id, exp: expirationDate.getTime() / 1000, }, clientSecret); // now let's use the webtoken to encrypt the access token const encryptedAccessToken = jwt.sign({ id: id, accessToken: access_token, exp: expirationDate.getTime() / 1000, }, webtoken); return { webtoken: webtoken, encryptedAccessToken: encryptedAccessToken }; }; /** * Use this middleware at the endpoint that is specified as the callback-url. * * @param fetchAccessToken function that can be called to fetch the access Token * @param getUserData function to get the userData, takes as input the response from the accessToken-request * @param clientSecret * @param callbackUrl * @param storeAuthData * @returns {any} */ export const createCallbackMiddleware = ( clientSecret, fetchAccessToken: (req: any) => any, getUserData: (resJson: any) => Promise<IUserData>, storeAuthData: (request: any, key: string, val: any, jsonData: any) => void, getAuthData: (request: any, matchBrowserIdentity: boolean, key: string, val: any) => any, loginUrl: string ) => async function (req, res, next) { const path = require('path'); //console.log("THIS IS THE AUTH CALLBACK - authMiddleware"); // we use this middleware also as endpoint for email confirmation, then the token-parameter must be specified const email_confirmation = req.query[EMAIL_CONFIRMATION_PARAM]; const email_param = req.query[EMAIL_PARAM]; const password_param = req.query[PASSWORD_PARAM]; const page = req.query["page"]; //console.log("received params: ", email_confirmation, email_param, password_param); if (email_param) { // get the entry of the database const authDataList = await getAuthData( req, // request: any false, //matchBrowserIdentity -- we do not want to match the browser identity, the user might use another browser to confirm he mail address IC_USER_ID, // key: string email_param//val: any, ); //console.log("retrieved auth-data-list: ", authDataList); // check whether the user already exists const parsedAuthDataList = authDataList.map(raw=> JSON.parse(raw.jsonData)); // the user logs in with her email and password if (password_param !== undefined && parsedAuthDataList.length > 0) { const authData = parsedAuthDataList .reduce((result, cur) => result !== undefined ? ( // check whether we have a better state! cur.status == AUTH_STATUS.ACTIVE ? cur : result ) : ( // check whether the password is correct cur.encrypted_password === password_param ? cur: undefined ), undefined); if (authData !== undefined) { if (authData.status == AUTH_STATUS.PENDING) { return next(AUTH_MESSAGE.VERIFICATIONPENDING); } // create a new webtoken, i.e. other browser will be logged out! const { webtoken, encryptedAccessToken } = getEncryptedAccessToken(email_param, clientSecret, password_param); // put the encrypted web token into the database, this is user (browser)-specific data! const storeResult = await storeAuthData( req, // request: any IC_USER_ID, // key: string email_param, //val: any, Object.assign({}, authData, { encryptedAccessToken: encryptedAccessToken }) ); req.universalCookies.set(IC_WEB_TOKEN, webtoken, { path: '/' }); req.universalCookies.set(IC_USER_ID, email_param, { path: '/' }); //console.log("store password verified result: ", storeResult); res.redirect(`${path.join(getBasename(), page !== undefined ? page : loginUrl)}?message=${AUTH_MESSAGE.SUCCESS}`); } else { //console.log ("could not verify password, ", password_param,email_param); return next(AUTH_MESSAGE.FAILED); } return; } else if (email_confirmation && parsedAuthDataList.length > 0) { // the user clicks the link from within the confirmation email const authData = parsedAuthDataList .reduce((result, cur) => result !== undefined ? result : ( cur.encryptedAccessToken === email_confirmation ? cur: undefined ), undefined); //console.log("retrieved auth-data: ", authData); if (authData !== undefined) { const { webtoken, encryptedAccessToken } = getEncryptedAccessToken(email_param, clientSecret, email_confirmation); // put the encrypted web token into the database, this is user (browser)-specific data! const storeResult = await storeAuthData( req, // request: any IC_USER_ID, // key: string email_param, //val: any, Object.assign({}, authData, { status: AUTH_STATUS.ACTIVE, encryptedAccessToken: encryptedAccessToken }) ); //console.log("webtoken: ", webtoken, email_param) req.universalCookies.set(IC_WEB_TOKEN, webtoken, { path: '/' }); req.universalCookies.set(IC_USER_ID, email_param, { path: '/' }); //console.log("store email verified result: ", storeResult); res.redirect(`${path.join(getBasename(), page !== undefined ? page : loginUrl)}?message=${AUTH_MESSAGE.MAILVERIFIED}`); } else { //console.log ("could not verify access token, ", email_confirmation,email_param); return next(AUTH_MESSAGE.FAILED); } return; } } const { redirectPage, fFetch } = fetchAccessToken(req); // store the redirectPage in the request for further processing console.log("redirect to: ", redirectPage); req["redirectPage"] = redirectPage; await fFetch().then(async function(resJson) { //const { token_type, access_token /*, refresh_token, scope, expires_at */} = resJson; // try the freshly acquired token and get the user's Medium.com id await getUserData(resJson).then(async function(data) { //console.log("get user data: ", JSON.stringify(data)); const {id, name, username, imageUrl, access_token, email, status } = data; //console.log("id: ", id); //console.log("name: ", name); const { webtoken, encryptedAccessToken } = getEncryptedAccessToken(id, clientSecret, access_token); //console.log("encryptedAccessToken: ", encryptedAccessToken); // TODO id may be undefined when the token expired! //console.log("storeAuthData: ", storeAuthData) // put the encrypted web token into the database, this is user (browser)-specific data! const storeResult = await storeAuthData( req, // request: any IC_USER_ID, // key: string id, //val: any, Object.assign({ /** We only store the encrypted token when we have an active status, i.e. a auth-provider * we keep it in clear-text for e-mail */ encryptedAccessToken: status === AUTH_STATUS.ACTIVE ? encryptedAccessToken : access_token, name: name, username: username, imageUrl: imageUrl, email: email, status: status, }, password_param ? { encrypted_password: password_param } : {}) //jsonData: any ); //console.log("storeResult: ", storeResult); // give the webtoken to back to the user - if the account is valid, only! if (status === AUTH_STATUS.ACTIVE) { req.universalCookies.set(IC_WEB_TOKEN, webtoken, { path: '/' }); req.universalCookies.set(IC_USER_ID, id, { path: '/' }); } //console.log("done") //'http://' +path.join(req.headers.host + + res.redirect(path.join(getBasename(), redirectPage)); return; }); }); };
the_stack
import React, { Component, ReactNode } from 'react'; import { Badge, Button, ButtonGroup, ButtonToolbar, Col, Row, ToggleButton, InputGroup, FormControl, Spinner } from 'react-bootstrap'; import { BsArrowCounterclockwise, BsArrowRepeat, BsPauseFill, BsPlayFill, BsFilter, BsTrashFill } from 'react-icons/bs'; import DataTable, { IDataTableColumn } from 'react-data-table-component'; // Local import { requestAPI } from '../handler'; import { JobAction } from '../types'; namespace types { export type Props = { availableColumns: string[]; defaultColumns?: string[]; itemsPerPage: number; itemsPerPageOptions: Array<number>; userOnly: boolean; processing: boolean; reloadQueue: boolean; autoReload: boolean; reloadRate: number; processJobAction: ( action: JobAction, rows: Record<string, unknown>[] ) => void; }; export type State = { rows: string[][]; selectedRows: Record<string, unknown>[]; displayRows: Record<string, unknown>[]; clearSelected: boolean; columns: string[]; displayColumns: IDataTableColumn<Record<string, unknown>>[]; itemsPerPage: number; filterQuery: string; lastSqueueFetch: Date; autoReload: boolean; reloadRate: number; reloadLimit: number; userOnly: boolean; loading: boolean; theme: string; observer: MutationObserver; }; } export default class SqueueDataTable extends Component< types.Props, types.State > { constructor(props: types.Props) { super(props); this.sortRows = this.sortRows.bind(this); let reloadRate = this.props.reloadRate; if (this.props.reloadRate < 5000) { console.log( 'jupyterlab-slurm has a floor for reloadRate of 5 seconds, you passed ' + this.props.reloadRate ); reloadRate = 5000; } const columns = props.defaultColumns ? props.defaultColumns : props.availableColumns; const body = document.getElementsByTagName('body')[0]; const observer = new MutationObserver(mutationRecords => { if (mutationRecords[0].oldValue === 'true') { this.setState({ theme: 'dark' }); } else { this.setState({ theme: 'default' }); } }); observer.observe(body, { attributes: true, attributeFilter: ['data-jp-theme-light'], attributeOldValue: true }); this.state = { rows: [], displayRows: [], selectedRows: [], clearSelected: false, columns: columns, displayColumns: columns.map(x => { return { name: x, selector: x, sortable: true, maxWidth: '200px' }; }), itemsPerPage: this.props.itemsPerPage, // make this prop dependent filterQuery: '', lastSqueueFetch: new Date(), autoReload: props.autoReload, reloadRate: reloadRate, reloadLimit: 5000, userOnly: props.userOnly, loading: false, theme: 'default', observer: observer }; } clearSelectedRows(): void { this.setState({ selectedRows: [], clearSelected: true }); } private toggleUserOnly() { const { userOnly } = this.state; this.setState({ userOnly: !userOnly }); } onSelectedRows(rowState: { allSelected: boolean; selectedCount: number; selectedRows: Record<string, unknown>[]; }): void { this.setState({ selectedRows: rowState.selectedRows, clearSelected: false }); } handleJobAction(action: JobAction): void { this.props.processJobAction(action, this.state.selectedRows); if (action === 'kill') { this.clearSelectedRows(); } } async getData(rateLimit = 0): Promise<string[][]> { const { userOnly } = this.state; const squeueParams = new URLSearchParams(`userOnly=${userOnly}`); if (rateLimit > 0) { const currentDT = new Date(); const delta = Number(currentDT) - Number(this.state.lastSqueueFetch); if (delta < rateLimit) { return; } } if (this.state.loading) { return; } this.setState({ loading: true }); return await requestAPI<any>('squeue', squeueParams) .then(data => { console.log('SqueueDataTable getData() squeue', squeueParams, data); this.setState( { lastSqueueFetch: new Date(), rows: data.data, loading: false }, () => { this.updateDisplayRows(); console.log('loading finished'); } ); }) .catch(error => { console.error('SqueueDataTable getData() error', error); return null; }); } private sortRows( rows: Record<string, unknown>[], field: string, direction: string ): Record<string, unknown>[] { function getSortValue( a: Record<string, unknown>, b: Record<string, unknown> ): number { // by default use the standard string comparison for field values let val_a = a[field]; let val_b = b[field]; // If the field value is a number, convert to number and use that for comparison if (!isNaN(Number(a[field])) && !isNaN(Number(b[field]))) { val_a = Number(a[field]); val_b = Number(b[field]); } else if (field === 'JOBID') { // Requires a special sorting for job array strings where it can't be converted to a number const jobIDSpecials = /[0-9][-_[\]]/g; const parts_a = String(a[field]) .split(jobIDSpecials) .map(x => Number(x)); const parts_b = String(b[field]) .split(jobIDSpecials) .map(x => Number(x)); let tot_a = 0; let tot_b = 0; let i; for (i = 0; i < parts_a.length; i++) { tot_a += parts_a[i]; } for (i = 0; i < parts_b.length; i++) { tot_b += parts_b[i]; } val_a = tot_a; val_b = tot_b; } const greater = val_a > val_b; if (direction === 'desc') { if (greater) { return 1; } else { return -1; } } else { if (greater) { return -1; } else { return 1; } } } const sorted_rows = rows.slice(0); sorted_rows.sort(getSortValue); return sorted_rows; } private updateDisplayRows() { const displayRows = this.state.rows .filter((row: string[]) => { const filterQuery = this.state.filterQuery.toLowerCase(); for (const el of row) { if (el.toLowerCase().includes(filterQuery)) { // console.log(`true for ${row}`); return true; } } return false; }) .map((x: string[]) => { const item: Record<string, unknown> = { id: x[0] }; let i, col, colValue; for (i = 0, col = 0; col < this.state.columns.length; i++, col++) { colValue = this.state.columns[col]; item[colValue] = x[i]; } return item; }); this.setState({ displayRows: displayRows }); } async onReloadButtonClick(): Promise<void> { await this.reload(); const currentDT = new Date(); const delta = Number(currentDT) - Number(this.state.lastSqueueFetch); if (delta >= this.state.reloadLimit) { await this.getData(); } } async reload(): Promise<void> { this.setState({ clearSelected: false }); } async componentDidMount(): Promise<void> { await this.getData().then(async () => { await this.reload(); }); // if (this.state.autoReload) { // useEffect(() => { // const interval = setInterval(async () => { // await this.getData(this.state.reloadRate); // }, this.state.reloadRate); // return () => clearInterval(interval); // }, []); // } if (this.state.autoReload) { const reload = async () => { this.setState({ loading: true }); await this.getData(this.state.reloadRate); this.setState({ loading: false }); setTimeout(reload, this.state.reloadRate); }; reload(); } } async componentDidUpdate( prevProps: Readonly<types.Props>, prevState: Readonly<types.State> ): Promise<void> { // reset the clear state to re-enable selections if (this.state.clearSelected) { this.setState({ clearSelected: false }); } // after a user submits a series of job actions (submit, cancel, hold, release), reload the squeue table view // we need to limit the frequency of squeue requests if (this.props.reloadQueue) { this.getData(this.state.reloadLimit); } // make sure a last attempt is made to reload when all job actions have completed if (prevProps.reloadQueue && !this.props.reloadQueue) { this.getData(); } } componentWillUnmount(): void { this.state.observer.disconnect(); } async handleFilter(filter: string): Promise<void> { this.setState({ filterQuery: filter }, this.updateDisplayRows); } render(): ReactNode { /* console.log({ rows: this.state.rows, columns: columns, data: data, rows_length: this.state.rows.length, itemsPerPage: this.state.itemsPerPage, selectedRows: selectedRows, displayedColumns: this.state.displayedColumns }); */ return ( <> <Row className={'mt-4 justify-content-start jp-SlurmWidget-row'}> <ButtonToolbar> <ButtonGroup size="sm" className={'ml-3 mr-2'}> <Button className="jp-SlurmWidget-table-button" variant="outline-secondary" onClick={this.onReloadButtonClick.bind(this)} > <BsArrowRepeat /> Update Queue </Button> <Button className="jp-SlurmWidget-table-button" disabled={this.state.selectedRows.length === 0} variant="outline-secondary" onClick={this.clearSelectedRows.bind(this)} > <BsArrowCounterclockwise /> Clear Selected {this.state.selectedRows.length > 0 && ( <Badge variant="light" pill={true} className={'jp-SlurmWidget-table-button-badge'} > {this.state.selectedRows.length} </Badge> )} </Button> </ButtonGroup> <ButtonGroup size="sm"> <Button className="jp-SlurmWidget-table-button" disabled={this.state.selectedRows.length === 0} variant={'outline-danger'} onClick={() => { this.handleJobAction('kill'); }} > <BsTrashFill /> Kill Job(s) {this.state.selectedRows.length > 0 && ( <Badge variant="light" pill={true} className={'jp-SlurmWidget-table-button-badge'} > {this.state.selectedRows.length} </Badge> )} </Button> <Button className="jp-SlurmWidget-table-button" disabled={this.state.selectedRows.length === 0} variant={'outline-danger'} onClick={() => { this.handleJobAction('hold'); }} > <BsPauseFill /> Hold Job(s) {this.state.selectedRows.length > 0 && ( <Badge variant="light" pill={true} className={'jp-SlurmWidget-table-button-badge'} > {this.state.selectedRows.length} </Badge> )} </Button> <Button className="jp-SlurmWidget-table-button" disabled={this.state.selectedRows.length === 0} variant={'outline-danger'} onClick={() => { this.handleJobAction('release'); }} > <BsPlayFill /> Release Job(s) {this.state.selectedRows.length > 0 && ( <Badge variant="light" pill={true} className={'jp-SlurmWidget-table-button-badge'} > {this.state.selectedRows.length} </Badge> )} </Button> </ButtonGroup> </ButtonToolbar> </Row> <Row className={'justify-content-start jp-SlurmWidget-row'}> <ButtonToolbar> <Col lg> <InputGroup size="sm" className="jp-SlurmWidget-table-filter-input-group" > <InputGroup.Prepend> <InputGroup.Text className="jp-SlurmWidget-table-filter-label"> <BsFilter /> Filter </InputGroup.Text> </InputGroup.Prepend> <FormControl className="jp-SlurmWidget-table-filter-input" value={this.state.filterQuery} onChange={e => { this.handleFilter(e.target.value); }} /> </InputGroup> </Col> <Col> <ToggleButton type="checkbox" className="jp-SlurmWidget-user-only-checkbox" variant="outline-light" size="sm" onChange={this.toggleUserOnly.bind(this)} checked={this.state.userOnly} value="1" > Display my jobs only </ToggleButton> </Col> </ButtonToolbar> <Col> Last updated: {this.state.lastSqueueFetch.toLocaleDateString()}{' '} {this.state.lastSqueueFetch.toLocaleTimeString()} </Col> </Row> {this.state.loading && ( <Row className={'justify-content-center jp-SlurmWidget-row'}> <div className={'justify-content-center jp-SlurmWidget-squeue-loading'} > <Spinner animation="grow" className={'jp-SlurmWidget-squeue-loader'} /> </div> </Row> )} <Row className={ 'justify-content-center jp-SlurmWidget-row jp-SlurmWidget-table-row' } > <DataTable data={this.state.displayRows} columns={this.state.displayColumns} defaultSortField={this.props.availableColumns[0]} defaultSortAsc={false} sortFunction={this.sortRows} striped highlightOnHover pagination selectableRows clearSelectedRows={this.state.clearSelected} onSelectedRowsChange={this.onSelectedRows.bind(this)} noDataComponent={'No jobs currently queued.'} paginationPerPage={this.state.itemsPerPage} paginationRowsPerPageOptions={this.props.itemsPerPageOptions} theme={this.state.theme} noHeader={true} className={'jp-SlurmWidget-table'} /> </Row> </> ); } }
the_stack
import React from 'react'; import {get, has, isNil, isEqual, isObjectLike} from 'lodash'; import {ErrorBoundary} from './ErrorBoundary'; import {getRuntimeContext} from './util/util'; import {isExpression, parseExpressionString} from './util/vm'; import {RootState} from '../data/reducers'; import { BasicProps, ContainerContextType, ContainerSetDataOption, ExecTaskOptions, FormItemContextType, IteratorContextType, RCREContextType, runTimeType, TriggerContextType } from '../types'; import {withAllContext} from './util/withAllContext'; type ESChild = (runTime: runTimeType, context: { container: ContainerContextType; trigger: TriggerContextType, formItem?: FormItemContextType, rcre: RCREContextType iterator: IteratorContextType }) => any; export interface ESProps { children: ESChild; name?: string; type?: string; debounce?: number; defaultValue?: any; disabled?: boolean; clearFormStatusOnlyWhenDestroy?: boolean; disableClearWhenDestroy?: boolean; clearWhenDestory?: boolean; clearWhenDestroy?: boolean; /** * 满足一定条件就清空组件的值 */ autoClearCondition?: (value: any, props: any) => boolean; disabledAutoClear?: boolean; } interface ESComponentInternalProps extends BasicProps { triggerContext: TriggerContextType; } enum ValidateDecision { SKIP = 0, // 跳过本次验证 BREAK = 1, // 阻止所有的验证 PASS = 2 // 触发验证 } class ESComponent extends React.PureComponent<ESProps & ESComponentInternalProps> { static displayName = 'ES'; public debounceCache: { [key: string]: any }; public debounceTimer: any; public isDebouncing: boolean; constructor(props: ESProps & ESComponentInternalProps) { super(props); this.debounceCache = {}; this.isDebouncing = false; let runTime = getRuntimeContext(props.containerContext, props.rcreContext, { iteratorContext: props.iteratorContext }); let value; let name = props.name; let state: RootState = props.rcreContext.store.getState(); // 设置默认值的逻辑 if ((props.hasOwnProperty('defaultValue') && props.defaultValue !== null && props.defaultValue !== undefined) && name && !has(runTime.$data, name)) { let defaultValue = props.defaultValue; runTime.$data = state.$rcre.container[props.containerContext.model]; if (isExpression(defaultValue)) { defaultValue = parseExpressionString(defaultValue, runTime); } props.containerContext.$setData(name, defaultValue); value = defaultValue; } else if (name) { let existValue = get(state.$rcre.container[props.containerContext.model], name); value = existValue; if (!isNil(existValue) && props.debounce) { this.debounceCache[name] = existValue; } } if (props.formItemContext && name) { props.formItemContext.initControlElements(name, { type: props.type, disabled: props.disabled, value: value }); } } componentWillUnmount() { if (this.props.name) { let clearWhenDestroy = this.props.clearWhenDestory || this.props.clearWhenDestroy; // 表单模式下,自动开启数据清除功能 if (this.props.formItemContext && this.props.formItemContext.isUnderFormItem) { if (this.props.clearFormStatusOnlyWhenDestroy) { this.props.formItemContext.$deleteFormItem(this.props.name); clearWhenDestroy = false; } else if (this.props.disableClearWhenDestroy === false) { clearWhenDestroy = false; } else { clearWhenDestroy = true; } } if (clearWhenDestroy) { this.props.containerContext.$deleteData(this.props.name); } if (this.props.formItemContext) { // 清空FormItem中监听的状态 this.props.formItemContext.deleteControlElements(this.props.name); } } } public updateNameValue = (name: string, value: any, options: ContainerSetDataOption = {}) => { if (name === this.props.name) { if (typeof this.props.debounce === 'number' && !options.skipDebounce) { this.debounceCache[name] = value; clearTimeout(this.debounceTimer); this.debounceTimer = setTimeout(() => { this.isDebouncing = false; this.props.containerContext.$setData(name!, this.debounceCache[name!], options); }, this.props.debounce); this.isDebouncing = true; this.forceUpdate(); return; } } this.props.containerContext.$setData(name, value, options); } public clearNameValue = (name?: string) => { name = name || this.props.name; if (name) { this.props.containerContext.$deleteData(name); } } /** * 组件name的变更是否会触发FormItem验证 * +----------------+-----------------+-----------------+ * | prev | next | action | * +----------------------------------------------------+ * | name exist | name not exist | delete form | * +----------------------------------------------------+ * | name not exist | name exist | validate form | * +----------------------------------------------------+ * | name not exist | name not exist | skip | * +----------------------------------------------------+ * | name exist | name exist | validate form | * +----------------+-----------------+-----------------+ * @param nextProps */ private shouldNameTriggerValidate(nextProps: ESProps & BasicProps): ValidateDecision { // 前后都没有name属性跳过 if (!this.props.name && !nextProps.name) { return ValidateDecision.SKIP; } // 之前有,现在name没了,销毁 if (this.props.name && !nextProps.name) { // delete this.props.containerContext.$deleteData(this.props.name); return ValidateDecision.SKIP; } if (this.props.name === nextProps.name) { return ValidateDecision.SKIP; } if (this.props.name && nextProps.name && this.props.name !== nextProps.name) { // 清空旧的数据 this.props.containerContext.$deleteData(this.props.name); } // 剩下都可以 return ValidateDecision.PASS; } private shouldDisabledTriggerValidate(nextProps: ESProps & BasicProps): ValidateDecision { if (!this.props.formItemContext || !nextProps.formItemContext) { return ValidateDecision.SKIP; } // disabled都没变化的情况跳过 if (!this.props.disabled && !nextProps.disabled) { return ValidateDecision.SKIP; } // disabled都没变化的情况跳过 if (this.props.disabled && nextProps.disabled) { return ValidateDecision.SKIP; } // 之前是false,现在改成true,需要强制设置formItem为验证成功 if (!this.props.disabled && nextProps.disabled && nextProps.name) { nextProps.formItemContext.$setFormItem({ formItemName: nextProps.name, valid: true, status: 'success', errorMsg: '' }); // 这里直接跳过验证,不再进行下一步操作 return ValidateDecision.BREAK; } // 剩下的情况就是触发验证了 return ValidateDecision.PASS; } private shouldValueTriggerValidate(nextProps: ESProps & BasicProps): ValidateDecision { if (!this.props.formItemContext || !nextProps.formItemContext) { return ValidateDecision.SKIP; } let nextValue = nextProps.name ? nextProps.containerContext.$getData(nextProps.name) : undefined; let prevValue = this.props.name ? this.props.containerContext.$getData(this.props.name) : undefined; if (prevValue === nextValue) { return ValidateDecision.SKIP; } return ValidateDecision.PASS; } /** * 处理值变更,name变更,以及disabled变更这三种情况所触发的表单验证 * @param nextProps */ private shouldValidateFormItem(nextProps: ESProps & BasicProps) { if (!nextProps.formItemContext || !this.props.formItemContext) { return; } let list = [this.shouldNameTriggerValidate, this.shouldDisabledTriggerValidate, this.shouldValueTriggerValidate]; let shouldValidate = false; for (let func of list) { let decision: ValidateDecision = func.call(this, nextProps); if (decision === ValidateDecision.SKIP) { continue; } if (decision === ValidateDecision.BREAK) { return; } if (decision === ValidateDecision.PASS) { shouldValidate = true; break; } } if (shouldValidate && nextProps.name) { let nextValue = nextProps.containerContext.$getData(nextProps.name); nextProps.formItemContext.$validateFormItem(nextProps.name, nextValue); } } public componentWillUpdate(nextProps: ESProps & BasicProps) { if (this.props.name && nextProps.name) { let nextValue = nextProps.containerContext.$getData(nextProps.name); let prevValue = this.props.containerContext.$getData(this.props.name); if (!isEqual(prevValue, nextValue) && this.props.debounce) { this.debounceCache[this.props.name] = nextValue; } } if (typeof this.props.autoClearCondition === 'function' && !this.props.disabledAutoClear && nextProps.name) { let value = nextProps.containerContext.$getData(nextProps.name); let clear = this.props.autoClearCondition(value, nextProps); if (clear) { this.clearNameValue(this.props.name); } } this.shouldValidateFormItem(nextProps); } render() { if (typeof this.props.children !== 'function') { console.error(`ES 组件的子元素只能是个函数. 例如 \n <ES> {runTime => { return <div>{JSON.stringify(runTime.$data)}</div> }} <ES>`); return this.props.children; } let context = { container: { ...this.props.containerContext, $setData: this.updateNameValue }, rcre: this.props.rcreContext, formItem: this.props.formItemContext, trigger: this.props.triggerContext, iterator: this.props.iteratorContext }; let name = this.props.name; let runTime = getRuntimeContext(this.props.containerContext, this.props.rcreContext, { iteratorContext: this.props.iteratorContext, formItemContext: this.props.formItemContext, triggerContext: this.props.triggerContext }); if (name) { let value = get(runTime.$data, name); if (this.props.debounce && this.props.name) { value = this.debounceCache[this.props.name!]; } else if (this.props.name) { value = this.props.containerContext.$getData(this.props.name); } // 阻止底层组件引用赋值破坏数据 if (isObjectLike(value)) { Object.freeze(value); } runTime.$name = name; runTime.$value = value; } return ( <ErrorBoundary> {this.props.children(runTime, context) || null} </ErrorBoundary> ); } public async TEST_execTask(task: string, args: any, options: ExecTaskOptions) { return this.props.triggerContext.execTask(task, args, options); } public async TEST_simulateEvent(event: string, args: Object = {}) { if (!this.props.triggerContext) { console.warn('Connect: 组件没有绑定事件'); return null; } return this.props.triggerContext.eventHandle(event, args); } public TEST_setData(value: any) { if (this.props.name) { return this.props.containerContext.$setData(this.props.name, value); } } public TEST_getData() { return this.props; } public TEST_getNameValue(name: string) { return this.props.containerContext.$getData(name); } /** * @deprecated * @constructor */ public TEST_isNameValid() { // if (!this.options.isNameValid) { // return true; // } // // if (!this.info.name) { // return true; // } // // let value = this.getValueFromDataStore(this.info.name); // return this.options.isNameValid(value, this.info); } } class DommyES extends React.Component<ESProps> {} export const ES = withAllContext(ESComponent) as typeof DommyES;
the_stack
import { FileManager } from "../../jupyter-hooks/file-manager"; import { Checkpoint, ChangeType, CellRunData } from "../../checkpoint"; import { NodeyCell, Nodey, NodeyCodeCell, NodeyOutput, NodeyNotebook, NodeyMarkdown, NodeyRawCell, } from "../../nodey"; import { History } from "../history"; import { CodeHistory } from "../store"; import { Stage } from "./stage"; import { jsn } from "../../notebook"; export class Commit { readonly history: History; /* * The checkpoint and notebook are the identifying pieces of this commit */ public checkpoint: Checkpoint; private notebook: NodeyNotebook; /* * The stage is for recording *potentially* edited nodey and figuring out * what was really edited and how for this commit */ private stage: Stage; constructor( checkpoint: Checkpoint, history: History, fileManager: FileManager ) { this.checkpoint = checkpoint; this.history = history; this.stage = new Stage(history, fileManager); } public markAsPossiblyEdited(nodey: Nodey) { this.stage.dirty_nodey.push(nodey.name); } public addCell(added: NodeyCell, index: number) { // first see if this commit can be combined with a prior one const merged = this.attemptMergeWithPriorCheckpoint([added], [index]); // add cell is an event that changes notebook version if (!this.notebook) this.createNotebookVersion(); // make sure new cell's parent is this newNotebook added.parent = this.notebook.name; let name = added.name; // make sure new cell's checkpoint is this one added.created = this.checkpoint.timestamp; // add added cell to notebook this.notebook.cells.splice(index, 0, name); // update checkpoint let cellDat = { cell: name, changeType: ChangeType.ADDED, } as CellRunData; this.checkpoint.targetCells.push(cellDat); // record checkpoint if (!merged) this.history.checkpoints.add(this.checkpoint); } public deleteCell(deleted: NodeyCell) { let oldNotebook = this.history.store.currentNotebook; let index = oldNotebook?.cells?.indexOf(deleted?.name) || -1; // first see if this commit can be combined with a prior one const merged = this.attemptMergeWithPriorCheckpoint([deleted], [index]); // delete cell is an event that changes notebook version if (!this.notebook) this.createNotebookVersion(); // remove deleted cell from notebook index = this.notebook.cells.indexOf(deleted.name); if (index > -1) this.notebook.cells.splice(index, 1); // update checkpoint let cellDat = { cell: deleted.name, changeType: ChangeType.REMOVED, index, } as CellRunData; this.checkpoint.targetCells.push(cellDat); // record checkpoint if (!merged) this.history.checkpoints.add(this.checkpoint); } public moveCell(moved: NodeyCell, newPos: number) { // get position let name = moved.name; let oldNotebook = this.history.store.currentNotebook; let index = oldNotebook.cells.indexOf(name); // first see if this commit can be combined with a prior one const merged = this.attemptMergeWithPriorCheckpoint([moved], [index]); // moving a cell is an event that changes notebook version if (!this.notebook) this.createNotebookVersion(); // move cell in the notebook if (index > -1) this.notebook.cells.splice(index, 1); // delete the pointer this.notebook.cells.splice(newPos, 0, name); // re-add in correct place // update checkpoint let cellDat = { cell: name, changeType: ChangeType.MOVED, index: newPos, } as CellRunData; this.checkpoint.targetCells.push(cellDat); // record checkpoint if (!merged) this.history.checkpoints.add(this.checkpoint); } public changeCellType(oldCell: NodeyCell, newCell: NodeyCell) { // get position let name = oldCell.name; let oldNotebook = this.history.store.currentNotebook; let index = oldNotebook.cells.indexOf(name); // first see if this commit can be combined with a prior one const merged = this.attemptMergeWithPriorCheckpoint( [oldCell, newCell], [index] ); // changing a cell type is an event that changes notebook version if (!this.notebook) this.createNotebookVersion(); // make sure new cell's parent is this newNotebook newCell.parent = this.notebook.name; // now update cells of notebook let oldName = oldCell.name; let newName = newCell.name; let i = this.notebook.cells.indexOf(oldName); if (i > -1) this.notebook.cells.splice(i, 1, newName); // update checkpoint let cellDat = { cell: newCell.name, changeType: ChangeType.TYPE_CHANGED, } as CellRunData; this.checkpoint.targetCells.push(cellDat); // record checkpoint if (!merged) this.history.checkpoints.add(this.checkpoint); } // returns true if there are changes such that a new commit is recorded public async commit(options: jsn): Promise<void> { await this.stage.stage(options); if (this.stage.isEdited()) { const allStaged = this.stage.getAllStaged(); // get indices let oldNotebook = this.history.store.currentNotebook; let indices = allStaged.map((s) => { const name = s.name; return oldNotebook.cells.indexOf(name); }); // first see if this commit can be combined with a prior one const merged = this.attemptMergeWithPriorCheckpoint(allStaged, indices); // if there are real edits, make sure we have a new notebook if (!this.notebook) this.createNotebookVersion(); this.commitStaged(); // record checkpoint if (!merged) this.history.checkpoints.add(this.checkpoint); } } private commitStaged() { // now go through an update existing cells this.notebook.cells = this.notebook.cells.map((c) => { let cell = this.history.store.get(c); let instructions = cell ? this.stage.getStaging(cell) : null; if (instructions) { let newCell; if (cell instanceof NodeyCodeCell) newCell = this.createCodeCellVersion(cell.artifactName, instructions); else if (cell instanceof NodeyMarkdown) newCell = this.createMarkdownVersion(cell.artifactName, instructions); else if (cell instanceof NodeyRawCell) newCell = this.createRawCellVersion(cell.artifactName, instructions); return newCell?.name || c; // return unchanged cell if error occurred } else { // otherwise assume this cell is unchanged in this commit return c; } }); } private attemptMergeWithPriorCheckpoint( targetedCells: Nodey[], indicies: number[] ): boolean { /* * We will try to add new changes to an existing notebook version if * 1) no changes on this commit conflict with existing changes on this notebook * version. * 2) changes on this commit occur within 5 minutes of existing changes on this * notebook version. * * The goal of this merge is to compress the number of overall notebook versions so * that there is less sparse information to shift through, and more meaty versions. */ let pass = false; let oldNotebook = this.history.store.currentNotebook; let oldCheckpoints = this.history.checkpoints.getForNotebook(oldNotebook); if (oldCheckpoints.length > 0) { let latestCheckpoint = oldCheckpoints[oldCheckpoints.length - 1]; // check that the latest checkpoint is within 5 min of this one pass = checkTimeDiff(latestCheckpoint, this.checkpoint); // check that the older checkpoint does not affect the same cells as this one if (pass) { pass = false; let oldTargets = latestCheckpoint?.targetCells?.map((target) => this.history.store.get(target?.cell) ); if (oldTargets) { pass = checkArtfiactOverlap(targetedCells, oldTargets); } // check that the older checkpoint does not affect the same cell indices as this one if (pass && indicies) { pass = latestCheckpoint.targetCells.every((target) => { if (target.index) return indicies.indexOf(target.index) < 0; return true; }); } } // OK to merge if (pass) { this.notebook = oldNotebook; this.checkpoint = latestCheckpoint; } } return pass; } public createNotebookVersion() { let oldNotebook = this.history.store.currentNotebook; let newNotebook = new NodeyNotebook({ id: oldNotebook?.id, created: this.checkpoint.id, cells: oldNotebook?.cells.slice(0) || [], }); let notebookHist = this.history.store.getHistoryOf(oldNotebook); notebookHist?.addVersion(newNotebook); this.notebook = newNotebook; this.checkpoint.notebook = this.notebook?.version; } private createMarkdownVersion( artifactName: string, instructions: { markdown: string } ): NodeyMarkdown | undefined { // first create the new Markdown version let nodeyHistory = this.history.store.getHistoryOf(artifactName); let oldNodey = nodeyHistory?.latest; if (nodeyHistory && oldNodey) { let newNodey = new NodeyMarkdown({ id: oldNodey.id, created: this.checkpoint.id, markdown: instructions.markdown, parent: this.notebook.name, }); nodeyHistory.addVersion(newNodey); // then add the update to checkpoint let cellDat = { cell: newNodey.name, changeType: ChangeType.CHANGED, } as CellRunData; this.checkpoint.targetCells.push(cellDat); // finally return updated new version return newNodey; } console.error( "Failed to create new markdown version of ", artifactName, instructions ); } private createRawCellVersion( artifactName: string, instructions: { literal: string } ): NodeyRawCell | undefined { // first create the new Raw Cell version let nodeyHistory = this.history.store.getHistoryOf(artifactName); let oldNodey = nodeyHistory?.latest; if (nodeyHistory && oldNodey) { let newNodey = new NodeyRawCell({ id: oldNodey.id, created: this.checkpoint.id, literal: instructions.literal, parent: this.notebook.name, }); nodeyHistory?.addVersion(newNodey); // then add the update to checkpoint let cellDat = { cell: newNodey.name, changeType: ChangeType.CHANGED, } as CellRunData; this.checkpoint.targetCells.push(cellDat); // finally return updated new version return newNodey; } else console.error( "Failed to create new raw cell version of ", artifactName, instructions ); } private createCodeCellVersion( artifactName: string, instructions: { [key: string]: any } ): NodeyCodeCell | undefined { // build base code cell let nodeyHistory = this.history.store.getHistoryOf( artifactName ) as CodeHistory; let oldNodey = nodeyHistory?.latest; let newNodey; // error case only if (!nodeyHistory || !oldNodey) { console.error( "Failed to create new code cell version of ", artifactName, instructions ); return; } // check do we need a new cell version other than output? if (instructions["literal"] || instructions["content"]) { newNodey = new NodeyCodeCell({ id: oldNodey.id, created: this.checkpoint.id, literal: instructions["literal"], parent: this.notebook.name, }); nodeyHistory.addVersion(newNodey); } else newNodey = oldNodey; // now check if there is output to build let newOut: NodeyOutput; if (instructions["output"]) { // see if we already have an output history to add to let oldOutputHist = this.history.store.getOutput(newNodey); if (oldOutputHist) { let oldOut = oldOutputHist.latest; newOut = new NodeyOutput({ id: oldOut.id, created: this.checkpoint?.id, parent: newNodey.name, raw: instructions["output"], }); oldOutputHist.addVersion(newOut); } else { // if there is no output history, create a new one // but only if raw is not empty if (instructions["output"].length > 0) { newOut = new NodeyOutput({ created: this.checkpoint?.id, parent: newNodey.name, raw: instructions["output"], }); this.history.store.store(newOut); nodeyHistory.addOutput(newNodey.version, newOut); } } } let changed = oldNodey.version !== newNodey.version; let changeKind: ChangeType; if (changed) changeKind = ChangeType.CHANGED; if (!changed && newOut) changeKind = ChangeType.OUTPUT_CHANGED; // update the checkpoint if (changeKind) { let cellDat = { cell: newNodey.name, changeType: changeKind, output: newOut ? [newOut.name] : [], } as CellRunData; this.checkpoint.targetCells.push(cellDat); } // finally return updated new version return newNodey; } } // helper functions function checkTimeDiff(A: Checkpoint, B: Checkpoint): boolean { let minutes_elapsed = Math.abs(A.timestamp - B.timestamp) / 1000 / 60; return minutes_elapsed < 6; } function checkArtfiactOverlap(targets_A, targets_B): boolean { let B = targets_B?.map((target) => target.artifactName); if (B) { return targets_A.every((nodey) => { let artifactName = nodey.artifactName; return B.indexOf(artifactName) < 0; }); } return false; }
the_stack
import {Actions} from '../common/actions'; import {Engine} from '../common/engine'; import { AggregationAttrs, AVAILABLE_AGGREGATIONS, AVAILABLE_TABLES, getDescendantsTables, getParentStackColumn, getStackColumn, getStackDepthColumn, PivotAttrs, PivotTableQueryResponse, removeHiddenAndAddStackColumns, RowAttrs, WHERE_FILTERS } from '../common/pivot_table_common'; import { getAggregationAlias, getAggregationOverStackAlias, getAliasedPivotColumns, getHiddenPivotAlias, getPivotAlias, getTotalAggregationAlias, PivotTableQueryGenerator } from '../common/pivot_table_query_generator'; import { QueryResponse, runQuery, } from '../common/queries'; import {Row} from '../common/query_result'; import {toNs} from '../common/time'; import {PivotTableHelper} from '../frontend/pivot_table_helper'; import {publishPivotTableHelper, publishQueryResult} from '../frontend/publish'; import {Controller} from './controller'; import {globals} from './globals'; export interface PivotTableControllerArgs { pivotTableId: string; engine: Engine; } function getExpandableColumn( pivotTableId: string, queriedPivots: PivotAttrs[]): string|undefined { if (queriedPivots.length === 0) { return undefined; } const selectedPivots = globals.state.pivotTable[pivotTableId].selectedPivots; const lastPivot = getPivotAlias(selectedPivots[selectedPivots.length - 1]); const lastQueriedPivot = getPivotAlias(queriedPivots[queriedPivots.length - 1]); if (lastQueriedPivot !== lastPivot) { return lastQueriedPivot; } return undefined; } function getRowWhereFilters( queriedPivots: PivotAttrs[], row: Row, parentRow?: RowAttrs) { let whereFilters = new Map(); // Add all the row's parent whereFilers. if (parentRow) { whereFilters = new Map(parentRow.whereFilters); } // Add whereFilters for all the queried pivots and any hidden pivots without // the stack pivots. getAliasedPivotColumns(queriedPivots) .filter(pivot => !pivot.pivotAttrs.isStackPivot) .forEach( pivot => whereFilters.set( pivot.columnAlias, `CAST(${pivot.pivotAttrs.tableName}.${ pivot.pivotAttrs.columnName} AS TEXT) = '${ row[pivot.columnAlias]!.toString()}'`)); return whereFilters; } function getPivotTableQueryResponseRows( pivotTableId: string, rows: Row[], queriedPivots: PivotAttrs[], parentRow?: RowAttrs) { const expandableColumns = new Set<string>(); if (queriedPivots.length > 0 && queriedPivots[0].isStackPivot) { // Make the stack column expandable. expandableColumns.add(getPivotAlias(queriedPivots[0])); } // Add expandable column after the stack column if it exists. const expandableColumn = getExpandableColumn(pivotTableId, queriedPivots); if (expandableColumn !== undefined) { expandableColumns.add(expandableColumn); } const newRows: RowAttrs[] = []; for (const row of rows) { newRows.push({ row, expandableColumns, depth: 0, whereFilters: getRowWhereFilters(queriedPivots, row, parentRow), expandedRows: new Map() }); } return newRows; } function getPivotTableQueryResponse( pivotTableId: string, queryResp: QueryResponse, queriedPivots: PivotAttrs[], parentRow?: RowAttrs): PivotTableQueryResponse { const columns = []; const pivotTable = globals.state.pivotTable[pivotTableId]; for (let i = 0; i < pivotTable.selectedPivots.length; ++i) { const pivot = pivotTable.selectedPivots[i]; columns.push({ name: getPivotAlias(pivot), index: i, tableName: pivot.tableName, columnName: pivot.columnName, isStackColumn: pivot.isStackPivot }); } for (let i = 0; i < pivotTable.selectedAggregations.length; ++i) { const aggregation = pivotTable.selectedAggregations[i]; columns.push({ name: getAggregationAlias(aggregation), index: i, tableName: aggregation.tableName, columnName: aggregation.columnName, aggregation: aggregation.aggregation, order: aggregation.order, isStackColumn: false }); } return { columns, rows: getPivotTableQueryResponseRows( pivotTableId, queryResp.rows, queriedPivots, parentRow), error: queryResp.error, durationMs: queryResp.durationMs }; } function getRowInPivotTableQueryResponse( queryResp: PivotTableQueryResponse, rowIndices: number[], expandedRowColumns: string[]) { if (rowIndices.length === 0) { throw new Error('Row indicies should have at least one index.'); } let row = queryResp.rows[rowIndices[0]]; // expandedRowColumns and rowIndices should refer to the same rows minus the // initial row index that specifies the row in the query response. if (rowIndices.length !== expandedRowColumns.length + 1) { throw Error(`expandedRowColumns length "${ expandedRowColumns.length}" should be less than rowIndicies length "${ rowIndices.length}" by one.`); } for (let i = 1; i < rowIndices.length; ++i) { const expandedRow = row.expandedRows.get(expandedRowColumns[i - 1]); if (expandedRow === undefined || expandedRow.rows.length <= rowIndices[i]) { throw new Error(`Expanded row index "${rowIndices[i]}" at row column "${ expandedRowColumns[i - 1]}" is out of bounds.`); } row = expandedRow.rows[rowIndices[i]]; } return row; } function getDescendantRows( pivotTableId: string, respRows: Row[], parentRow: RowAttrs, queriedPivots: PivotAttrs[], queriedAggregations: AggregationAttrs[]) { const stackPivot = queriedPivots[0]; if (stackPivot === undefined || !stackPivot.isStackPivot) { throw Error('Queried pivot is not a stack pivot'); } const stackIdColumn = getHiddenPivotAlias(getStackColumn(stackPivot)); const parentStackIdColumn = getHiddenPivotAlias(getParentStackColumn(stackPivot)); const depthColumn = getHiddenPivotAlias(getStackDepthColumn(stackPivot)); const stackColumn = getPivotAlias(stackPivot); // "name (stack)" column. const parentDepth = Number(parentRow.row[depthColumn]?.toString()); if (!Number.isInteger(parentDepth)) { throw Error('Parent row has undefined depth.'); } const parentRowStackId = parentRow.row[stackIdColumn]?.toString(); if (parentRowStackId === undefined) { throw Error('Parent row has undefined stack_id.'); } const nextPivot = queriedPivots[1]; let nextColumnName = ''; if (nextPivot !== undefined) { nextColumnName = getPivotAlias(nextPivot); } const newRows: Map<string, RowAttrs> = new Map(); for (const row of respRows) { const depth = Number(row[depthColumn]?.toString()); const stackId = row[stackIdColumn]?.toString(); const parentStackId = row[parentStackIdColumn]?.toString(); if (!Number.isInteger(depth)) { throw Error('Descendant result has undefined depth.'); } if (!stackId || !parentStackId) { throw Error('Descendant result has undefined stack or parent stack id.'); } const expandableColumns = new Set<string>(); // Get expandable column after the stack column if it exists. const expandableColumn = getExpandableColumn(pivotTableId, queriedPivots); if (expandableColumn !== undefined) { expandableColumns.add(expandableColumn); } const newRow: RowAttrs = { row: Object.assign({}, row), depth: depth - parentDepth, whereFilters: getRowWhereFilters(queriedPivots, row, parentRow), expandedRows: new Map(), expandableColumns }; // If we have already added the stackId, we need to extract and nest its // next column values in its expanded rows. if (newRows.has(stackId)) { newRow.row[stackColumn] = null; const parent = newRows.get(stackId)!; let nextColumnRows = parent.expandedRows.get(nextColumnName); if (nextColumnRows === undefined) { // Since the parent row has more than one value for the next column, // we nest the values in rows under the parent row instead of inline // with it. // Making a new row to hold the next column value. const row = Object.assign({}, parent.row); const nextColumnRow: RowAttrs = { row: Object.assign({}, row), depth: depth - parentDepth, whereFilters: getRowWhereFilters(queriedPivots, row, parentRow), expandedRows: new Map(), expandableColumns }; parent.row[nextColumnName] = null; // Modify the parent row to show the aggregation over stack rows instead // of the partitioned aggregations. for (const aggregation of queriedAggregations) { parent.row[getAggregationAlias(aggregation)] = parent.row[getAggregationOverStackAlias(aggregation)]; } nextColumnRow.row[stackColumn] = null; if (nextColumnRow.row[nextColumnName] !== undefined) { parent.expandedRows.set( nextColumnName, {isExpanded: true, rows: [nextColumnRow]}); } nextColumnRows = parent.expandedRows.get(nextColumnName); } newRow.expandableColumns = expandableColumns; nextColumnRows!.rows.push(newRow); } // If we have already added the parentStackId, we need to nest the row // in its parent's expanded rows. // This works because we sort the result of the descendants query by // depth, insuring that if the stack_id has a parent other than the // parent row, its parent will show up first. if (newRows.has(parentStackId)) { const parent = newRows.get(parentStackId)!; let descendants = parent.expandedRows.get(stackColumn); if (descendants === undefined) { parent.expandedRows.set(stackColumn, {isExpanded: true, rows: []}); descendants = parent.expandedRows.get(stackColumn); } descendants!.rows.push(newRow); parent.expandableColumns.add(stackColumn); // Unexpand if parent has more than one child. if (descendants!.rows.length > 1) { descendants!.isExpanded = false; if (parent.expandedRows.has(nextColumnName)) { parent.expandedRows.get(nextColumnName)!.isExpanded = false; } } } if (!newRows.has(stackId)) { newRows.set(stackId, newRow); } } // Get only direct descendants of the parent row. The rest is nested inside // the descendants. const descendantRows = Array.from(newRows.values()) .filter( row => row.row[parentStackIdColumn]?.toString() === parentRowStackId); // Get the next column values of the parent row. let nextColumnRows; if (newRows.has(parentRowStackId)) { if (newRows.get(parentRowStackId)!.expandedRows.has(nextColumnName)) { nextColumnRows = newRows.get(parentRowStackId)!.expandedRows.get(nextColumnName)!.rows; } else { // If the next column value is inline with the parent row. nextColumnRows = [newRows.get(parentRowStackId)!]; } } return {descendantRows, nextColumnRows}; } function getPivotColumns( pivotTableId: string, columnIdx: number, isStackQuery: boolean) { const selectedPivots = globals.state.pivotTable[pivotTableId].selectedPivots; // Slice returns the pivot at columnIdx if it exists, and an empty // array if columnIdx is out of bounds. const pivots = selectedPivots.slice(columnIdx, columnIdx + 1); if (isStackQuery) { // Adds the next pivot, if it exists, to be queried with the stack query. pivots.push(...selectedPivots.slice(columnIdx + 1, columnIdx + 2)); } return pivots; } function getWhereFilters( pivotTableId: string, parentRowWhereFilters: Map<string, string>, pivots: PivotAttrs[], isStackQuery: boolean) { const whereFiltersMap = new Map(parentRowWhereFilters); // Remove any existing where filters for the pivots to query. getAliasedPivotColumns(pivots).forEach( pivotAlias => whereFiltersMap.delete(pivotAlias.columnAlias)); const whereFilters = Array.from(whereFiltersMap.values()); if (pivots.length > 0 && pivots[0].isStackPivot && !isStackQuery) { // Only query top level slices, descendants can be generated // when expanded. const orderColumn = getStackDepthColumn(pivots[0]); whereFilters.push(`${orderColumn.tableName}.${orderColumn.columnName} = 0`); } // Add global where filters whereFilters.push(...WHERE_FILTERS); // Add area restrictions where filters if set. const pivotTable = globals.state.pivotTable[pivotTableId]; if (pivotTable.selectedTrackIds) { whereFilters.push(`slice.track_id IN (${pivotTable.selectedTrackIds})`); } if (pivotTable.traceTime) { whereFilters.push( `slice.ts + slice.dur > ${toNs(pivotTable.traceTime.startSec)}`); whereFilters.push(`slice.ts < ${toNs(pivotTable.traceTime.endSec)}`); } return whereFilters; } export class PivotTableController extends Controller<'main'> { private pivotTableId: string; private pivotTableQueryGenerator = new PivotTableQueryGenerator(); private engine: Engine; private queryResp?: PivotTableQueryResponse; constructor(args: PivotTableControllerArgs) { super('main'); this.engine = args.engine; this.pivotTableId = args.pivotTableId; this.setup().then(() => { this.run(); }); } run() { const {requestedAction} = globals.state.pivotTable[this.pivotTableId]; const pivotTable = globals.state.pivotTable[this.pivotTableId]; if (!requestedAction) return; globals.dispatch( Actions.resetPivotTableRequest({pivotTableId: this.pivotTableId})); switch (requestedAction.action) { case 'DESCENDANTS': const descendantsAttrs = requestedAction.attrs; if (descendantsAttrs === undefined) { throw Error('No attributes provided for descendants query.'); } if (this.queryResp === undefined) { throw Error( 'Descendants query requested without setting the main query.'); } const stackPivot = pivotTable.selectedPivots[descendantsAttrs.columnIdx]; const stackColumnName = getPivotAlias(stackPivot); const nextPivot = pivotTable.selectedPivots[descendantsAttrs.columnIdx + 1]; let nextColumnName = ''; if (nextPivot !== undefined) { nextColumnName = getPivotAlias(nextPivot); } const ancestorRow = getRowInPivotTableQueryResponse( this.queryResp, descendantsAttrs.rowIndices, descendantsAttrs.expandedRowColumns); // No need to query if the row has been expanded before. if (ancestorRow.expandedRows.has(stackColumnName)) { ancestorRow.expandedRows.get(stackColumnName)!.isExpanded = true; if (ancestorRow.expandedRows.has(nextColumnName) && !ancestorRow.expandableColumns.has(nextColumnName)) { ancestorRow.expandedRows.get(nextColumnName)!.isExpanded = true; } break; } const descendantsPivots = getPivotColumns( this.pivotTableId, descendantsAttrs.columnIdx, /* is_stack_query = */ true); if (descendantsPivots.length === 0) { throw Error( `Descendant operation at column index "${ descendantsAttrs .columnIdx}" should only be allowed if there are` + `are more columns to query.`); } const descendantsWhereFilters = getWhereFilters( this.pivotTableId, ancestorRow.whereFilters, descendantsPivots, /* is_stack_query = */ true); const stackIdColumn = getHiddenPivotAlias(getStackColumn(stackPivot)); const stackId = ancestorRow.row[stackIdColumn]?.toString(); if (stackId === undefined) { throw Error(`"${ getPivotAlias( stackPivot)}" row has undefined stack id at column "${ stackIdColumn}".`); } const descendantsTables = getDescendantsTables(descendantsPivots, stackId); // Query the descendants and the next column if it exists. const descendantsQuery = this.pivotTableQueryGenerator.generateStackQuery( descendantsPivots, pivotTable.selectedAggregations, descendantsWhereFilters, descendantsTables, stackId); ancestorRow.loadingColumn = stackColumnName; runQuery(this.pivotTableId, descendantsQuery, this.engine) .then(resp => { // Query resulting from query generator should always be valid. if (resp.error) { throw Error(`Pivot table descendants query ${ descendantsQuery} resulted in SQL error: ${resp.error}`); } const printDescendantsQuery = descendantsQuery.length <= 1024 ? descendantsQuery : ''; console.log(`Descendants query${printDescendantsQuery} took ${ resp.durationMs} ms`); const {descendantRows, nextColumnRows} = getDescendantRows( this.pivotTableId, resp.rows, ancestorRow, descendantsPivots, pivotTable.selectedAggregations); // Set descendant rows. ancestorRow.expandedRows.set( stackColumnName, {isExpanded: true, rows: descendantRows}); // Set the next pivot row(s), if they exist, inside the parent // row. if (nextColumnRows !== undefined) { if (nextColumnRows.length <= 1) { // If there is only one value for the next column of the // parent row, add it to the same row as the parent. ancestorRow.row = nextColumnRows[0].row; ancestorRow.expandableColumns = new Set([ ...nextColumnRows[0].expandableColumns, ...ancestorRow.expandableColumns ]); } else { ancestorRow.expandedRows.set( nextColumnName, {isExpanded: true, rows: nextColumnRows}); } } ancestorRow.loadingColumn = undefined; this.queryResp!.durationMs += resp.durationMs; }); break; case 'EXPAND': const expandAttrs = requestedAction.attrs; if (expandAttrs === undefined) { throw Error('No attributes provided for expand query.'); } if (this.queryResp === undefined) { throw Error('Expand query requested without setting the main query.'); } const expandColumnName = getPivotAlias(pivotTable.selectedPivots[expandAttrs.columnIdx]); const expandRow = getRowInPivotTableQueryResponse( this.queryResp, expandAttrs.rowIndices, expandAttrs.expandedRowColumns); // No need to query if the row has been expanded before. if (expandRow.expandedRows.has(expandColumnName)) { expandRow.expandedRows.get(expandColumnName)!.isExpanded = true; break; } const expandPivots = getPivotColumns( this.pivotTableId, expandAttrs.columnIdx + 1, /* is_stack_query = */ false); if (expandPivots.length === 0) { throw Error( `Expand operation at column index "${ expandAttrs.columnIdx}" should only be allowed if there are` + `are more columns to query.`); } const expandWhereFilters = getWhereFilters( this.pivotTableId, expandRow.whereFilters, expandPivots, /* is_stack_query = */ false); const expandQuery = this.pivotTableQueryGenerator.generateQuery( expandPivots, pivotTable.selectedAggregations, expandWhereFilters, AVAILABLE_TABLES); expandRow.loadingColumn = getPivotAlias(pivotTable.selectedPivots[expandAttrs.columnIdx]); runQuery(this.pivotTableId, expandQuery, this.engine).then(resp => { // Query resulting from query generator should always be valid. if (resp.error) { throw Error(`Pivot table expand query ${ expandQuery} resulted in SQL error: ${resp.error}`); } const printExpandQuery = expandQuery.length <= 1024 ? expandQuery : ''; console.log( `Expand query${printExpandQuery} took ${resp.durationMs} ms`); expandRow.expandedRows.set(expandColumnName, { isExpanded: true, rows: getPivotTableQueryResponseRows( this.pivotTableId, resp.rows, expandPivots, expandRow) }); expandRow.loadingColumn = undefined; this.queryResp!.durationMs += resp.durationMs; }); break; case 'UNEXPAND': const unexpandAttrs = requestedAction.attrs; if (unexpandAttrs === undefined) { throw Error('No attributes provided for unexpand query.'); } if (this.queryResp === undefined) { throw Error( 'Unexpand query requested without setting the main query.'); } const unexpandPivot = pivotTable.selectedPivots[unexpandAttrs.columnIdx]; const unexpandColumnName = getPivotAlias(unexpandPivot); const unexpandRow = getRowInPivotTableQueryResponse( this.queryResp, unexpandAttrs.rowIndices, unexpandAttrs.expandedRowColumns); if (unexpandRow.expandedRows.has(unexpandColumnName)) { unexpandRow.expandedRows.get(unexpandColumnName)!.isExpanded = false; const nextPivot = pivotTable.selectedPivots[unexpandAttrs.columnIdx + 1]; let nextColumnName = ''; if (nextPivot !== undefined) { nextColumnName = getPivotAlias(nextPivot); } // Unexpand the next column rows if they are nested inside the // parent expanded row, but no expandable column exists for the // next column. if (unexpandPivot.isStackPivot && unexpandRow.expandedRows.has(nextColumnName) && !unexpandRow.expandableColumns.has(nextColumnName)) { unexpandRow.expandedRows.get(nextColumnName)!.isExpanded = false; } } else { throw Error('Unexpand request called on already undexpanded row.'); } break; case 'QUERY': // Generates and executes new query based on selectedPivots and // selectedAggregations. const pivots = getPivotColumns( this.pivotTableId, /* column_idx = */ 0, /* is_stack_query = */ false); const whereFilers = getWhereFilters( this.pivotTableId, /*parent_row_where_Filters = */ new Map(), pivots, /* is_stack_query = */ false); const query = this.pivotTableQueryGenerator.generateQuery( pivots, pivotTable.selectedAggregations, whereFilers, AVAILABLE_TABLES); if (query !== '') { globals.dispatch( Actions.toggleQueryLoading({pivotTableId: this.pivotTableId})); runQuery(this.pivotTableId, query, this.engine).then(resp => { // Query resulting from query generator should always be valid. if (resp.error) { throw Error(`Pivot table query ${query} resulted in SQL error: ${ resp.error}`); } const printQuery = query.length <= 1024 ? query : ''; console.log(`Query${printQuery} took ${resp.durationMs} ms`); const data = getPivotTableQueryResponse(this.pivotTableId, resp, pivots); if (pivotTable.selectedAggregations.length > 0 && resp.rows.length > 0) { const totalAggregationsRow = Object.assign({}, resp.rows[0]); // Modify the total aggregations row to show the total // aggregations. if (pivotTable.selectedPivots.length > 0) { for (const aggregation of pivotTable.selectedAggregations) { totalAggregationsRow[getAggregationAlias(aggregation)] = totalAggregationsRow[getTotalAggregationAlias( aggregation)]; } } data.totalAggregations = totalAggregationsRow; } publishQueryResult({id: this.pivotTableId, data}); this.queryResp = data; globals.dispatch( Actions.toggleQueryLoading({pivotTableId: this.pivotTableId})); }); } else { publishQueryResult({id: this.pivotTableId, data: undefined}); } break; default: throw new Error(`Unexpected requested action ${requestedAction}`); } } private async setup(): Promise<void> { const pivotTable = globals.state.pivotTable[this.pivotTableId]; const selectedPivots = pivotTable.selectedPivots; const selectedAggregations = pivotTable.selectedAggregations; let availableColumns = globals.state.pivotTableConfig.availableColumns; // No need to retrieve table columns if they are already stored. // Only needed when first pivot table is created. if (availableColumns === undefined) { availableColumns = []; for (const table of AVAILABLE_TABLES) { const columns = await this.getColumnsForTable(table); if (columns.length > 0) { availableColumns.push({tableName: table, columns}); } } globals.dispatch(Actions.setAvailablePivotTableColumns( {availableColumns, availableAggregations: AVAILABLE_AGGREGATIONS})); } publishPivotTableHelper({ id: this.pivotTableId, data: new PivotTableHelper( this.pivotTableId, availableColumns, AVAILABLE_AGGREGATIONS, selectedPivots, selectedAggregations) }); } private async getColumnsForTable(tableName: string): Promise<string[]> { const query = `select * from ${tableName} limit 0;`; const resp = await runQuery(this.pivotTableId, query, this.engine); return removeHiddenAndAddStackColumns(tableName, resp.columns); } }
the_stack
import { CamelCaseNamingConvention, PascalCaseNamingConvention, SnakeCaseNamingConvention, } from '@automapper/core'; import { setupPojos } from '../setup.spec'; import { createSimpleFooBarPascalMetadata, PascalSimpleBar, PascalSimpleBarVm, PascalSimpleFoo, PascalSimpleFooVm, } from './fixtures/interfaces/simple-foo-bar-pascal.interface'; import { createSimpleFooBarSnakeMetadata, SnakeSimpleBar, SnakeSimpleBarVm, SnakeSimpleFoo, SnakeSimpleFooVm, } from './fixtures/interfaces/simple-foo-bar-snake.interface'; import { createSimpleFooBarMetadata, SimpleBar, SimpleBarVm, SimpleFoo, SimpleFooVm, } from './fixtures/interfaces/simple-foo-bar.interface'; import { PascalUser, PascalUserVm, } from './fixtures/interfaces/user-pascal.interface'; import { SnakeUser, SnakeUserVm, } from './fixtures/interfaces/user-snake.interface'; import { User, UserVm } from './fixtures/interfaces/user.interface'; import { addressProfile, pascalAddressProfile, snakeAddressProfile, } from './fixtures/profiles/address.profile'; import { avatarProfile, pascalAvatarProfile, snakeAvatarProfile, } from './fixtures/profiles/avatar.profile'; import { pascalUserProfileProfile, snakeUserProfileProfile, userProfileProfile, } from './fixtures/profiles/user-profile.profile'; import { pascalUserProfile, snakeUserProfile, userProfile, } from './fixtures/profiles/user.profile'; import { getPascalUser, getSnakeUser, getUser } from './utils/get-user'; describe('Naming Conventions', () => { describe('with pascal <-> camel', () => { const [mapper] = setupPojos('pascalCamel', { source: new PascalCaseNamingConvention(), destination: new CamelCaseNamingConvention(), }); it('should create mapper', () => { expect(mapper).toBeTruthy(); }); it('should map', () => { createSimpleFooBarMetadata(); createSimpleFooBarPascalMetadata(); createSimpleFooBarSnakeMetadata(); mapper.createMap<PascalSimpleBar, SimpleBarVm>( 'PascalSimpleBar', 'SimpleBarVm' ); mapper.createMap<PascalSimpleFoo, SimpleFooVm>( 'PascalSimpleFoo', 'SimpleFooVm' ); const foo = { Foo: 'Foo', FooBar: 123, Bar: { Bar: 'Bar', }, } as PascalSimpleFoo; const vm = mapper.map<PascalSimpleFoo, SimpleFooVm>( foo, 'SimpleFooVm', 'PascalSimpleFoo' ); expect(vm.foo).toEqual(foo.Foo); expect(vm.bar.bar).toEqual(foo.Bar.Bar); expect(vm.fooBar).toEqual(foo.FooBar); }); it('should map with complex models', () => { mapper .addProfile(pascalAddressProfile) .addProfile(pascalAvatarProfile) .addProfile(pascalUserProfileProfile) .addProfile(pascalUserProfile); const user = getPascalUser(); const vm = mapper.map<PascalUser, UserVm>(user, 'UserVm', 'PascalUser'); expect(vm).toBeTruthy(); // Asserting the whole VM is too repetitive expect(vm.jobTitle).toEqual(user.Job.Title); expect(vm.jobAnnualSalary).toEqual(user.Job.AnnualSalary); }); }); describe('with camel <-> pascal', () => { const [mapper] = setupPojos('camelPascal', { source: new CamelCaseNamingConvention(), destination: new PascalCaseNamingConvention(), }); it('should create mapper', () => { expect(mapper).toBeTruthy(); }); it('should map', () => { createSimpleFooBarMetadata(); createSimpleFooBarPascalMetadata(); createSimpleFooBarSnakeMetadata(); mapper.createMap<SimpleBar, PascalSimpleBarVm>( 'SimpleBar', 'PascalSimpleBarVm' ); mapper.createMap<SimpleFoo, PascalSimpleFooVm>( 'SimpleFoo', 'PascalSimpleFooVm' ); const foo = { foo: 'Foo', fooBar: 123, bar: { bar: 'Bar', }, } as SimpleFoo; const vm = mapper.map<SimpleFoo, PascalSimpleFooVm>( foo, 'PascalSimpleFooVm', 'SimpleFoo' ); expect(vm.Foo).toEqual(foo.foo); expect(vm.Bar.Bar).toEqual(foo.bar.bar); expect(vm.FooBar).toEqual(foo.fooBar); }); it('should map with complex models', () => { mapper .addProfile(addressProfile) .addProfile(avatarProfile) .addProfile(userProfileProfile) .addProfile(userProfile); const user = getUser(); const vm = mapper.map<User, PascalUserVm>(user, 'PascalUserVm', 'User'); expect(vm).toBeTruthy(); // Asserting the whole VM is too repetitive expect(vm.JobTitle).toEqual(user.job.title); expect(vm.JobAnnualSalary).toEqual(user.job.annualSalary); }); }); describe('with snake <-> camel', () => { const [mapper] = setupPojos('snakeCamel', { source: new SnakeCaseNamingConvention(), destination: new CamelCaseNamingConvention(), }); it('should create mapper', () => { expect(mapper).toBeTruthy(); }); it('should map', () => { createSimpleFooBarMetadata(); createSimpleFooBarPascalMetadata(); createSimpleFooBarSnakeMetadata(); mapper.createMap<SnakeSimpleBar, SimpleBarVm>( 'SnakeSimpleBar', 'SimpleBarVm' ); mapper.createMap<SnakeSimpleFoo, SimpleFooVm>( 'SnakeSimpleFoo', 'SimpleFooVm' ); const foo = { foo: 'Foo', foo_bar: 123, bar: { bar: 'Bar', }, } as SnakeSimpleFoo; const vm = mapper.map<SnakeSimpleFoo, SimpleFooVm>( foo, 'SimpleFooVm', 'SnakeSimpleFoo' ); expect(vm.foo).toEqual(foo.foo); expect(vm.bar.bar).toEqual(foo.bar.bar); expect(vm.fooBar).toEqual(foo.foo_bar); }); it('should map with complex models', () => { mapper .addProfile(snakeAddressProfile) .addProfile(snakeAvatarProfile) .addProfile(snakeUserProfileProfile) .addProfile(snakeUserProfile); const user = getSnakeUser(); const vm = mapper.map<SnakeUser, UserVm>(user, 'UserVm', 'SnakeUser'); expect(vm).toBeTruthy(); // Asserting the whole VM is too repetitive expect(vm.jobTitle).toEqual(user.job.title); expect(vm.jobAnnualSalary).toEqual(user.job.annual_salary); }); }); describe('with camel <-> snake', () => { const [mapper] = setupPojos('camelSnake', { source: new CamelCaseNamingConvention(), destination: new SnakeCaseNamingConvention(), }); it('should create mapper', () => { expect(mapper).toBeTruthy(); }); it('should map', () => { createSimpleFooBarMetadata(); createSimpleFooBarPascalMetadata(); createSimpleFooBarSnakeMetadata(); mapper.createMap<SimpleBar, SnakeSimpleBarVm>( 'SimpleBar', 'SnakeSimpleBarVm' ); mapper.createMap<SimpleFoo, SnakeSimpleFooVm>( 'SimpleFoo', 'SnakeSimpleFooVm' ); const foo = { foo: 'Foo', fooBar: 123, bar: { bar: 'Bar', }, } as SimpleFoo; const vm = mapper.map<SimpleFoo, SnakeSimpleFooVm>( foo, 'SnakeSimpleFooVm', 'SimpleFoo' ); expect(vm.foo).toEqual(foo.foo); expect(vm.bar.bar).toEqual(foo.bar.bar); expect(vm.foo_bar).toEqual(foo.fooBar); }); it('should map with complex models', () => { mapper .addProfile(addressProfile) .addProfile(avatarProfile) .addProfile(userProfileProfile) .addProfile(userProfile); const user = getUser(); const vm = mapper.map<User, SnakeUserVm>(user, 'SnakeUserVm', 'User'); expect(vm).toBeTruthy(); // Asserting the whole VM is too repetitive expect(vm.job_title).toEqual(user.job.title); expect(vm.job_annual_salary).toEqual(user.job.annualSalary); }); }); describe('with pascal <-> snake', () => { const [mapper] = setupPojos('pascalSnake', { source: new PascalCaseNamingConvention(), destination: new SnakeCaseNamingConvention(), }); it('should create mapper', () => { expect(mapper).toBeTruthy(); }); it('should map', () => { createSimpleFooBarMetadata(); createSimpleFooBarPascalMetadata(); createSimpleFooBarSnakeMetadata(); mapper.createMap<PascalSimpleBar, SnakeSimpleBarVm>( 'PascalSimpleBar', 'SnakeSimpleBarVm' ); mapper.createMap<PascalSimpleFoo, SnakeSimpleFooVm>( 'PascalSimpleFoo', 'SnakeSimpleFooVm' ); const foo = { Foo: 'Foo', FooBar: 123, Bar: { Bar: 'Bar', }, } as PascalSimpleFoo; const vm = mapper.map<PascalSimpleFoo, SnakeSimpleFooVm>( foo, 'SnakeSimpleFooVm', 'PascalSimpleFoo' ); expect(vm.foo).toEqual(foo.Foo); expect(vm.bar.bar).toEqual(foo.Bar.Bar); expect(vm.foo_bar).toEqual(foo.FooBar); }); it('should map with complex models', () => { mapper .addProfile(pascalAddressProfile) .addProfile(pascalAvatarProfile) .addProfile(pascalUserProfileProfile) .addProfile(pascalUserProfile); const user = getPascalUser(); const vm = mapper.map<PascalUser, SnakeUserVm>( user, 'SnakeUserVm', 'PascalUser' ); expect(vm).toBeTruthy(); // Asserting the whole VM is too repetitive expect(vm.job_title).toEqual(user.Job.Title); expect(vm.job_annual_salary).toEqual(user.Job.AnnualSalary); }); }); describe('with snake <-> pascal', () => { const [mapper] = setupPojos('snakePascal', { source: new SnakeCaseNamingConvention(), destination: new PascalCaseNamingConvention(), }); it('should create mapper', () => { expect(mapper).toBeTruthy(); }); it('should map', () => { createSimpleFooBarMetadata(); createSimpleFooBarPascalMetadata(); createSimpleFooBarSnakeMetadata(); mapper.createMap<SnakeSimpleBar, PascalSimpleBarVm>( 'SnakeSimpleBar', 'PascalSimpleBarVm' ); mapper.createMap<SnakeSimpleFoo, PascalSimpleFooVm>( 'SnakeSimpleFoo', 'PascalSimpleFooVm' ); const foo = { foo: 'Foo', foo_bar: 123, bar: { bar: 'Bar', }, } as SnakeSimpleFoo; const vm = mapper.map<SnakeSimpleFoo, PascalSimpleFooVm>( foo, 'PascalSimpleFooVm', 'SnakeSimpleFoo' ); expect(vm.Foo).toEqual(foo.foo); expect(vm.Bar.Bar).toEqual(foo.bar.bar); expect(vm.FooBar).toEqual(foo.foo_bar); }); it('should map with complex models', () => { mapper .addProfile(snakeAddressProfile) .addProfile(snakeAvatarProfile) .addProfile(snakeUserProfileProfile) .addProfile(snakeUserProfile); const user = getSnakeUser(); const vm = mapper.map<SnakeUser, PascalUserVm>( user, 'PascalUserVm', 'SnakeUser' ); expect(vm).toBeTruthy(); // Asserting the whole VM is too repetitive expect(vm.JobTitle).toEqual(user.job.title); expect(vm.JobAnnualSalary).toEqual(user.job.annual_salary); }); }); });
the_stack
'use strict'; import { createBuildings, Building } from './createBuilding'; import { Mesh } from './Mesh'; import { createFeatureMetadataExtension } from './createFeatureMetadataExtension'; var Cesium = require('cesium'); var createB3dm = require('./createB3dm'); var path = require('path'); var createGltf = require('./createGltf'); var gltfPipeline = require('gltf-pipeline'); var processGltf = gltfPipeline.processGltf; var gltfToGlb = gltfPipeline.gltfToGlb; var gltfConversionOptions = { resourceDirectory: path.join(__dirname, '../') }; var Cartesian3 = Cesium.Cartesian3; var combine = Cesium.combine; var defaultValue = Cesium.defaultValue; var defined = Cesium.defined; var Matrix4 = Cesium.Matrix4; var sizeOfUint8 = 1; var sizeOfFloat = 4; var sizeOfDouble = 8; var scratchMatrix = new Matrix4(); var batchTableJsonAndBinary; /** * Creates a b3dm tile that represents a set of buildings. * * @param {Object} options Object with the following properties: * @param {Object} options.buildingOptions Options used to create the buildings. * @param {Boolean} [options.useBatchIds=true] Modify the glTF to include the batchId vertex attribute. * @param {Boolean} [options.createBatchTable=true] Create a batch table for the b3dm tile. * @param {Boolean} [options.createBatchTableExtra=false] Add additional test properties to the batch table. * @param {Boolean} [options.createBatchTableBinary=false] Create a batch table binary for the b3dm tile. * @param {Matrix4} [options.transform=Matrix4.IDENTITY] A transform to bake into the tile, for example a transform into WGS84. * @param {Boolean} [options.relativeToCenter=false] Set mesh positions relative to center. * @param {Number[]} [options.rtcCenterPosition] If defined, sets RTC_CENTER attribute in the feature table. * @param {Boolean} [options.useVertexColors=false] Bake materials as vertex colors. * @param {Boolean} [options.animated=false] Whether to include glTF animations. * @param {Boolean} [options.deprecated1=false] Save the b3dm with the deprecated 20-byte header and the glTF with the BATCHID semantic. * @param {Boolean} [options.deprecated2=false] Save the b3dm with the deprecated 24-byte header and the glTF with the BATCHID semantic. * * @returns {Promise} A promise that resolves with the b3dm buffer and batch table JSON. * OR a promise that resolves with a glTF */ export function createBuildingsTile(options) { var buildings = createBuildings(options.buildingOptions); var useBatchIds = defaultValue(options.useBatchIds, true); var createBatchTable = defaultValue(options.createBatchTable, true) && useBatchIds; var createBatchTableExtra = defaultValue(options.createBatchTableExtra, false) && useBatchIds; var createBatchTableBinary = defaultValue(options.createBatchTableBinary, false) && useBatchIds; var tileTransform = defaultValue(options.transform, Matrix4.IDENTITY); var use3dTilesNext = defaultValue(options.use3dTilesNext, false); var useGlb = defaultValue(options.useGlb, false); var animated = defaultValue(options.animated, false); var relativeToCenter = options.relativeToCenter; var rtcCenterPosition = options.rtcCenterPosition; var useVertexColors = options.useVertexColors; var deprecated1 = options.deprecated1; var deprecated2 = options.deprecated2; var buildingsLength = buildings.length; var batchLength = useBatchIds ? buildingsLength : 0; var meshes = new Array(buildingsLength); for (var i = 0; i < buildingsLength; ++i) { var building = buildings[i]; var transform = Matrix4.multiply( tileTransform, building.matrix, scratchMatrix ); var mesh = Mesh.createCube(); mesh.transform(transform); mesh.material = building.material; if (useVertexColors) { mesh.transferMaterialToVertexColors(); } meshes[i] = mesh; } var batchedMesh = Mesh.batch(meshes); var batchTableJson; var batchTableBinary; if (createBatchTable) { batchTableJson = generateBuildingBatchTable(buildings); if (createBatchTableExtra) { var batchTableExtra = generateBatchTableExtra(buildings); batchTableJson = combine(batchTableJson, batchTableExtra); } if (createBatchTableBinary) { batchTableJsonAndBinary = use3dTilesNext ? generateBatchTableBinary3dTilesNext(buildings) : generateBatchTableBinary(buildings); batchTableBinary = batchTableJsonAndBinary.binary; batchTableJson = combine( batchTableJson, batchTableJsonAndBinary.json ); } } var featureTableJson: any = { BATCH_LENGTH: batchLength }; if (defined(rtcCenterPosition)) { featureTableJson.RTC_CENTER = rtcCenterPosition; } else if (relativeToCenter) { featureTableJson.RTC_CENTER = Cartesian3.pack( batchedMesh.center, new Array(3) ); } var gltfOptions = { mesh: batchedMesh, useBatchIds: useBatchIds, relativeToCenter: relativeToCenter, deprecated: deprecated1 || deprecated2, use3dTilesNext: use3dTilesNext, featureTableJson: featureTableJson, animated: animated }; var gltf = createGltf(gltfOptions); var b3dmOptions: any = { featureTableJson: featureTableJson, batchTableJson: batchTableJson, batchTableBinary: batchTableBinary, batchTableJsonAndBinary: batchTableJsonAndBinary, deprecated1: deprecated1, deprecated2: deprecated2 }; var binary = defined(b3dmOptions.batchTableBinary) ? b3dmOptions.batchTableJsonAndBinary.binary : undefined; // Don't add the batch table extension if there is no batchTableJson (e.g in the case of `createBatchedWithoutBatchTable`) if (use3dTilesNext && defined(b3dmOptions.batchTableJson)) { gltf = createFeatureMetadataExtension( gltf, b3dmOptions.batchTableJson, binary ); } if (use3dTilesNext && !useGlb) { return processGltf(gltf, gltfConversionOptions).then(function ( results ) { return { gltf: results.gltf, batchTableJson: batchTableJson }; }); } if (use3dTilesNext) { return gltfToGlb(gltf, gltfConversionOptions).then(function (results) { return { glb: results.glb, batchTableJson: batchTableJson }; }); } return gltfToGlb(gltf, gltfConversionOptions).then(function (results) { b3dmOptions.glb = results.glb; return { b3dm: createB3dm(b3dmOptions), batchTableJson: batchTableJson }; }); } export type BatchTable = { id?: number[]; Longitude?: number[]; Latitude?: number[]; Height: number[]; } export function generateBuildingBatchTable(buildings: Building[]): BatchTable { var buildingsLength = buildings.length; var batchTable = { id: new Array(buildingsLength), Longitude: new Array(buildingsLength), Latitude: new Array(buildingsLength), Height: new Array(buildingsLength) }; for (var i = 0; i < buildingsLength; ++i) { var building = buildings[i]; batchTable.id[i] = i; batchTable.Longitude[i] = building.longitude; batchTable.Latitude[i] = building.latitude; batchTable.Height[i] = building.height; } return batchTable; } function generateBatchTableExtra(buildings) { var buildingsLength = buildings.length; var batchTable = { info: new Array(buildingsLength), rooms: new Array(buildingsLength) }; for (var i = 0; i < buildingsLength; ++i) { batchTable.info[i] = { name: 'building' + i, year: i }; batchTable.rooms[i] = [ 'room' + i + '_a', 'room' + i + '_b', 'room' + i + '_c' ]; } return batchTable; } function generateBatchTableBinary(buildings) { var buildingsLength = buildings.length; var cartographicBuffer = Buffer.alloc(buildingsLength * 3 * sizeOfDouble); var codeBuffer = Buffer.alloc(buildingsLength * sizeOfUint8); var batchTableJson = { cartographic: { byteOffset: 0, componentType: 'DOUBLE', type: 'VEC3' }, code: { byteOffset: cartographicBuffer.length, componentType: 'UNSIGNED_BYTE', type: 'SCALAR' } }; for (var i = 0; i < buildingsLength; ++i) { var building = buildings[i]; var code = Math.max(i, 255); cartographicBuffer.writeDoubleLE( building.longitude, i * 3 * sizeOfDouble ); cartographicBuffer.writeDoubleLE( building.latitude, (i * 3 + 1) * sizeOfDouble ); cartographicBuffer.writeDoubleLE( building.height, (i * 3 + 2) * sizeOfDouble ); codeBuffer.writeUInt8(code, i); } // No need for padding with these sample properties var batchTableBinary = Buffer.concat([cartographicBuffer, codeBuffer]); return { json: batchTableJson, binary: batchTableBinary }; } function generateBatchTableBinary3dTilesNext(buildings) { var buildingsLength = buildings.length; var cartographicBuffer = Buffer.alloc(buildingsLength * 3 * sizeOfFloat); var codeBuffer = Buffer.alloc(buildingsLength * sizeOfUint8); var batchTableJson = { cartographic: { name: 'cartographic', byteOffset: 0, byteLength: cartographicBuffer.length, componentType: 0x1406, // FLOAT type: 'VEC3', count: buildingsLength }, code: { name: 'code', byteOffset: cartographicBuffer.length, count: codeBuffer.length, byteLength: codeBuffer.length, componentType: 0x1401, // UNSIGNED_BYTE type: 'SCALAR' } }; for (var i = 0; i < buildingsLength; ++i) { var building = buildings[i]; var code = Math.max(i, 255); cartographicBuffer.writeFloatLE( building.longitude, i * 3 * sizeOfFloat ); cartographicBuffer.writeFloatLE( building.latitude, (i * 3 + 1) * sizeOfFloat ); cartographicBuffer.writeFloatLE( building.height, (i * 3 + 2) * sizeOfFloat ); codeBuffer.writeUInt8(code, i); } // No need for padding with these sample properties var batchTableBinary = Buffer.concat([cartographicBuffer, codeBuffer]); return { json: batchTableJson, binary: batchTableBinary }; }
the_stack
import type {Class} from "@swim/util"; import {Affinity, MemberFastenerClass, Property} from "@swim/component"; import {AnyLength, Length} from "@swim/math"; import {AnyFocus, Focus, AnyExpansion, Expansion} from "@swim/style"; import { Look, Feel, ThemeAnimator, FocusThemeAnimator, ExpansionThemeAnimator, ThemeConstraintAnimator, } from "@swim/theme"; import { PositionGestureInput, PositionGesture, ViewContextType, ViewFlags, ViewCreator, View, ViewSet, } from "@swim/view"; import {ViewNode, HtmlView} from "@swim/dom"; import {ButtonGlow} from "@swim/button"; import {AnyTableLayout, TableLayout} from "../layout/TableLayout"; import {CellView} from "../cell/CellView"; import type {LeafViewObserver} from "./LeafViewObserver"; /** @public */ export class LeafView extends HtmlView { constructor(node: HTMLElement) { super(node); this.initLeaf(); } protected initLeaf(): void { this.addClass("leaf"); this.position.setState("relative", Affinity.Intrinsic); this.overflowX.setState("hidden", Affinity.Intrinsic); this.overflowY.setState("hidden", Affinity.Intrinsic); const highlightPhase = this.highlight.getPhase(); const hoverPhase = this.hover.getPhase(); const backgroundPhase = Math.max(highlightPhase, hoverPhase); this.modifyMood(Feel.default, [[Feel.transparent, 1 - backgroundPhase], [Feel.hovering, hoverPhase * (1 - highlightPhase)], [Feel.selected, highlightPhase]], false); } override readonly observerType?: Class<LeafViewObserver>; @Property({type: TableLayout, inherits: true, value: null, updateFlags: View.NeedsLayout}) readonly layout!: Property<this, TableLayout | null, AnyTableLayout | null>; @Property({type: Number, inherits: true, value: 0, updateFlags: View.NeedsLayout}) readonly depth!: Property<this, number>; @ThemeConstraintAnimator({type: Length, inherits: true, value: null, updateFlags: View.NeedsLayout}) readonly rowSpacing!: ThemeConstraintAnimator<this, Length | null, AnyLength | null>; @ThemeConstraintAnimator({type: Length, inherits: true, value: null, updateFlags: View.NeedsLayout}) readonly rowHeight!: ThemeConstraintAnimator<this, Length | null, AnyLength | null>; @ThemeAnimator({type: Expansion, inherits: true, value: null, updateFlags: View.NeedsLayout}) readonly stretch!: ExpansionThemeAnimator<this, Expansion | null, AnyExpansion | null>; @Property({type: Boolean, inherits: true, value: false}) readonly hovers!: Property<this, boolean>; @ThemeAnimator<LeafView, Focus, AnyFocus>({ type: Focus, value: Focus.unfocused(), didSetValue(newHover: Focus, oldHover: Focus): void { const highlightPhase = this.owner.highlight.getPhase(); const hoverPhase = newHover.phase; const backgroundPhase = Math.max(highlightPhase, hoverPhase); this.owner.modifyMood(Feel.default, [[Feel.transparent, 1 - backgroundPhase], [Feel.hovering, hoverPhase * (1 - highlightPhase)], [Feel.selected, highlightPhase]], false); if (backgroundPhase !== 0) { this.owner.backgroundColor.setLook(Look.backgroundColor, Affinity.Intrinsic); } else { this.owner.backgroundColor.setLook(null, Affinity.Intrinsic); this.owner.backgroundColor.setState(null, Affinity.Intrinsic); } }, }) readonly hover!: FocusThemeAnimator<this>; @ThemeAnimator<LeafView, Focus, AnyFocus>({ type: Focus, value: Focus.unfocused(), willFocus(): void { this.owner.callObservers("viewWillHighlight", this.owner); }, didFocus(): void { this.owner.callObservers("viewDidHighlight", this.owner); }, willUnfocus(): void { this.owner.callObservers("viewWillUnhighlight", this.owner); }, didUnfocus(): void { this.owner.callObservers("viewDidUnhighlight", this.owner); }, didSetValue(newHighlight: Focus, oldHighlight: Focus): void { const highlightPhase = newHighlight.phase; const hoverPhase = this.owner.hover.getPhase(); const backgroundPhase = Math.max(highlightPhase, hoverPhase); this.owner.modifyMood(Feel.default, [[Feel.transparent, 1 - backgroundPhase], [Feel.hovering, hoverPhase * (1 - highlightPhase)], [Feel.selected, highlightPhase]], false); if (backgroundPhase !== 0) { this.owner.backgroundColor.setLook(Look.backgroundColor, Affinity.Intrinsic); } else { this.owner.backgroundColor.setLook(null, Affinity.Intrinsic); this.owner.backgroundColor.setState(null, Affinity.Intrinsic); } }, }) readonly highlight!: FocusThemeAnimator<this>; getCell<F extends abstract new (...args: any) => CellView>(key: string, cellViewClass: F): InstanceType<F> | null; getCell(key: string): CellView | null; getCell(key: string, cellViewClass?: abstract new (...args: any) => CellView): CellView | null { if (cellViewClass === void 0) { cellViewClass = CellView; } const cellView = this.getChild(key); return cellView instanceof cellViewClass ? cellView : null; } getOrCreateCell<F extends ViewCreator<F, CellView>>(key: string, cellViewClass: F): InstanceType<F> { let cellView = this.getChild(key, cellViewClass); if (cellView === null) { cellView = cellViewClass.create(); this.setChild(key, cellView); } return cellView!; } setCell(key: string, cellView: CellView): void { this.setChild(key, cellView); } @ViewSet<LeafView, CellView>({ type: CellView, binds: true, initView(cellView: CellView): void { cellView.display.setState("none", Affinity.Intrinsic); cellView.position.setState("absolute", Affinity.Intrinsic); cellView.left.setState(0, Affinity.Intrinsic); cellView.top.setState(0, Affinity.Intrinsic); cellView.width.setState(0, Affinity.Intrinsic); cellView.height.setState(this.owner.height.state, Affinity.Intrinsic); }, willAttachView(cellView: CellView, target: View | null): void { this.owner.callObservers("viewWillAttachCell", cellView, target, this.owner); }, didDetachView(cellView: CellView): void { this.owner.callObservers("viewDidDetachCell", cellView, this.owner); }, }) readonly cells!: ViewSet<this, CellView>; static readonly cells: MemberFastenerClass<LeafView, "cells">; protected override onLayout(viewContext: ViewContextType<this>): void { super.onLayout(viewContext); this.layoutLeaf(); } protected layoutLeaf(): void { const rowHeight = this.rowHeight.value; if (rowHeight !== null) { this.height.setState(rowHeight, Affinity.Intrinsic); } } protected override displayChildren(displayFlags: ViewFlags, viewContext: ViewContextType<this>, displayChild: (this: this, child: View, displayFlags: ViewFlags, viewContext: ViewContextType<this>) => void): void { if ((displayFlags & View.NeedsLayout) !== 0) { this.layoutChildViews(displayFlags, viewContext, displayChild); } else { super.displayChildren(displayFlags, viewContext, displayChild); } } protected layoutChildViews(displayFlags: ViewFlags, viewContext: ViewContextType<this>, displayChild: (this: this, child: View, displayFlags: ViewFlags, viewContext: ViewContextType<this>) => void): void { const layout = this.layout.value; const height = this.height.state; const stretch = this.stretch.getPhaseOr(1); type self = this; function layoutChildView(this: self, child: View, displayFlags: ViewFlags, viewContext: ViewContextType<self>): void { if (child instanceof CellView) { const key = child.key; const col = layout !== null && key !== void 0 ? layout.getCol(key) : null; if (col !== null) { child.display.setState(!col.hidden ? "flex" : "none", Affinity.Intrinsic); child.left.setState(col.left, Affinity.Intrinsic); child.width.setState(col.width, Affinity.Intrinsic); child.height.setState(height, Affinity.Intrinsic); const textColor = col.textColor; if (textColor instanceof Look) { child.color.setLook(textColor, Affinity.Intrinsic); } else { child.color.setState(textColor, Affinity.Intrinsic); } if (!col.persistent) { child.opacity.setState(stretch, Affinity.Intrinsic); } } else { child.display.setState("none", Affinity.Intrinsic); child.left.setState(null, Affinity.Intrinsic); child.width.setState(null, Affinity.Intrinsic); child.height.setState(null, Affinity.Intrinsic); } } displayChild.call(this, child, displayFlags, viewContext); } super.displayChildren(displayFlags, viewContext, layoutChildView); } @Property({type: Boolean, inherits: true, value: true}) readonly glows!: Property<this, boolean>; protected glow(input: PositionGestureInput): void { if (input.detail instanceof ButtonGlow) { input.detail.fade(input.x, input.y); input.detail = void 0; } if (input.detail === void 0) { const delay = input.inputType === "mouse" ? 0 : 100; input.detail = this.prependChild(ButtonGlow); (input.detail as ButtonGlow).glow(input.x, input.y, void 0, delay); } } @PositionGesture<LeafView, LeafView>({ self: true, didBeginPress(input: PositionGestureInput, event: Event | null): void { if (this.owner.glows.value) { this.owner.glow(input); } }, didMovePress(input: PositionGestureInput, event: Event | null): void { if (input.isRunaway()) { this.cancelPress(input, event); } else if (!this.owner.clientBounds.contains(input.x, input.y)) { input.clearHoldTimer(); this.beginHover(input, event); if (input.detail instanceof ButtonGlow) { input.detail.fade(input.x, input.y); input.detail = void 0; } } }, didEndPress(input: PositionGestureInput, event: Event | null): void { if (!this.owner.clientBounds.contains(input.x, input.y)) { this.endHover(input, event); if (input.detail instanceof ButtonGlow) { input.detail.fade(input.x, input.y); input.detail = void 0; } } else if (input.detail instanceof ButtonGlow) { input.detail.pulse(input.x, input.y); } }, didCancelPress(input: PositionGestureInput, event: Event | null): void { if (!this.owner.clientBounds.contains(input.x, input.y)) { this.endHover(input, event); } if (input.detail instanceof ButtonGlow) { input.detail.fade(input.x, input.y); input.detail = void 0; } }, didStartHovering(): void { if (this.owner.hovers.value) { this.owner.hover.focus(false); } this.owner.callObservers("viewDidEnter", this.owner); }, didStopHovering(): void { if (this.owner.hovers.value) { this.owner.hover.unfocus(); } this.owner.callObservers("viewDidLeave", this.owner); }, didPress(input: PositionGestureInput, event: Event | null): void { if (this.owner.clientBounds.contains(input.x, input.y)) { if (!input.defaultPrevented) { let target = input.target; while (target !== null && target !== this.owner.node) { const targetView = (target as ViewNode).view; if (targetView instanceof CellView) { targetView.onPress(input, event); targetView.didPress(input, event); break; } target = target instanceof Node ? target.parentNode : null; } } if (!input.defaultPrevented) { this.owner.callObservers("viewDidPress", input, event, this.owner); } } }, didLongPress(input: PositionGestureInput): void { if (!input.defaultPrevented) { let target = input.target; while (target !== null && target !== this.owner.node) { const targetView = (target as ViewNode).view; if (targetView instanceof CellView) { targetView.onLongPress(input); targetView.didLongPress(input); break; } target = target instanceof Node ? target.parentNode : null; } } if (!input.defaultPrevented) { this.owner.callObservers("viewDidLongPress", input, this.owner); } }, }) readonly gesture!: PositionGesture<this, LeafView>; static readonly gesture: MemberFastenerClass<LeafView, "gesture">; }
the_stack
import { DOWN_ARROW, ENTER, ESCAPE, UP_ARROW } from '@angular/cdk/keycodes'; import { OverlayContainer } from '@angular/cdk/overlay'; import { CommonModule } from '@angular/common'; import { Component, NgModule, NgZone, OnDestroy, QueryList, ViewChild, ViewChildren } from '@angular/core'; import { Type } from '@angular/core/src/type'; import { async, ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { Subscription } from 'rxjs'; import { createKeyboardEvent, dispatchFakeEvent, dispatchKeyboardEvent, expectDom, fastTestSetup, typeInElement, } from '../../../../test/helpers'; import { MockNgZone } from '../../../../test/mocks/browser'; import { FormFieldModule } from '../form-field'; import { InputModule } from '../input'; import { AutocompleteItemComponent } from './autocomplete-item.component'; import { AUTOCOMPLETE_ITEM_HEIGHT, AUTOCOMPLETE_PANEL_HEIGHT, AutocompleteTriggerDirective, } from './autocomplete-trigger.directive'; import { AutocompleteComponent } from './autocomplete.component'; import { AutocompleteModule } from './autocomplete.module'; describe('browser.ui.autocomplete', () => { let overlayContainer: OverlayContainer; let overlayContainerEl: HTMLElement; let zone: MockNgZone; function createFixture<T>(component: Type<T>): ComponentFixture<T> { const fixture = TestBed.createComponent(component); fixture.detectChanges(); return fixture; } fastTestSetup(); beforeAll(async () => { await TestBed .configureTestingModule({ imports: [TestAutocompleteModule], providers: [...MockNgZone.providers()], }) .compileComponents(); }); beforeEach(() => { overlayContainer = TestBed.get(OverlayContainer); overlayContainerEl = overlayContainer.getContainerElement(); zone = TestBed.get(NgZone); }); afterEach(() => { overlayContainer.ngOnDestroy(); }); describe('panel toggling', () => { let fixture: ComponentFixture<SimpleAutocompleteComponent>; let inputEl: HTMLInputElement; beforeEach(() => { fixture = createFixture<SimpleAutocompleteComponent>(SimpleAutocompleteComponent); inputEl = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement; }); it('should open the panel when the input is focused.', () => { expect(fixture.componentInstance.trigger.panelOpen) .toBe(false, `Expected panel state to start out closed.`); dispatchFakeEvent(inputEl, 'focusin'); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen).toBe(true); expectDom(overlayContainerEl).toContainText('Alabama'); expectDom(overlayContainerEl).toContainText('California'); }); it('should not open the panel on focus if the input is readonly.', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; inputEl.readOnly = true; fixture.detectChanges(); expect(trigger.panelOpen).toBe(false, 'Expected panel state to start out closed.'); dispatchFakeEvent(inputEl, 'focusin'); flush(); fixture.detectChanges(); expect(trigger.panelOpen).toBe(false, 'Expected panel to stay closed.'); })); it('should not open using the arrow keys when the input is readonly', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; inputEl.readOnly = true; fixture.detectChanges(); expect(trigger.panelOpen).toBe(false, 'Expected panel state to start out closed.'); dispatchKeyboardEvent(inputEl, 'keydown', DOWN_ARROW); flush(); fixture.detectChanges(); expect(trigger.panelOpen).toBe(false, 'Expected panel to stay closed.'); })); it('should show the panel when the first open is after the initial zone stabilization.', async(() => { // Note that we're running outside the Angular zone, in order to be able // to test properly without the subscription from `_subscribeToClosingActions` // giving us a false positive. fixture.ngZone.runOutsideAngular(() => { fixture.componentInstance.trigger.openPanel(); Promise.resolve().then(() => { expect(fixture.componentInstance.panel.showPanel) .toBe(true, `Expected panel to be visible.`); }); }); })); it('should close the panel when the user clicks away.', fakeAsync(() => { dispatchFakeEvent(inputEl, 'focusin'); fixture.detectChanges(); zone.simulateZoneExit(); dispatchFakeEvent(document, 'click'); expect(fixture.componentInstance.trigger.panelOpen) .toBe(false, `Expected clicking outside the panel to set its state to closed.`); expect(overlayContainerEl.textContent) .toEqual('', `Expected clicking outside the panel to close the panel.`); })); it('should close the panel when an item is clicked.', fakeAsync(() => { dispatchFakeEvent(inputEl, 'focusin'); fixture.detectChanges(); zone.simulateZoneExit(); const item = overlayContainerEl.querySelector('gd-autocomplete-item') as HTMLElement; item.click(); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .toBe(false, `Expected clicking an option to set the panel state to closed.`); expect(overlayContainerEl.textContent) .toEqual('', `Expected clicking an option to close the panel.`); })); it('should close the panel when a newly created item is clicked', fakeAsync(() => { dispatchFakeEvent(inputEl, 'focusin'); fixture.detectChanges(); zone.simulateZoneExit(); // Filter down the option list to a subset of original items ('Alabama', 'California') typeInElement('al', inputEl); fixture.detectChanges(); tick(); let items = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; items[0].click(); // Changing value from 'Alabama' to 'al' to re-populate the option list, // ensuring that 'California' is created new. dispatchFakeEvent(inputEl, 'focusin'); zone.simulateZoneExit(); typeInElement('al', inputEl); fixture.detectChanges(); tick(); items = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; items[1].click(); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .toBe(false, `Expected clicking a new option to set the panel state to closed.`); expect(overlayContainerEl.textContent) .toEqual('', `Expected clicking a new option to close the panel.`); })); it('should hide the panel when the items list is empty.', fakeAsync(() => { dispatchFakeEvent(inputEl, 'focusin'); fixture.detectChanges(); zone.simulateZoneExit(); const panel = overlayContainerEl.querySelector('.Autocomplete__panel') as HTMLElement; expect(panel.classList.contains('Autocomplete__panel--visible')).toBe(true); // Filter down the option list such that no options match the value typeInElement('af', inputEl); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(panel.classList.contains('Autocomplete__panel--hidden')).toBe(true); })); it('should not be able to open the panel if the autocomplete is disabled', () => { expect(fixture.componentInstance.trigger.panelOpen).toBe(false); fixture.componentInstance.autocompleteDisabled = true; fixture.detectChanges(); dispatchFakeEvent(inputEl, 'focusin'); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen).toBe(false); }); }); describe('form integrations', () => { let fixture: ComponentFixture<SimpleAutocompleteComponent>; let inputEl: HTMLInputElement; beforeEach(() => { fixture = createFixture<SimpleAutocompleteComponent>(SimpleAutocompleteComponent); inputEl = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement; }); it('should update control value as user types with input value.', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); zone.simulateZoneExit(); typeInElement('a', inputEl); fixture.detectChanges(); expect(fixture.componentInstance.control.value).toEqual('a'); typeInElement('al', inputEl); fixture.detectChanges(); expect(fixture.componentInstance.control.value).toEqual('al'); }); it('should update control value when item is selected with item value.', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); zone.simulateZoneExit(); const items = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; items[1].click(); fixture.detectChanges(); expect(fixture.componentInstance.control.value).toEqual({ code: 'CA', name: 'California' }); })); it('should update the control back to a string if user types after an item is selected.', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); zone.simulateZoneExit(); const items = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; items[1].click(); fixture.detectChanges(); typeInElement('Californi', inputEl); fixture.detectChanges(); tick(); expect(fixture.componentInstance.control.value).toEqual('Californi'); })); it('should fill the text field with display value when an item is selected.', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); zone.simulateZoneExit(); const items = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; items[1].click(); fixture.detectChanges(); expect(inputEl.value).toContain('California'); })); it('should fill the text field with value if displayWith is not set', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); zone.simulateZoneExit(); fixture.componentInstance.panel.displayWith = null; fixture.componentInstance.options.toArray()[1].value = 'test value'; fixture.detectChanges(); const items = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; items[1].click(); fixture.detectChanges(); expect(inputEl.value).toContain('test value'); })); it('should fill the text field correctly if value is set to obj programmatically.', fakeAsync(() => { fixture.componentInstance.control.setValue({code: 'AL', name: 'Alabama'}); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(inputEl.value).toContain('Alabama'); })); it('should clear the text field if value is reset programmatically.', fakeAsync(() => { typeInElement('Alabama', inputEl); fixture.detectChanges(); tick(); fixture.componentInstance.control.reset(); tick(); fixture.detectChanges(); tick(); expect(inputEl.value).toEqual(''); })); it('should disable input in view when disabled programmatically', () => { expect(inputEl.disabled).toBe(false); fixture.componentInstance.control.disable(); fixture.detectChanges(); expect(inputEl.disabled).toBe(true); }); it('should mark the autocomplete control as dirty as user types.', () => { expect(fixture.componentInstance.control.dirty).toBe(false); typeInElement('a', inputEl); fixture.detectChanges(); expect(fixture.componentInstance.control.dirty).toBe(true); }); it('should mark the autocomplete control as dirty when an item is selected', fakeAsync(() => { expect(fixture.componentInstance.control.dirty).toBe(false); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); zone.simulateZoneExit(); const items = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; items[1].click(); fixture.detectChanges(); expect(fixture.componentInstance.control.dirty).toBe(true); })); }); describe('keyboard events', () => { let fixture: ComponentFixture<SimpleAutocompleteComponent>; let inputEl: HTMLInputElement; let DOWN_ARROW_EVENT: KeyboardEvent; let UP_ARROW_EVENT: KeyboardEvent; let ENTER_EVENT: KeyboardEvent; beforeEach(fakeAsync(() => { fixture = createFixture<SimpleAutocompleteComponent>(SimpleAutocompleteComponent); fixture.detectChanges(); inputEl = fixture.debugElement.query(By.css('input')).nativeElement; DOWN_ARROW_EVENT = createKeyboardEvent('keydown', DOWN_ARROW); UP_ARROW_EVENT = createKeyboardEvent('keydown', UP_ARROW); ENTER_EVENT = createKeyboardEvent('keydown', ENTER); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); zone.simulateZoneExit(); })); it('should not focus the item when DOWN key is pressed.', () => { spyOn(fixture.componentInstance.options.first, 'focus'); fixture.componentInstance.trigger._handleKeyDown(DOWN_ARROW_EVENT); expect(fixture.componentInstance.options.first.focus).not.toHaveBeenCalled(); }); it('should not close the panel when DOWN key is pressed.', () => { fixture.componentInstance.trigger._handleKeyDown(DOWN_ARROW_EVENT); expect(fixture.componentInstance.trigger.panelOpen) .toBe(true, `Expected panel state to stay open when DOWN key is pressed.`); expect(overlayContainerEl.textContent) .toContain('Alabama', `Expected panel to keep displaying when DOWN key is pressed.`); expect(overlayContainerEl.textContent) .toContain('California', `Expected panel to keep displaying when DOWN key is pressed.`); }); it('should set the active item to the first option when DOWN key is pressed.', () => { const componentInstance = fixture.componentInstance; const itemEls = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; expect(componentInstance.trigger.panelOpen) .toBe(true, 'Expected first down press to open the pane.'); componentInstance.trigger._handleKeyDown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(componentInstance.trigger.activeItem === componentInstance.options.first) .toBe(true, 'Expected first option to be active.'); expect(itemEls[0].classList).toContain('AutocompleteItem--active'); expect(itemEls[1].classList).not.toContain('AutocompleteItem--active'); componentInstance.trigger._handleKeyDown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(componentInstance.trigger.activeItem === componentInstance.options.toArray()[1]) .toBe(true, 'Expected second option to be active.'); expect(itemEls[0].classList).not.toContain('AutocompleteItem--active'); expect(itemEls[1].classList).toContain('AutocompleteItem--active'); }); it('should set the active item to the last option when UP key is pressed.', () => { const componentInstance = fixture.componentInstance; const itemEls = overlayContainerEl.querySelectorAll('gd-autocomplete-item') as NodeListOf<HTMLElement>; expect(componentInstance.trigger.panelOpen) .toBe(true, 'Expected first up press to open the pane.'); componentInstance.trigger._handleKeyDown(UP_ARROW_EVENT); fixture.detectChanges(); expect(componentInstance.trigger.activeItem === componentInstance.options.last) .toBe(true, 'Expected last option to be active.'); expect(itemEls[20].classList).toContain('AutocompleteItem--active'); expect(itemEls[0].classList).not.toContain('AutocompleteItem--active'); componentInstance.trigger._handleKeyDown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(componentInstance.trigger.activeItem === componentInstance.options.first) .toBe(true, 'Expected first option to be active.'); expect(itemEls[0].classList).toContain('AutocompleteItem--active'); }); it('should set the active item properly after filtering.', fakeAsync(() => { const componentInstance = fixture.componentInstance; componentInstance.trigger._handleKeyDown(DOWN_ARROW_EVENT); tick(); fixture.detectChanges(); })); it('should close the panel when pressing escape.', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; inputEl.focus(); flush(); fixture.detectChanges(); expect(document.activeElement).toBe(inputEl, 'Expected input to be focused.'); expect(trigger.panelOpen).toBe(true, 'Expected panel to be open.'); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); fixture.detectChanges(); expect(document.activeElement).toBe(inputEl, 'Expected input to continue to be focused.'); expect(trigger.panelOpen).toBe(false, 'Expected panel to be closed.'); })); it('should scroll to active items below the fold', () => { const trigger = fixture.componentInstance.trigger; const scrollContainer = document.querySelector('.cdk-overlay-pane .Autocomplete__panel'); trigger._handleKeyDown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(scrollContainer.scrollTop).toEqual(0, `Expected panel not to scroll.`); // These down arrows will set the 12th option active, below the fold. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].forEach(() => trigger._handleKeyDown(DOWN_ARROW_EVENT)); // Expect option bottom minus the panel height (288 - 256 = 32) const expected = 12 * AUTOCOMPLETE_ITEM_HEIGHT - AUTOCOMPLETE_PANEL_HEIGHT; expect(scrollContainer.scrollTop).toEqual(expected, `Expected panel to reveal the ten item.`); }); it('should scroll to active items on UP arrow', () => { const scrollContainer = document.querySelector('.cdk-overlay-pane .Autocomplete__panel'); fixture.componentInstance.trigger._handleKeyDown(UP_ARROW_EVENT); fixture.detectChanges(); // Expect option bottom minus the panel height (24 * 21 - 256 = 248) expect(scrollContainer.scrollTop).toEqual(248, `Expected panel to reveal last option.`); }); }); }); @Component({ template: ` <gd-form-field> <input gdInput [gdAutocompleteTrigger]="auto" [gdAutocompleteDisabled]="autocompleteDisabled" [formControl]="control"> </gd-form-field> <gd-autocomplete #auto="gdAutocomplete" [displayWith]="displayFn"> <gd-autocomplete-item *ngFor="let state of filteredStates" [value]="state"> <span>{{ state.code }}: {{ state.name }}</span> </gd-autocomplete-item> </gd-autocomplete> `, }) class SimpleAutocompleteComponent implements OnDestroy { control = new FormControl(); filteredStates: any[]; valueSub: Subscription; autocompleteDisabled = false; @ViewChild(AutocompleteTriggerDirective) trigger: AutocompleteTriggerDirective; @ViewChild(AutocompleteComponent) panel: AutocompleteComponent; @ViewChildren(AutocompleteItemComponent) options: QueryList<AutocompleteItemComponent>; states = [ { code: 'AL', name: 'Alabama' }, { code: 'CA', name: 'California' }, { code: 'FL', name: 'Florida' }, { code: 'KS', name: 'Kansas' }, { code: 'MA', name: 'Massachusetts' }, { code: 'NY', name: 'New York' }, { code: 'OR', name: 'Oregon' }, { code: 'PA', name: 'Pennsylvania' }, { code: 'TN', name: 'Tennessee' }, { code: 'VA', name: 'Virginia' }, { code: 'WY', name: 'Wyoming' }, { code: 'OO', name: 'Oooo' }, { code: 'PP', name: 'Pppp' }, { code: 'QQ', name: 'Qqqq' }, { code: 'BB', name: 'Bbbb' }, { code: 'CC', name: 'Cccc' }, { code: 'II', name: 'Iiii' }, { code: 'UU', name: 'Uuuu' }, { code: 'ZZ', name: 'Zzzz' }, { code: 'Nm', name: 'Nmmm' }, { code: '11', name: '1111' }, ]; constructor() { this.filteredStates = this.states; this.valueSub = this.control.valueChanges.subscribe(val => { this.filteredStates = val ? this.states.filter(s => s.name.match(new RegExp(val, 'gi'))) : this.states; }); } displayFn(value: any): string { return value ? value.name : value; } ngOnDestroy(): void { this.valueSub.unsubscribe(); } } @NgModule({ imports: [ CommonModule, AutocompleteModule, FormFieldModule, InputModule, ReactiveFormsModule, ], declarations: [ SimpleAutocompleteComponent, ], exports: [ SimpleAutocompleteComponent, ], }) class TestAutocompleteModule { }
the_stack
import { EventEmitter } from 'events' import { priorityQueue, AsyncPriorityQueue } from 'async' import { Logger, LoggerOptions } from 'node-log-it' import { merge, map, difference, filter, take } from 'lodash' import { Node } from './node' import { Mesh } from './mesh' import { MemoryStorage } from '../storages/memory-storage' import { MongodbStorage } from '../storages/mongodb-storage' // import C from '../common/constants' const MODULE_NAME = 'Syncer' const DEFAULT_OPTIONS: SyncerOptions = { minHeight: 1, maxHeight: undefined, blockRedundancy: 1, // If value is greater than 1, than it'll keep multiple copies of same block as integrity measurement // TODO: to ensure redundant blocks are coming from unique sources checkRedundancyBeforeStoreBlock: true, // Perform a count on given height before attempt to store block. startOnInit: true, toSyncIncremental: true, toSyncForMissingBlocks: true, toPruneRedundantBlocks: true, storeQueueConcurrency: 30, pruneQueueConcurrency: 10, enqueueBlockIntervalMs: 5000, verifyBlocksIntervalMs: 1 * 60 * 1000, maxStoreQueueLength: 1000, retryEnqueueDelayMs: 5000, standardEnqueueBlockPriority: 5, retryEnqueueBlockPriority: 3, missingEnqueueStoreBlockPriority: 1, enqueuePruneBlockPriority: 5, maxPruneChunkSize: 1000, loggerOptions: {}, } export interface SyncerOptions { minHeight?: number maxHeight?: number blockRedundancy?: number checkRedundancyBeforeStoreBlock?: boolean startOnInit?: boolean toSyncIncremental?: boolean toSyncForMissingBlocks?: boolean toPruneRedundantBlocks?: boolean storeQueueConcurrency?: number pruneQueueConcurrency?: number enqueueBlockIntervalMs?: number verifyBlocksIntervalMs?: number maxStoreQueueLength?: number retryEnqueueDelayMs?: number standardEnqueueBlockPriority?: number retryEnqueueBlockPriority?: number missingEnqueueStoreBlockPriority?: number enqueuePruneBlockPriority?: number maxPruneChunkSize?: number loggerOptions?: LoggerOptions } export class Syncer extends EventEmitter { private _isRunning = false private storeQueue: AsyncPriorityQueue<object> private pruneQueue: AsyncPriorityQueue<object> private blockWritePointer: number = 0 private mesh: Mesh private storage?: MemoryStorage | MongodbStorage private options: SyncerOptions private logger: Logger private enqueueStoreBlockIntervalId?: NodeJS.Timer private blockVerificationIntervalId?: NodeJS.Timer private isVerifyingBlocks = false constructor(mesh: Mesh, storage?: MemoryStorage | MongodbStorage, options: SyncerOptions = {}) { super() // Associate required properties this.mesh = mesh this.storage = storage // Associate optional properties this.options = merge({}, DEFAULT_OPTIONS, options) this.validateOptionalParameters() // Bootstrapping this.logger = new Logger(MODULE_NAME, this.options.loggerOptions) this.storeQueue = this.getPriorityQueue(this.options.storeQueueConcurrency!) this.pruneQueue = this.getPriorityQueue(this.options.pruneQueueConcurrency!) if (this.options.startOnInit) { this.start() } // Event handlers this.on('storeBlock:complete', this.storeBlockCompleteHandler.bind(this)) this.logger.debug('constructor completes.') } isRunning(): boolean { return this._isRunning } start() { if (this._isRunning) { this.logger.info('Syncer has already started.') return } if (!this.storage) { this.logger.info('Unable to start syncer when no storage are defined.') return } this.logger.info('Start syncer. minHeight:', this.options.minHeight!, 'maxHeight:', this.options.maxHeight) this._isRunning = true this.emit('start') this.initStoreBlock() this.initBlockVerification() } stop() { if (!this._isRunning) { this.logger.info('Syncer is not running at the moment.') return } this.logger.info('Stop syncer.') this._isRunning = false this.emit('stop') clearInterval(this.enqueueStoreBlockIntervalId!) clearInterval(this.blockVerificationIntervalId!) } close() { this.stop() } private storeBlockCompleteHandler(payload: any) { if (payload.isSuccess === false) { this.logger.debug('storeBlockCompleteHandler !isSuccess triggered.') setTimeout(() => { // Re-queue the method when failed after an injected delay this.enqueueStoreBlock(payload.height, this.options.retryEnqueueBlockPriority!) }, this.options.retryEnqueueDelayMs!) } } private validateOptionalParameters() { if (!this.options.blockRedundancy) { throw new Error('blockRedundancy parameter must be supplied.') } else if (this.options.blockRedundancy !== 1) { throw new Error('supplied blockRedundancy parameter is invalid. Currently only supports for value [1].') } } private getPriorityQueue(concurrency: number): AsyncPriorityQueue<object> { return priorityQueue((task: object, callback: () => void) => { const method: (attrs: object) => Promise<any> = (task as any).method const attrs: object = (task as any).attrs const meta: object = (task as any).meta this.logger.debug('New worker for queue. meta:', meta, 'attrs:', attrs) method(attrs) .then(() => { callback() this.logger.debug('Worker queued method completed.') this.emit('queue:worker:complete', { isSuccess: true, task }) }) .catch((err: any) => { this.logger.info('Worker queued method failed, but to continue... meta:', meta, 'attrs:', attrs, 'Message:', err.message) callback() this.emit('queue:worker:complete', { isSuccess: false, task }) }) }, concurrency) } private initStoreBlock() { this.logger.debug('initStoreBlock triggered.') this.setBlockWritePointer() .then(() => { if (this.options.toSyncIncremental) { // Enqueue blocks for download periodically this.enqueueStoreBlockIntervalId = setInterval(() => { this.doEnqueueStoreBlock() }, this.options.enqueueBlockIntervalMs!) } }) .catch((err: any) => { this.logger.warn('setBlockWritePointer() failed. Error:', err.message) }) } private doEnqueueStoreBlock() { this.logger.debug('doEnqueueStoreBlock triggered.') if (this.isReachedMaxHeight()) { this.logger.info(`BlockWritePointer is greater or equal to designated maxHeight [${this.options.maxHeight}]. There will be no enqueue block beyond this point.`) return } const node = this.mesh.getHighestNode() if (node) { // TODO: better way to validate a node // TODO: undefined param handler while (!this.isReachedMaxHeight() && !this.isReachedHighestBlock(node) && !this.isReachedMaxStoreQueueLength()) { this.increaseBlockWritePointer() this.enqueueStoreBlock(this.blockWritePointer!, this.options.standardEnqueueBlockPriority!) } } else { this.logger.error('Unable to find a valid node.') } } private isReachedMaxHeight(): boolean { return !!(this.options.maxHeight && this.blockWritePointer >= this.options.maxHeight) } private isReachedHighestBlock(node: Node): boolean { return this.blockWritePointer! >= node.blockHeight! } private isReachedMaxStoreQueueLength(): boolean { return this.storeQueue.length() >= this.options.maxStoreQueueLength! } private async setBlockWritePointer(): Promise<void> { this.logger.debug('setBlockWritePointer triggered.') try { const height = await this.storage!.getHighestBlockHeight() this.logger.debug('getHighestBlockHeight() success. height:', height) if (this.options.minHeight && height < this.options.minHeight) { this.logger.info(`storage height is smaller than designated minHeight. BlockWritePointer will be set to minHeight [${this.options.minHeight}] instead.`) this.blockWritePointer = this.options.minHeight } else { this.blockWritePointer = height } } catch (err) { this.logger.warn('storage.getHighestBlockHeight() failed. Error:', err.message) this.logger.info('Assumed that there are no blocks.') this.blockWritePointer = this.options.minHeight! } } private initBlockVerification() { this.logger.debug('initEnqueueBlock triggered.') this.blockVerificationIntervalId = setInterval(() => { this.doBlockVerification() }, this.options.verifyBlocksIntervalMs!) } private async doBlockVerification() { this.logger.debug('doBlockVerification triggered.') this.emit('blockVerification:init') // Queue sizes this.logger.info('storeQueue.length:', this.storeQueue.length()) this.logger.info('pruneQueue.length:', this.pruneQueue.length()) // Check if this process is currently executing if (this.isVerifyingBlocks) { this.logger.info('doBlockVerification() is already running. Skip this turn.') this.emit('blockVerification:complete', { isSkipped: true }) return } // Blocks analysis this.isVerifyingBlocks = true const startHeight = this.options.minHeight! const endHeight = this.options.maxHeight && this.blockWritePointer > this.options.maxHeight ? this.options.maxHeight : this.blockWritePointer this.logger.debug('Analyzing blocks in storage...') let blockReport: any try { blockReport = await this.storage!.analyzeBlocks(startHeight, endHeight) this.logger.debug('Analyzing blocks complete!') } catch (err) { this.logger.info('storage.analyzeBlocks error, but to continue... Message:', err.message) this.emit('blockVerification:complete', { isSuccess: false }) this.isVerifyingBlocks = false return } const all: number[] = [] for (let i = startHeight; i <= endHeight; i++) { all.push(i) } const availableBlocks: number[] = map(blockReport, (item: any) => item._id) this.logger.info('Blocks available count:', availableBlocks.length) // Enqueue missing block heights const missingBlocks = difference(all, availableBlocks) this.logger.info('Blocks missing count:', missingBlocks.length) this.emit('blockVerification:missingBlocks', { count: missingBlocks.length }) if (this.options.toSyncForMissingBlocks) { missingBlocks.forEach((height: number) => { this.enqueueStoreBlock(height, this.options.missingEnqueueStoreBlockPriority!) }) } // Request pruning of excessive blocks const excessiveBlocks = map(filter(blockReport, (item: any) => item.count > this.options.blockRedundancy!), (item: any) => item._id) this.logger.info('Blocks excessive redundancy count:', excessiveBlocks.length) this.emit('blockVerification:excessiveBlocks', { count: excessiveBlocks.length }) if (this.options.toPruneRedundantBlocks) { const takenBlocks = take(excessiveBlocks, this.options.maxPruneChunkSize!) takenBlocks.forEach((height: number) => { this.enqueuePruneBlock(height, this.options.blockRedundancy!, this.options.enqueuePruneBlockPriority!) }) } // Enqueue for redundancy blocks if (this.options.blockRedundancy! > 1) { const insufficientBlocks = map(filter(blockReport, (item: any) => item.count < this.options.blockRedundancy!), (item: any) => item._id) this.logger.info('Blocks insufficient redundancy count:', insufficientBlocks.length) // TODO throw new Error('Not Implemented.') } // Check if fully sync'ed const node = this.mesh.getHighestNode() if (node) { if (this.isReachedMaxHeight() || this.isReachedHighestBlock(node)) { if (missingBlocks.length === 0) { this.logger.info('Storage is fully synced and up to date.') this.emit('upToDate') } } } // Conclude this.isVerifyingBlocks = false this.emit('blockVerification:complete', { isSuccess: true }) } private increaseBlockWritePointer() { this.logger.debug('increaseBlockWritePointer triggered.') this.blockWritePointer += 1 } /** * @param priority Lower value, the higher its priority to be executed. */ private enqueueStoreBlock(height: number, priority: number) { this.logger.debug('enqueueStoreBlock triggered. height:', height, 'priority:', priority) // if the block height is above the current height, increment the write pointer. if (height > this.blockWritePointer) { this.logger.debug('height > this.blockWritePointer, blockWritePointer is now:', height) this.blockWritePointer = height } // enqueue the block this.storeQueue.push( { method: this.storeBlock.bind(this), attrs: { height, }, meta: { methodName: 'storeBlock', }, }, priority ) } /** * @param priority Lower value, the higher its priority to be executed. */ private enqueuePruneBlock(height: number, redundancySize: number, priority: number) { this.logger.debug('enqueuePruneBlock triggered. height:', height, 'redundancySize:', redundancySize, 'priority:', priority) this.pruneQueue.push( { method: this.pruneBlock.bind(this), attrs: { height, redundancySize, }, meta: { methodName: 'pruneBlock', }, }, priority ) } private async storeBlock(attrs: object): Promise<any> { this.logger.debug('storeBlock triggered. attrs:', attrs) const height: number = (attrs as any).height const node = this.mesh.getOptimalNode(height) this.emit('storeBlock:init', { height }) try { // Validate redundancy level if (this.options.checkRedundancyBeforeStoreBlock) { const redundantCount = await this.storage!.countBlockRedundancy(height) if (redundantCount >= this.options.blockRedundancy!) { this.logger.debug('setBlock skipped. height:', height) this.emit('storeBlock:complete', { isSkipped: true, height }) return } } // Validate dependencies if (!node) { this.emit('storeBlock:complete', { isSuccess: false, height }) throw new Error('No valid node found.') } // Fetch and store block const block = await node!.getBlock(height) const source = node!.endpoint const userAgent = node!.userAgent await this.storage!.setBlock(height, block, { source, userAgent }) this.logger.debug('storeBlock succeeded. height:', height) this.emit('storeBlock:complete', { isSuccess: true, height }) } catch (err) { this.logger.debug('storeBlock failed. height:', height, 'Message:', err.message) this.emit('storeBlock:complete', { isSuccess: false, height }) throw err } } private async pruneBlock(attrs: object): Promise<void> { this.logger.debug('pruneBlock triggered. attrs:', attrs) const height: number = (attrs as any).height const redundancySize: number = (attrs as any).redundancySize await this.storage!.pruneBlock(height, redundancySize) } }
the_stack
import { Base } from "../../src/class/Base.js" import { calculate, Entity, field } from "../../src/replica/Entity.js" import { reference } from "../../src/replica/Reference.js" import { bucket } from "../../src/replica/ReferenceBucket.js" import { Replica } from "../../src/replica/Replica.js" import { Schema } from "../../src/schema/Schema.js" declare const StartTest : any StartTest(t => { t.it('Author/Book no commits', async t => { const SomeSchema = Schema.new({ name : 'Cool data schema' }) const entity = SomeSchema.getEntityDecorator() @entity class Author extends Entity.mix(Base) { @bucket() books : Set<Book> } @entity class Book extends Entity.mix(Base) { @reference({ bucket : 'books' }) writtenBy : Author } const replica1 = Replica.new({ schema : SomeSchema }) const markTwain = Author.new() const tomSoyer = Book.new({ writtenBy : markTwain }) replica1.addEntity(markTwain) replica1.addEntity(tomSoyer) //-------------------- t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly filled bucket') t.isDeeply(tomSoyer.writtenBy, markTwain, 'Correct reference value') //-------------------- const tomSoyer2 = Book.new({ writtenBy : markTwain }) replica1.addEntity(tomSoyer2) t.isDeeply(markTwain.books, new Set([ tomSoyer, tomSoyer2 ]), 'Correctly resolved reference #1') //-------------------- tomSoyer2.writtenBy = null t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly resolved reference #2') //-------------------- replica1.removeEntity(tomSoyer) t.isDeeply(markTwain.books, new Set(), 'Correctly resolved reference #3') //-------------------- replica1.addEntity(tomSoyer) t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly resolved reference #4') }) t.it('Author/Book with commits', async t => { const SomeSchema = Schema.new({ name : 'Cool data schema' }) const entity = SomeSchema.getEntityDecorator() @entity class Author extends Entity.mix(Base) { @bucket() books : Set<Book> } @entity class Book extends Entity.mix(Base) { @reference({ bucket : 'books' }) writtenBy : Author } const replica1 = Replica.new({ schema : SomeSchema }) const markTwain = Author.new() const tomSoyer = Book.new({ writtenBy : markTwain }) replica1.addEntity(markTwain) replica1.addEntity(tomSoyer) //-------------------- replica1.commit() t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly filled bucket') t.isDeeply(tomSoyer.writtenBy, markTwain, 'Correct reference value') //-------------------- const tomSoyer2 = Book.new({ writtenBy : markTwain }) replica1.addEntity(tomSoyer2) // comment to see a failure related to the unordered processing of added/removed entries in the bucket // bucket should have a single, ordered queue for add/remove mutations instead of 2 props `newRefs`, `oldRefs` replica1.commit() t.isDeeply(markTwain.books, new Set([ tomSoyer, tomSoyer2 ]), 'Correctly resolved reference #1') //-------------------- tomSoyer2.writtenBy = null replica1.commit() t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly resolved reference #2') //-------------------- replica1.removeEntity(tomSoyer) replica1.commit() t.isDeeply(markTwain.books, new Set(), 'Correctly resolved reference') //-------------------- replica1.addEntity(tomSoyer) replica1.commit() t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly resolved reference') }) t.it('Author/Book #2', async t => { const SomeSchema = Schema.new({ name : 'Cool data schema' }) const entity = SomeSchema.getEntityDecorator() @entity class Author extends Entity.mix(Base) { @bucket() books : Set<Book> } @entity class Book extends Entity.mix(Base) { @reference({ bucket : 'books' }) writtenBy : Author } const replica1 = Replica.new({ schema : SomeSchema }) const markTwain = Author.new() const markTwain2 = Author.new() const tomSoyer = Book.new({ writtenBy : markTwain }) replica1.addEntities([ markTwain, markTwain2, tomSoyer ]) //-------------------- replica1.commit() t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly resolved reference') t.isDeeply(markTwain2.books, new Set(), 'Correctly resolved reference') t.isDeeply(tomSoyer.writtenBy, markTwain, 'Correct reference value') //-------------------- tomSoyer.writtenBy = markTwain2 // overwrite previous write tomSoyer.writtenBy = markTwain replica1.commit() t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly resolved reference') t.isDeeply(markTwain2.books, new Set(), 'Correctly resolved reference') t.isDeeply(tomSoyer.writtenBy, markTwain, 'Correct reference value') //-------------------- tomSoyer.writtenBy = markTwain2 // remove modified reference replica1.removeEntity(tomSoyer) replica1.commit() t.isDeeply(markTwain.books, new Set(), 'Correctly resolved reference') t.isDeeply(markTwain2.books, new Set(), 'Correctly resolved reference') }) t.it('TreeNode', async t => { const SomeSchema = Schema.new({ name : 'Cool data schema' }) const entity = SomeSchema.getEntityDecorator() @entity class TreeNode extends Entity.mix(Base) { @bucket() children : Set<TreeNode> @reference({ bucket : 'children'}) parent : TreeNode } const replica1 = Replica.new({ schema : SomeSchema }) const node1 = TreeNode.new() const node2 = TreeNode.new({ parent : node1 }) const node3 = TreeNode.new({ parent : node1 }) const node4 = TreeNode.new({ parent : node2 }) replica1.addEntities([ node1, node2, node3, node4 ]) replica1.commit() t.isDeeply(node1.children, new Set([ node2, node3 ]), 'Correctly resolved `children` reference') t.isDeeply(node2.children, new Set([ node4 ]), 'Correctly resolved `children` reference') t.isDeeply(node3.children, new Set(), 'Correctly resolved `children` reference') t.isDeeply(node4.children, new Set(), 'Correctly resolved `children` reference') }) t.it('TreeNode w/o propagate', async t => { const SomeSchema = Schema.new({ name : 'Cool data schema' }) const entity = SomeSchema.getEntityDecorator() @entity class TreeNode extends Entity.mix(Base) { @bucket() children : Set<TreeNode> @reference({ bucket : 'children'}) parent : TreeNode } const replica1 = Replica.new({ schema : SomeSchema }) const node1 = TreeNode.new() replica1.addEntity(node1) // early read to fill the bucket quark with value which needs to be overriden after adding other nodes t.isDeeply(node1.children, new Set([]), 'Correctly resolved `children` reference') const node2 = TreeNode.new({ parent : node1 }) const node3 = TreeNode.new({ parent : node1 }) const node4 = TreeNode.new({ parent : node2 }) replica1.addEntities([ node2, node3, node4 ]) t.isDeeply(node1.children, new Set([ node2, node3 ]), 'Correctly resolved `children` reference') t.isDeeply(node2.children, new Set([ node4 ]), 'Correctly resolved `children` reference') t.isDeeply(node3.children, new Set(), 'Correctly resolved `children` reference') t.isDeeply(node4.children, new Set(), 'Correctly resolved `children` reference') }) t.it('Resolver for reference should work', async t => { const authors = new Map<string, Author>() class Author extends Entity.mix(Base) { id : string @bucket() books : Set<Book> initialize () { super.initialize(...arguments) authors.set(this.id, this) } } class Book extends Entity.mix(Base) { @reference({ bucket : 'books', resolver : locator => authors.get(locator) }) writtenBy : Author | string @field() someField : number } //------------------ const replica = Replica.new() const markTwain = Author.new({ id : 'markTwain'}) const tomSoyer = Book.new({ writtenBy : 'markTwain' }) replica.addEntity(markTwain) replica.addEntity(tomSoyer) //------------------ const spy = t.spyOn(tomSoyer.$.writtenBy, 'calculation') replica.commit() t.isDeeply(markTwain.books, new Set([ tomSoyer ]), 'Correctly resolved reference') t.is(tomSoyer.writtenBy, markTwain, 'Correctly resolved reference') //------------------ spy.reset() tomSoyer.someField = 11 replica.commit() // the reference should be resolved at the proposed value stage, to not be recalculated again t.expect(spy).toHaveBeenCalled(0) }) t.it('Reference with resolver, without bucket', async t => { const authors = new Map<string, Author>() class Author extends Entity.mix(Base) { id : string initialize () { super.initialize(...arguments) authors.set(this.id, this) } } class Book extends Entity.mix(Base) { @reference({ resolver : locator => authors.get(locator) }) writtenBy : Author | string } const replica = Replica.new() const markTwain = Author.new({ id : 'markTwain'}) const tomSoyer = Book.new({ writtenBy : 'markTwain' }) replica.addEntity(markTwain) replica.addEntity(tomSoyer) replica.commit() t.is(tomSoyer.writtenBy, markTwain, 'Correctly resolved reference') }) t.it('Mutual references with resolvers should work', async t => { const dictionary1 = new Map<string, Entity1>() const dictionary2 = new Map<string, Entity2>() class Entity1 extends Entity.mix(Base) { id : string @bucket() referencedFromEntity2 : Set<Entity2> @reference({ bucket : 'referencedFromEntity1', resolver : locator => dictionary2.get(locator) }) referencingEntity2 : Entity2 | string initialize () { super.initialize(...arguments) dictionary1.set(this.id, this) } } class Entity2 extends Entity.mix(Base) { id : string @bucket() referencedFromEntity1 : Set<Entity2> @reference({ bucket : 'referencedFromEntity2', resolver : locator => dictionary1.get(locator) }) referencingEntity1 : Entity1 | string initialize () { super.initialize(...arguments) dictionary2.set(this.id, this) } } const replica = Replica.new() const entity1 = Entity1.new({ id : 'entity1', referencingEntity2 : 'entity2' }) const entity2 = Entity2.new({ id : 'entity2', referencingEntity1 : 'entity1' }) replica.addEntities([ entity1, entity2 ]) replica.commit() t.isDeeply(entity1.referencingEntity2, entity2, 'Correctly resolved reference') t.isDeeply(entity2.referencingEntity1, entity1, 'Correctly resolved reference') t.isDeeply(entity1.referencedFromEntity2, new Set([ entity2 ]), 'Correctly resolved reference') t.isDeeply(entity2.referencedFromEntity1, new Set([ entity1 ]), 'Correctly resolved reference') }) t.it('Removing an added entity w/o propagation should not throw exception', async t => { const SomeSchema = Schema.new({ name : 'Cool data schema' }) const entity = SomeSchema.getEntityDecorator() @entity class Author extends Entity.mix(Base) { @bucket() books : Set<Book> } @entity class Book extends Entity.mix(Base) { @reference({ bucket : 'books' }) writtenBy : Author } const replica1 = Replica.new({ schema : SomeSchema }) const markTwain = Author.new() const tomSoyer = Book.new({ writtenBy : markTwain }) replica1.addEntity(markTwain) replica1.addEntity(tomSoyer) // no propagation here, we test that no exception is thrown replica1.removeEntity(markTwain) replica1.removeEntity(tomSoyer) t.pass('No exception thrown') }) t.it('Author/Book auto-commit', async t => { class Author extends Entity.mix(Base) { @field() firstName : string @field() lastName : string @field() fullName : string @calculate('fullName') calculateFullName () : string { return this.firstName + ' ' + this.lastName } @bucket() books : Set<Book> } class Book extends Entity.mix(Base) { @reference({ bucket : 'books' }) writtenBy : Author } const replica1 = Replica.new() const markTwain = Author.new() const tomSoyer = Book.new({ writtenBy : markTwain }) t.is(replica1.hasPendingAutoCommit(), false, 'No pending commit') t.is(replica1.dirty, false, 'Replica is clean') replica1.addEntity(markTwain) t.is(replica1.hasPendingAutoCommit(), true, 'Pending commit after entity addition') t.is(replica1.dirty, true, 'Replica is dirty after adding an entity') replica1.addEntity(tomSoyer) await t.waitFor(() => !replica1.dirty) t.is(replica1.hasPendingAutoCommit(), false, 'No pending commit') //-------------------- tomSoyer.writtenBy = null t.is(replica1.hasPendingAutoCommit(), true, 'Pending commit') t.is(replica1.dirty, true, 'Replica is dirty') await t.waitFor(() => !replica1.dirty) t.is(replica1.hasPendingAutoCommit(), false, 'No pending commit') t.isDeeply(markTwain.books, new Set(), 'Correctly resolved reference') //-------------------- replica1.removeEntity(tomSoyer) t.is(replica1.hasPendingAutoCommit(), true, 'Pending commit') t.is(replica1.dirty, true, 'Replica is dirty') await t.waitFor(() => !replica1.dirty) t.is(replica1.hasPendingAutoCommit(), false, 'No pending commit') }) })
the_stack
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentRef, ElementRef, EventEmitter, Inject, InjectionToken, Input, NgZone, OnDestroy, OnInit, Optional, Output, ViewChild, ViewContainerRef, ViewEncapsulation, } from '@angular/core'; import { Directionality } from '@angular/cdk/bidi'; import { BooleanInput, coerceBooleanProperty, coerceStringArray } from '@angular/cdk/coercion'; import { ESCAPE, hasModifierKey, UP_ARROW } from '@angular/cdk/keycodes'; import { FlexibleConnectedPositionStrategy, Overlay, OverlayConfig, OverlayRef, ScrollStrategy, } from '@angular/cdk/overlay'; import { ComponentPortal } from '@angular/cdk/portal'; import { _getFocusedElementPierceShadowDom } from '@angular/cdk/platform'; import { CanColor, mixinColor, ThemePalette } from '@angular/material/core'; import { merge, Subject, Subscription } from 'rxjs'; import { filter, take } from 'rxjs/operators'; import { DatetimeAdapter } from '@ng-matero/extensions/core'; import { MtxCalendarView, MtxCalendar } from './calendar'; import { createMissingDateImplError } from './datetimepicker-errors'; import { MtxDatetimepickerFilterType } from './datetimepicker-filtertype'; import { MtxDatetimepickerInput } from './datetimepicker-input'; import { mtxDatetimepickerAnimations } from './datetimepicker-animations'; import { MtxDatetimepickerType } from './datetimepicker-types'; /** Used to generate a unique ID for each datetimepicker instance. */ let datetimepickerUid = 0; export type MtxDatetimepickerMode = 'auto' | 'portrait' | 'landscape'; /** Possible positions for the colorpicker dropdown along the X axis. */ export type DatetimepickerDropdownPositionX = 'start' | 'end'; /** Possible positions for the colorpicker dropdown along the Y axis. */ export type DatetimepickerDropdownPositionY = 'above' | 'below'; /** Injection token that determines the scroll handling while the calendar is open. */ export const MTX_DATETIMEPICKER_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>( 'mtx-datetimepicker-scroll-strategy' ); export function MTX_DATETIMEPICKER_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy { return () => overlay.scrollStrategies.reposition(); } export const MTX_DATETIMEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER = { provide: MTX_DATETIMEPICKER_SCROLL_STRATEGY, deps: [Overlay], useFactory: MTX_DATETIMEPICKER_SCROLL_STRATEGY_FACTORY, }; // Boilerplate for applying mixins to MtxDatetimepickerContent. /** @docs-private */ const _MtxDatetimepickerContentBase = mixinColor( class { constructor(public _elementRef: ElementRef) {} } ); /** * Component used as the content for the datetimepicker dialog and popup. We use this instead of * using MtxCalendar directly as the content so we can control the initial focus. This also gives us * a place to put additional features of the popup that are not part of the calendar itself in the * future. (e.g. confirmation buttons). * @docs-private */ @Component({ selector: 'mtx-datetimepicker-content', templateUrl: 'datetimepicker-content.html', styleUrls: ['datetimepicker-content.scss'], host: { 'class': 'mtx-datetimepicker-content', '[class.mtx-datetimepicker-content-touch]': 'datetimepicker?.touchUi', '[attr.mode]': 'datetimepicker.mode', '[@transformPanel]': '_animationState', '(@transformPanel.done)': '_animationDone.next()', }, animations: [ mtxDatetimepickerAnimations.transformPanel, mtxDatetimepickerAnimations.fadeInCalendar, ], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, inputs: ['color'], }) export class MtxDatetimepickerContent<D> extends _MtxDatetimepickerContentBase implements OnInit, AfterContentInit, OnDestroy, CanColor { @ViewChild(MtxCalendar, { static: true }) _calendar!: MtxCalendar<D>; datetimepicker!: MtxDatetimepicker<D>; /** Whether the datetimepicker is above or below the input. */ _isAbove!: boolean; /** Current state of the animation. */ _animationState!: 'enter-dropdown' | 'enter-dialog' | 'void'; /** Emits when an animation has finished. */ readonly _animationDone = new Subject<void>(); constructor(elementRef: ElementRef, private _changeDetectorRef: ChangeDetectorRef) { super(elementRef); } ngOnInit() { this._animationState = this.datetimepicker.touchUi ? 'enter-dialog' : 'enter-dropdown'; } ngAfterContentInit() { this._calendar._focusActiveCell(); } _startExitAnimation() { this._animationState = 'void'; this._changeDetectorRef.markForCheck(); } ngOnDestroy() { this._animationDone.complete(); } } @Component({ selector: 'mtx-datetimepicker', exportAs: 'mtxDatetimepicker', template: '', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, }) export class MtxDatetimepicker<D> implements OnDestroy { /** Active multi year view when click on year. */ @Input() get multiYearSelector(): boolean { return this._multiYearSelector; } set multiYearSelector(value: boolean) { this._multiYearSelector = coerceBooleanProperty(value); } private _multiYearSelector = false; /** if true change the clock to 12 hour format. */ @Input() get twelvehour(): boolean { return this._twelvehour; } set twelvehour(value: boolean) { this._twelvehour = coerceBooleanProperty(value); } private _twelvehour = false; /** The view that the calendar should start in. */ @Input() startView: MtxCalendarView = 'month'; @Input() mode: MtxDatetimepickerMode = 'auto'; @Input() timeInterval: number = 1; /** Prevent user to select same date time */ @Input() preventSameDateTimeSelection = false; /** * Emits new selected date when selected date changes. * @deprecated Switch to the `dateChange` and `dateInput` binding on the input element. */ @Output() selectedChanged = new EventEmitter<D>(); /** Emits when the datetimepicker has been opened. */ @Output('opened') openedStream: EventEmitter<void> = new EventEmitter<void>(); /** Emits when the datetimepicker has been closed. */ @Output('closed') closedStream: EventEmitter<void> = new EventEmitter<void>(); /** Emits when the view has been changed. */ @Output() viewChanged: EventEmitter<MtxCalendarView> = new EventEmitter<MtxCalendarView>(); /** * Classes to be passed to the date picker panel. * Supports string and string array values, similar to `ngClass`. */ @Input() get panelClass(): string | string[] { return this._panelClass; } set panelClass(value: string | string[]) { this._panelClass = coerceStringArray(value); } private _panelClass!: string[]; /** Whether the calendar is open. */ @Input() get opened(): boolean { return this._opened; } set opened(value: boolean) { coerceBooleanProperty(value) ? this.open() : this.close(); } private _opened = false; /** The id for the datetimepicker calendar. */ id = `mtx-datetimepicker-${datetimepickerUid++}`; /** Color palette to use on the datetimepicker's calendar. */ @Input() get color(): ThemePalette { return ( this._color || (this.datetimepickerInput ? this.datetimepickerInput.getThemePalette() : undefined) ); } set color(value: ThemePalette) { this._color = value; } private _color: ThemePalette; /** The input element this datetimepicker is associated with. */ datetimepickerInput!: MtxDatetimepickerInput<D>; /** Emits when the datetimepicker is disabled. */ _disabledChange = new Subject<boolean>(); private _validSelected: D | null = null; /** A reference to the overlay into which we've rendered the calendar. */ private _overlayRef!: OverlayRef | null; /** Reference to the component instance rendered in the overlay. */ private _componentRef!: ComponentRef<MtxDatetimepickerContent<D>> | null; /** The element that was focused before the datetimepicker was opened. */ private _focusedElementBeforeOpen: HTMLElement | null = null; /** Unique class that will be added to the backdrop so that the test harnesses can look it up. */ private _backdropHarnessClass = `${this.id}-backdrop`; private _inputStateChanges = Subscription.EMPTY; constructor( private _overlay: Overlay, private _ngZone: NgZone, private _viewContainerRef: ViewContainerRef, @Inject(MTX_DATETIMEPICKER_SCROLL_STRATEGY) private _scrollStrategy: any, @Optional() private _dateAdapter: DatetimeAdapter<D>, @Optional() private _dir: Directionality ) { if (!this._dateAdapter) { throw createMissingDateImplError('DateAdapter'); } } /** The date to open the calendar to initially. */ @Input() get startAt(): D | null { // If an explicit startAt is set we start there, otherwise we start at whatever the currently // selected value is. return this._startAt || (this.datetimepickerInput ? this.datetimepickerInput.value : null); } set startAt(date: D | null) { this._startAt = this._dateAdapter.getValidDateOrNull(date); } private _startAt!: D | null; @Input() get type() { return this._type; } set type(value: MtxDatetimepickerType) { this._type = value || 'date'; } private _type: MtxDatetimepickerType = 'date'; /** * Whether the calendar UI is in touch mode. In touch mode the calendar opens in a dialog rather * than a popup and elements have more padding to allow for bigger touch targets. */ @Input() get touchUi(): boolean { return this._touchUi; } set touchUi(value: boolean) { this._touchUi = coerceBooleanProperty(value); } private _touchUi = false; /** Whether the datetimepicker pop-up should be disabled. */ @Input() get disabled(): boolean { return this._disabled === undefined && this.datetimepickerInput ? this.datetimepickerInput.disabled : !!this._disabled; } set disabled(value: boolean) { const newValue = coerceBooleanProperty(value); if (newValue !== this._disabled) { this._disabled = newValue; this._disabledChange.next(newValue); } } private _disabled!: boolean; /** Preferred position of the datetimepicker in the X axis. */ @Input() xPosition: DatetimepickerDropdownPositionX = 'start'; /** Preferred position of the datetimepicker in the Y axis. */ @Input() yPosition: DatetimepickerDropdownPositionY = 'below'; /** * Whether to restore focus to the previously-focused element when the panel is closed. * Note that automatic focus restoration is an accessibility feature and it is recommended that * you provide your own equivalent, if you decide to turn it off. */ @Input() get restoreFocus(): boolean { return this._restoreFocus; } set restoreFocus(value: boolean) { this._restoreFocus = coerceBooleanProperty(value); } private _restoreFocus = true; /** The currently selected date. */ get _selected(): D | null { return this._validSelected; } set _selected(value: D | null) { this._validSelected = value; } /** The minimum selectable date. */ get _minDate(): D | null { return this.datetimepickerInput && this.datetimepickerInput.min; } /** The maximum selectable date. */ get _maxDate(): D | null { return this.datetimepickerInput && this.datetimepickerInput.max; } get _dateFilter(): (date: D | null, type: MtxDatetimepickerFilterType) => boolean { return this.datetimepickerInput && this.datetimepickerInput._dateFilter; } _viewChanged(type: MtxCalendarView): void { this.viewChanged.emit(type); } ngOnDestroy() { this._destroyOverlay(); this.close(); this._inputStateChanges.unsubscribe(); this._disabledChange.complete(); } /** Selects the given date */ _select(date: D): void { const oldValue = this._selected; this._selected = date; if (!this._dateAdapter.sameDatetime(oldValue, this._selected)) { this.selectedChanged.emit(date); } } /** * Register an input with this datetimepicker. * @param input The datetimepicker input to register with this datetimepicker. */ _registerInput(input: MtxDatetimepickerInput<D>): void { if (this.datetimepickerInput) { throw Error('A MtxDatetimepicker can only be associated with a single input.'); } this.datetimepickerInput = input; this._inputStateChanges = this.datetimepickerInput._valueChange.subscribe( (value: D | null) => (this._selected = value) ); } /** Open the calendar. */ open(): void { if (this._opened || this.disabled) { return; } if (!this.datetimepickerInput) { throw Error('Attempted to open an MtxDatetimepicker with no associated input.'); } this._focusedElementBeforeOpen = _getFocusedElementPierceShadowDom(); this._openOverlay(); this._opened = true; this.openedStream.emit(); } /** Close the calendar. */ close(): void { if (!this._opened) { return; } if (this._componentRef) { this._destroyOverlay(); } const completeClose = () => { // The `_opened` could've been reset already if // we got two events in quick succession. if (this._opened) { this._opened = false; this.closedStream.emit(); this._focusedElementBeforeOpen = null; } }; if ( this._restoreFocus && this._focusedElementBeforeOpen && typeof this._focusedElementBeforeOpen.focus === 'function' ) { // Because IE moves focus asynchronously, we can't count on it being restored before we've // marked the datetimepicker as closed. If the event fires out of sequence and the element // that we're refocusing opens the datetimepicker on focus, the user could be stuck with not // being able to close the calendar at all. We work around it by making the logic, that marks // the datetimepicker as closed, async as well. this._focusedElementBeforeOpen.focus(); setTimeout(completeClose); } else { completeClose(); } } /** * Forwards relevant values from the datetimepicker to the * datetimepicker content inside the overlay. */ protected _forwardContentValues(instance: MtxDatetimepickerContent<D>) { instance.datetimepicker = this; instance.color = this.color; } /** Opens the overlay with the calendar. */ private _openOverlay(): void { this._destroyOverlay(); const isDialog = this.touchUi; const labelId = this.datetimepickerInput.getOverlayLabelId(); const portal = new ComponentPortal<MtxDatetimepickerContent<D>>( MtxDatetimepickerContent, this._viewContainerRef ); const overlayRef = (this._overlayRef = this._overlay.create( new OverlayConfig({ positionStrategy: isDialog ? this._getDialogStrategy() : this._getDropdownStrategy(), hasBackdrop: true, backdropClass: [ isDialog ? 'cdk-overlay-dark-backdrop' : 'mat-overlay-transparent-backdrop', this._backdropHarnessClass, ], direction: this._dir, scrollStrategy: isDialog ? this._overlay.scrollStrategies.block() : this._scrollStrategy(), panelClass: `mtx-datetimepicker-${isDialog ? 'dialog' : 'popup'}`, }) )); const overlayElement = overlayRef.overlayElement; overlayElement.setAttribute('role', 'dialog'); if (labelId) { overlayElement.setAttribute('aria-labelledby', labelId); } if (isDialog) { overlayElement.setAttribute('aria-modal', 'true'); } this._getCloseStream(overlayRef).subscribe(event => { if (event) { event.preventDefault(); } this.close(); }); this._componentRef = overlayRef.attach(portal); this._forwardContentValues(this._componentRef.instance); // Update the position once the calendar has rendered. Only relevant in dropdown mode. if (!isDialog) { this._ngZone.onStable.pipe(take(1)).subscribe(() => overlayRef.updatePosition()); } } /** Destroys the current overlay. */ private _destroyOverlay() { if (this._overlayRef) { this._overlayRef.dispose(); this._overlayRef = this._componentRef = null; } } /** Gets a position strategy that will open the calendar as a dropdown. */ private _getDialogStrategy() { return this._overlay.position().global().centerHorizontally().centerVertically(); } /** Gets a position strategy that will open the calendar as a dropdown. */ private _getDropdownStrategy() { const strategy = this._overlay .position() .flexibleConnectedTo(this.datetimepickerInput.getConnectedOverlayOrigin()) .withTransformOriginOn('.mtx-datetimepicker-content') .withFlexibleDimensions(false) .withViewportMargin(8) .withLockedPosition(); return this._setConnectedPositions(strategy); } /** * Sets the positions of the datetimepicker in dropdown mode based on the current configuration. */ private _setConnectedPositions(strategy: FlexibleConnectedPositionStrategy) { const primaryX = this.xPosition === 'end' ? 'end' : 'start'; const secondaryX = primaryX === 'start' ? 'end' : 'start'; const primaryY = this.yPosition === 'above' ? 'bottom' : 'top'; const secondaryY = primaryY === 'top' ? 'bottom' : 'top'; return strategy.withPositions([ { originX: primaryX, originY: secondaryY, overlayX: primaryX, overlayY: primaryY, }, { originX: primaryX, originY: primaryY, overlayX: primaryX, overlayY: secondaryY, }, { originX: secondaryX, originY: secondaryY, overlayX: secondaryX, overlayY: primaryY, }, { originX: secondaryX, originY: primaryY, overlayX: secondaryX, overlayY: secondaryY, }, ]); } /** Gets an observable that will emit when the overlay is supposed to be closed. */ private _getCloseStream(overlayRef: OverlayRef) { return merge( overlayRef.backdropClick(), overlayRef.detachments(), overlayRef.keydownEvents().pipe( filter(event => { // Closing on alt + up is only valid when there's an input associated with the datetimepicker. return ( (event.keyCode === ESCAPE && !hasModifierKey(event)) || (this.datetimepickerInput && hasModifierKey(event, 'altKey') && event.keyCode === UP_ARROW) ); }) ) ); } static ngAcceptInputType_multiYearSelector: BooleanInput; static ngAcceptInputType_twelvehour: BooleanInput; static ngAcceptInputType_preventSameDateTimeSelection: BooleanInput; static ngAcceptInputType_disabled: BooleanInput; static ngAcceptInputType_opened: BooleanInput; static ngAcceptInputType_touchUi: BooleanInput; static ngAcceptInputType_restoreFocus: BooleanInput; }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { ConnectorModel } from '../../../src/diagram/objects/connector-model'; import { NodeModel } from '../../../src/diagram/objects/node-model'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; /** * SpacingOptions Spec */ describe('SpacingOptions Commands', () => { describe('Nodes with SpacingOptions RightToLeft', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let connector: ConnectorModel = { id: 'connector1', sourcePoint: { x: 600, y: 100 }, targetPoint: { x: 800, y: 100 } }; let node: NodeModel = { id: 'node1', width: 200, height: 100, offsetX: 200, offsetY: 200, annotations: [{ content: 'Node1', style: { strokeColor: 'black', opacity: 1 } }] }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Node2', style: { strokeColor: 'black', opacity: 1 } }] }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 100, annotations: [{ content: 'Node3', style: { strokeColor: 'black', opacity: 1 } }] }; diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node, node2, node3], connectors: [connector] }); diagram.appendTo('#diagram'); let objects: (NodeModel | ConnectorModel)[] = []; objects.push(diagram.nodes[0], diagram.nodes[1], diagram.nodes[2], diagram.connectors[0]); diagram.distribute('RightToLeft', objects); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation', (done: Function) => { expect((diagram.nodes[0].offsetX === 300 && diagram.nodes[0].offsetY === 200) && (diagram.nodes[1].offsetX === 100 && diagram.nodes[1].offsetY === 100) && (diagram.nodes[2].offsetX === 500 && diagram.nodes[2].offsetY === 100) && (diagram.connectors[0].sourcePoint.x === 600 && diagram.connectors[0].sourcePoint.y === 100) && (diagram.connectors[0].targetPoint.x === 800 && diagram.connectors[0].targetPoint.y === 100)).toBe(true); done(); }); }); describe('Nodes with SpacingOptions Right', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram1' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 200, height: 100, offsetX: 200, offsetY: 200, annotations: [{ content: 'Node1', style: { strokeColor: 'black', opacity: 1 } }] }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Node2', style: { strokeColor: 'black', opacity: 1 } }] }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 100, annotations: [{ content: 'Node3', style: { strokeColor: 'black', opacity: 1 } }] }; diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node, node2, node3] }); diagram.appendTo('#diagram1'); let objects: (NodeModel | ConnectorModel)[] = []; objects.push(diagram.nodes[0], diagram.nodes[1], diagram.nodes[2]); diagram.distribute('Right', objects); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation', (done: Function) => { expect((diagram.nodes[0].offsetX === 250 && diagram.nodes[0].offsetY === 200) && (diagram.nodes[1].offsetX === 100 && diagram.nodes[1].offsetY === 100) && (diagram.nodes[2].offsetX === 500 && diagram.nodes[2].offsetY === 100)).toBe(true); done(); }); }); describe('Nodes with SpacingOptions Left', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram2' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 200, height: 100, offsetX: 300, offsetY: 200, annotations: [{ content: 'Node1', style: { strokeColor: 'black', opacity: 1 } }] }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Node2', style: { strokeColor: 'black', opacity: 1 } }] }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 100, annotations: [{ content: 'Node3', style: { strokeColor: 'black', opacity: 1 } }] }; diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node, node2, node3] }); diagram.appendTo('#diagram2'); let objects: (NodeModel | ConnectorModel)[] = []; objects.push(diagram.nodes[0], diagram.nodes[1], diagram.nodes[2]); diagram.distribute('Left', objects); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation', (done: Function) => { expect((diagram.nodes[0].offsetX === 350 && diagram.nodes[0].offsetY === 200) && (diagram.nodes[1].offsetX === 100 && diagram.nodes[1].offsetY === 100) && (diagram.nodes[2].offsetX === 500 && diagram.nodes[2].offsetY === 100)).toBe(true); done(); }); }); describe('Nodes with SpacingOptions Center', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram3' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 200, height: 100, offsetX: 200, offsetY: 200, annotations: [{ content: 'Node1', style: { strokeColor: 'black', opacity: 1 } }] }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Node2', style: { strokeColor: 'black', opacity: 1 } }] }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 100, annotations: [{ content: 'Node3', style: { strokeColor: 'black', opacity: 1 } }] }; diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node, node2, node3] }); diagram.appendTo('#diagram3'); let objects: (NodeModel | ConnectorModel)[] = []; objects.push(diagram.nodes[0], diagram.nodes[1], diagram.nodes[2]); diagram.distribute('Center', objects); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation', (done: Function) => { expect((diagram.nodes[0].offsetX === 300 && diagram.nodes[0].offsetY === 200) && (diagram.nodes[1].offsetX === 100 && diagram.nodes[1].offsetY === 100) && (diagram.nodes[2].offsetX === 500 && diagram.nodes[2].offsetY === 100)).toBe(true); done(); }); }); describe('Nodes with SpacingOptions BottomToTop', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram4' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 200, height: 100, offsetX: 200, offsetY: 200, annotations: [{ content: 'Node1', style: { strokeColor: 'black', opacity: 1 } }] }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Node2', style: { strokeColor: 'black', opacity: 1 } }] }; let connector: ConnectorModel = { id: 'connector1', sourcePoint: { x: 250, y: 300 }, targetPoint: { x: 400, y: 300 } }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 500, annotations: [{ content: 'Node3', style: { strokeColor: 'black', opacity: 1 } }] }; diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node, node2, node3], connectors: [connector] }); diagram.appendTo('#diagram4'); let objects: (NodeModel | ConnectorModel)[] = []; objects.push(diagram.nodes[0], diagram.nodes[1], diagram.nodes[2], diagram.connectors[0]); diagram.distribute('Middle', objects); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation', (done: Function) => { expect((diagram.nodes[1].offsetX === 100 && diagram.nodes[1].offsetY === 100) && (diagram.nodes[2].offsetX === 500 && diagram.nodes[2].offsetY === 500) && (Math.round(diagram.nodes[0].offsetX) === 200 && Math.round(diagram.nodes[0].offsetY) === 367) && (diagram.connectors[0].sourcePoint.x === 250 && Math.round(diagram.connectors[0].sourcePoint.y) === 233) && (diagram.connectors[0].targetPoint.x === 400 && Math.round(diagram.connectors[0].targetPoint.y) === 233)).toBe(true); done(); }); }); describe('Nodes with SpacingOptions Top', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram5' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Node1', style: { strokeColor: 'black', opacity: 1 } }] }; let connector: ConnectorModel = { id: 'connector1', sourcePoint: { x: 100, y: 200 }, targetPoint: { x: 200, y: 300 }, type: 'Orthogonal' }; let node2: NodeModel = { id: 'node2', width: 100, height: 150, offsetX: 300, offsetY: 400, annotations: [{ content: 'Node2', style: { strokeColor: 'black', opacity: 1 } }] }; diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node, node2], connectors: [connector] }); diagram.appendTo('#diagram5'); let objects: (NodeModel | ConnectorModel)[] = []; objects.push(diagram.nodes[0], diagram.nodes[1], diagram.connectors[0]); diagram.distribute('Top', objects); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation', (done: Function) => { expect((diagram.nodes[0].offsetX === 100 && diagram.nodes[0].offsetY === 100) && (diagram.nodes[1].offsetX === 300 && diagram.nodes[1].offsetY === 400) && (diagram.connectors[0].sourcePoint.x === 100 && diagram.connectors[0].sourcePoint.y === 187.5) && (diagram.connectors[0].targetPoint.x === 200 && diagram.connectors[0].targetPoint.y === 287.5)).toBe(true); done(); }); }); describe('Nodes with SpacingOptions Bottom', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram6' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Node1', style: { strokeColor: 'black', opacity: 1 } }] }; let connector: ConnectorModel = { id: 'connector1', sourcePoint: { x: 100, y: 200 }, targetPoint: { x: 200, y: 300 }, type: 'Orthogonal' }; let node2: NodeModel = { id: 'node2', width: 100, height: 150, offsetX: 300, offsetY: 400, annotations: [{ content: 'Node2', style: { strokeColor: 'black', opacity: 1 } }] }; diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node, node2], connectors: [connector] }); diagram.appendTo('#diagram6'); let objects: (NodeModel | ConnectorModel)[] = []; objects.push(diagram.nodes[0], diagram.nodes[1], diagram.connectors[0]); diagram.distribute('Bottom', objects); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation', (done: Function) => { expect((diagram.nodes[0].offsetX === 100 && diagram.nodes[0].offsetY === 100) && (diagram.nodes[1].offsetX === 300 && diagram.nodes[1].offsetY === 400) && (diagram.connectors[0].sourcePoint.x === 100 && diagram.connectors[0].sourcePoint.y === 212.5) && (diagram.connectors[0].targetPoint.x === 200 && diagram.connectors[0].targetPoint.y === 312.5)).toBe(true); done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); describe('Nodes with SpacingOptions Default', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram6' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Node1', style: { strokeColor: 'black', opacity: 1 } }] }; let connector: ConnectorModel = { id: 'connector1', sourcePoint: { x: 100, y: 200 }, targetPoint: { x: 200, y: 300 }, type: 'Orthogonal' }; let node2: NodeModel = { id: 'node2', width: 100, height: 150, offsetX: 300, offsetY: 400, annotations: [{ content: 'Node2', style: { strokeColor: 'black', opacity: 1 } }] }; diagram = new Diagram({ width: '1000px', height: '1000px', nodes: [node, node2], connectors: [connector] }); diagram.appendTo('#diagram6'); let objects: (NodeModel | ConnectorModel)[] = []; objects.push(diagram.nodes[0], diagram.nodes[1], diagram.connectors[0]); diagram.distribute('BottomToTop', objects); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation', (done: Function) => { expect((diagram.nodes[0].offsetX === 100 && diagram.nodes[0].offsetY === 100) && (diagram.nodes[1].offsetX === 300 && diagram.nodes[1].offsetY === 400) && (diagram.connectors[0].sourcePoint.x === 100 && diagram.connectors[0].sourcePoint.y === 212.5) && (diagram.connectors[0].targetPoint.x === 200 && diagram.connectors[0].targetPoint.y === 312.5)).toBe(true); done(); }); }); });
the_stack
import React, { useState, useEffect, useReducer } from 'react'; import styles from './SpFxAlm.module.scss'; import { ISpFxAlmProps } from './ISpFxAlmProps'; import { escape } from '@microsoft/sp-lodash-subset'; import { PrimaryButton } from 'office-ui-fabric-react/lib/Button'; import HttpService from './service'; import { Label, ILabelStyles } from 'office-ui-fabric-react/lib/Label'; import { Pivot, PivotItem } from 'office-ui-fabric-react/lib/Pivot'; import { IStyleSet } from 'office-ui-fabric-react/lib/Styling'; import { css } from "@uifabric/utilities/lib/css"; import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog'; import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner'; import { Dropdown, IDropdownStyles, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { Toggle } from 'office-ui-fabric-react/lib/Toggle'; export default function SpFxAlm(props: ISpFxAlmProps) { const [isSiteAppCatalog, setSiteAppCatalog] = useState(false); const [file, setFile] = useState(null); const [hideDialog, hideDialogBox] = useState(true); const [operationInfo, setMessage] = useState(""); const [operationCompleted, setoperationStatus] = useState(false); const [siteURL, setSiteURL] = useState(""); const [allSiteURL, setAllSiteURL] = useState([]); const [tentantAppURL, setTenantAppURL] = useState(""); const [allSPFxApps, setAllApps] = useState([]); const [appID, setAppID] = useState(null); const [showaddremoveError, setShowUploadError] = useState({ addAppSelectSiteErr: false, addAppSelectAppErr: false, uploadAppSelectAppErr: false }); const [showDeployRetractError, setShoweployRetractError] = useState({ deployAppSelectSiteErr: false, deployAppSelectAppErr: false }); const [showunInstallError, setshowunInstallError] = useState({ appinstallSelectSiteErr: false, appinstallSelectAppErr: false }); const labelStyles: Partial<IStyleSet<ILabelStyles>> = { root: { marginTop: 0 } }; const dropdownStyles: Partial<IDropdownStyles> = { dropdown: { width: 300 } }; useEffect(() => { loadPrereqs(); }, [siteURL, isSiteAppCatalog, appID]); return ( <div className={styles.spFxAlm} > <div className={styles.container}> <div className={css(styles.row, styles.customBorder)}> <div style={{ display: 'flex' }} > <Pivot style={{ width: '100%' }} aria-label="Basic Pivot Example"> <PivotItem headerText="Add or Remove App" headerButtonProps={{ 'data-order': 1, 'data-title': 'My Files Title' }} > <div className={styles.row}> {isSiteAppCatalog && <Dropdown placeholder="Select a site" label="Select a site to perform the activity" options={allSiteURL} styles={{ dropdown: { width: '100%' }, root: { height: 100 } }} onChange={_onSiteChange} defaultSelectedKey={siteURL} errorMessage={showaddremoveError.addAppSelectSiteErr ? 'Select Site' : undefined} />} <Dropdown placeholder="Select an app" label="Select an app to perform the activity" options={allSPFxApps} styles={{ dropdown: { width: '100%' }, root: { height: 100 } }} onChange={_onAppChange} defaultSelectedKey={appID} errorMessage={showaddremoveError.addAppSelectAppErr ? 'Select an App' : undefined} /> <div className='ms-Grid-col ms-u-sm6'> <Label styles={labelStyles}>Upload solution package</Label> </div> <div className='ms-Grid-col ms-u-sm6'> <input type='file' id='file' onChange={(e) => handleChange(e.target.files, e)} required accept='.sppkg' /> {showaddremoveError.uploadAppSelectAppErr && <div className={styles.errorMessage}>.sppkg file is required</div>} </div> </div> <div className={styles.row}> <PrimaryButton text='Add an app' onClick={() => { addanApp() }} /> &nbsp; <PrimaryButton text='Remove App' onClick={() => { removeApp() }} ></PrimaryButton> </div> </PivotItem> <PivotItem headerText="Deploy or Retract App"> <div className={styles.row}> {isSiteAppCatalog && <Dropdown placeholder="Select a site" label="Select a site to perform the activity" options={allSiteURL} styles={{ dropdown: { width: '100%' }, root: { height: 100 } }} onChange={_onSiteChange} defaultSelectedKey={siteURL} errorMessage={showDeployRetractError.deployAppSelectSiteErr ? 'Select Site' : undefined} />} <Dropdown placeholder="Select an app" label="Select an app to perform the activity" options={allSPFxApps} styles={{ dropdown: { width: '100%' }, root: { height: 100 } }} onChange={_onAppChange} defaultSelectedKey={appID} errorMessage={showDeployRetractError.deployAppSelectAppErr ? 'Select an App' : undefined} /> <PrimaryButton text='Deploy' onClick={() => { deployApp() }} ></PrimaryButton> &nbsp; <PrimaryButton text='Retract' onClick={() => { retractApp() }} ></PrimaryButton> </div> </PivotItem> <PivotItem headerText="Install or Uninstall App"> <div className={styles.row}> <Dropdown placeholder="Select a site" label="Select a site to perform the activity" options={allSiteURL} styles={{ dropdown: { width: '100%' }, root: { height: 100 } }} onChange={_onSiteChange} defaultSelectedKey={siteURL} errorMessage={showunInstallError.appinstallSelectSiteErr ? 'Select Site' : undefined} /> <Dropdown placeholder="Select an app" label="Select an app to perform the activity" options={allSPFxApps} styles={{ dropdown: { width: '100%' }, root: { height: 100 } }} onChange={_onAppChange} defaultSelectedKey={appID} errorMessage={showunInstallError.appinstallSelectAppErr ? 'Select an App' : undefined} /> <PrimaryButton text='Install' onClick={() => { installApp() }} ></PrimaryButton> &nbsp; <PrimaryButton text='Uninstall' onClick={() => { uninstallApp() }} ></PrimaryButton> </div> </PivotItem> </Pivot> <Toggle style={{ display: 'flex' }} label="For Site Collection App Catalog" onText="On" offText="Off" onChange={_ontoggleChange} /> </div> </div> <Dialog hidden={hideDialog} onDismiss={hideDialogWindow} dialogContentProps={{ type: DialogType.normal, title: '', subText: '' }} modalProps={{ titleAriaId: 'myLabelId', subtitleAriaId: 'mySubTextId', isBlocking: true, containerClassName: 'ms-dialogMainOverride' }} >{operationCompleted ? <span>{operationInfo}</span> : <Spinner size={SpinnerSize.large} label="Working on it..." ariaLive='assertive' />} <DialogFooter> {operationCompleted ? <PrimaryButton onClick={hideDialogWindow} text="Okay" /> : null} </DialogFooter> </Dialog> </div> </div > ); function _onAppChange(event: React.FormEvent<HTMLDivElement>, item: IDropdownOption) { setAppID(item.key); }; function _onSiteChange(event: React.FormEvent<HTMLDivElement>, item: IDropdownOption) { setSiteURL(item.text); getAllApps(); }; function _ontoggleChange(ev: React.MouseEvent<HTMLElement>, checked: boolean) { setSiteAppCatalog(checked); getAllApps(); } function hideDialogWindow() { setAppID(null); getAllApps(); hideDialogBox(true); setoperationStatus(false); } function displayDialog() { hideDialogBox(false); } function handleChange(selectorFiles: FileList, currentEvent: any) { //Add only if .sppkg file if (selectorFiles[0].name.substr(selectorFiles[0].name.length - 6).toLowerCase() === '.sppkg') { setFile(selectorFiles); } } /** * To load the prerequisite for this spfx app */ async function loadPrereqs() { const tenanAppCatalogResponse = await HttpService.GetTenantAppcatalogUrl(props.url); setTenantAppURL(tenanAppCatalogResponse.CorporateCatalogUrl); getAllSites(); getAllApps(); } /** * Get all sites present on the tenant - brings 1000 sites */ async function getAllSites() { const targetSite = isSiteAppCatalog ? siteURL : tentantAppURL; const siteDetails = await HttpService.GetAllSites(targetSite, props.rootSiteUrl); let allSiteCollectionURL: IDropdownOption[] = []; await Promise.all(siteDetails.PrimaryQueryResult.RelevantResults.Table.Rows.map((currentSite) => { allSiteCollectionURL.push({ key: currentSite.Cells[3].Value, text: currentSite.Cells[3].Value }); })); if (allSiteCollectionURL !== allSiteURL) { setAllSiteURL(allSiteCollectionURL); } } /** * Get all apps present on the tenant or site collection */ async function getAllApps() { const targetSite = isSiteAppCatalog ? siteURL : tentantAppURL; try { const appDetails = await HttpService.GetApps(targetSite, isSiteAppCatalog); let allApps: IDropdownOption[] = []; // check if appcatalog available for the site if (appDetails["error"] === undefined) { appDetails.value.map((currentappDetail) => { allApps.push({ key: currentappDetail.ID, text: currentappDetail.Title }) }); setAllApps(allApps); } else { setAllApps([]); } } catch (exception) { setMessage(exception); setAllApps([]); } } /** * To Add an app in a site collection on tenant app catalog */ async function addanApp() { try { if (validate("AddApp")) { setMessage("Working on it..."); displayDialog(); const targetSite = isSiteAppCatalog ? siteURL : tentantAppURL; await HttpService.AddanApp(file, targetSite, isSiteAppCatalog); setMessage("App added successfully !"); setoperationStatus(true); } } catch (exception) { setMessage(exception); } } /** * To remove an app from site collection or tenant app catalog */ async function removeApp() { try { if (validate("RemoveApp")) { setMessage("Working on it..."); displayDialog(); const targetSite = isSiteAppCatalog ? siteURL : tentantAppURL; await HttpService.RemoveApp(targetSite, appID, isSiteAppCatalog); setMessage("App removed successfully !"); setoperationStatus(true); } } catch (exception) { setMessage(exception); } } /** * To install an app on a site */ async function installApp() { try { if (validate("InstallApp")) { setMessage("Working on it..."); displayDialog(); const installAppResponse = await HttpService.InstallApp(siteURL, appID, isSiteAppCatalog); setMessage("App installed successfully !"); setoperationStatus(true); } } catch (exception) { setMessage(exception); } } /** * To Uninstall app from a site */ async function uninstallApp() { try { if (validate("UninstallApp")) { setMessage("Working on it..."); displayDialog(); const uninstallAppResponse = await HttpService.UninstallApp(siteURL, appID, isSiteAppCatalog); setMessage("App uninstalled successfully !"); setoperationStatus(true); } } catch (exception) { setMessage(exception); } } /** * To deploy an app on tenant or site app catalog */ async function deployApp() { try { if (validate("DeployApp")) { setMessage("Working on it..."); displayDialog(); const targetSite = isSiteAppCatalog ? siteURL : tentantAppURL; await HttpService.DeployApp(targetSite, appID, isSiteAppCatalog); setMessage("App deployed successfully !"); setoperationStatus(true); } } catch (exception) { setMessage(exception); } } /** * To retract an app from tenant or site app catalog */ async function retractApp() { try { if (validate("RetractApp")) { setMessage("Working on it..."); displayDialog(); const targetSite = isSiteAppCatalog ? siteURL : tentantAppURL; await HttpService.RetractApp(targetSite, appID, isSiteAppCatalog); setMessage("App retracted successfully !"); setoperationStatus(true); } } catch (exception) { setMessage(exception); } } /** * to validate the inputs are selected and show validations */ function validate(stage): boolean { let isActionAllowed = true; switch (stage) { case 'AddApp': if ((isSiteAppCatalog && siteURL.length === 0) || file === null) { isActionAllowed = false; } setShowUploadError({ addAppSelectSiteErr: (siteURL.length > 0) ? false : true, addAppSelectAppErr: false, uploadAppSelectAppErr: file === null ? true : false }); break; case 'RemoveApp': if ((isSiteAppCatalog && siteURL.length === 0) || appID === null) { isActionAllowed = false; } setShowUploadError({ addAppSelectSiteErr: (siteURL.length > 0) ? false : true, addAppSelectAppErr: appID === null ? true : false, uploadAppSelectAppErr: false }); break; case 'DeployApp': if ((isSiteAppCatalog && siteURL.length === 0) || appID === null) { isActionAllowed = false; } setShoweployRetractError({ deployAppSelectSiteErr: (siteURL.length > 0) ? false : true, deployAppSelectAppErr: appID === null ? true : false }); break; case 'RetractApp': if ((isSiteAppCatalog && siteURL.length === 0) || appID === null) { isActionAllowed = false; } setShoweployRetractError({ deployAppSelectSiteErr: (siteURL.length > 0) ? false : true, deployAppSelectAppErr: appID === null ? true : false }); break; case 'InstallApp': if ((isSiteAppCatalog && siteURL.length === 0) || appID === null) { isActionAllowed = false; } setshowunInstallError({ appinstallSelectSiteErr: (siteURL.length > 0) ? false : true, appinstallSelectAppErr: appID === null ? true : false }); break; case 'UninstallApp': if ((isSiteAppCatalog && siteURL.length === 0) || appID === null) { isActionAllowed = false; } setshowunInstallError({ appinstallSelectSiteErr: (siteURL.length > 0) ? false : true, appinstallSelectAppErr: appID === null ? true : false }); break; } return isActionAllowed; } }
the_stack
import * as path from 'path'; import * as os from 'os'; import { isNil, get as _get } from 'lodash'; import { SfdxError, SfdxErrorConfig, fs, Logger, Messages, SfdxProject } from '@salesforce/core'; import srcDevUtil = require('../core/srcDevUtil'); import consts = require('../core/constants'); import MdapiPackage = require('../source/mdapiPackage'); import { AggregateSourceElement } from './aggregateSourceElement'; import { MetadataTypeFactory } from './metadataTypeFactory'; import { MetadataType } from './metadataType'; import { InFolderMetadataType } from './metadataTypeImpl/inFolderMetadataType'; import { XmlLineError } from './xmlMetadataDocument'; import { NondecomposedTypesWithChildrenMetadataType } from './metadataTypeImpl/nondecomposedTypesWithChildrenMetadataType'; import { CustomLabelsMetadataType } from './metadataTypeImpl/customLabelsMetadataType'; import { SourceWorkspaceAdapter } from './sourceWorkspaceAdapter'; import { AggregateSourceElements } from './aggregateSourceElements'; import MetadataRegistry = require('./metadataRegistry'); import { RemoteSourceTrackingService } from './remoteSourceTrackingService'; Messages.importMessagesDirectory(__dirname); /** * Validate the value for the 'wait' parameter and reset it as a number. * * @param flags The command parameters (aka flags) * @param minWaitTime The minimum allowable time to wait */ export const parseWaitParam = (flags: { wait?: string }, minWaitTime: number = consts.MIN_SRC_WAIT_MINUTES) => { if (!isNil(flags.wait)) { if (srcDevUtil.isInt(flags.wait)) { const wait = (flags.wait = parseInt(flags.wait, 10) as any); // convert to a number if (wait >= minWaitTime) { return; } } const errConfig = new SfdxErrorConfig('salesforce-alm', 'source', 'mdapiCliInvalidNumericParam'); errConfig.setErrorTokens(['wait']); throw SfdxError.create(errConfig); } }; /** * Validate that the org is a non-source-tracked org. * * @param orgName The username of the org for doing the source:deploy or source:retrieve * @param errAction The action ('push' or 'pull') to take when the org is discovered to be a source tracked org. */ export const validateNonSourceTrackedOrg = async (orgName: string, errAction: string) => { if (await srcDevUtil.isSourceTrackedOrg(orgName)) { const errConfig = new SfdxErrorConfig('salesforce-alm', 'source', 'SourceTrackedOrgError'); errConfig.addAction('SourceTrackedOrgErrorAction', [errAction]); throw SfdxError.create(errConfig); } }; /** * Validate that a manifest file path exists and is readable. * * @param manifestPath The path to the manifest file (package.xml) */ export const validateManifestPath = async (manifestPath: string) => { try { await fs.access(manifestPath, fs.constants.R_OK); } catch (e) { throw SfdxError.create('salesforce-alm', 'source', 'InvalidManifestError', [manifestPath]); } }; export async function createOutputDir(cmdName: string): Promise<string> { const logger: Logger = await Logger.child('SourceUtil'); const targetDir = process.env.SFDX_MDAPI_TEMP_DIR || os.tmpdir(); const tmpOutputDir = path.join(targetDir, `sdx_${cmdName}_${Date.now()}`); await fs.mkdirp(tmpOutputDir, fs.DEFAULT_USER_DIR_MODE); logger.info(`Created output directory '${tmpOutputDir}'`); return tmpOutputDir; } export async function cleanupOutputDir(outputDir: string): Promise<void> { const logger: Logger = await Logger.child('SourceUtil'); if (outputDir && !outputDir.includes(process.env.SFDX_MDAPI_TEMP_DIR)) { try { await fs.remove(outputDir); try { if (await fs.stat(`${outputDir}.zip`)) { await fs.unlink(`${outputDir}.zip`); } } catch (err) { if (err.code !== 'ENOENT') { logger.warn(`Could not delete the MDAPI temporary zip file ${outputDir}.zip due to: ${err.message}`); } } } catch (err) { logger.warn(`Could not delete the outputDir '${outputDir}' due to: ${err.message}`); } } else { logger.warn(`Did not delete the outputDir '${outputDir}' because it was set by the user`); } } /** * Return the aggregate source element for the specified file * * @param {string} sourcePath the file in the workspace * @param sourceWorkspaceAdapter * @returns {AggregateSourceElement} */ export const getSourceElementForFile = async function ( sourcePath: string, sourceWorkspaceAdapter: SourceWorkspaceAdapter, metadataType?: MetadataType ): Promise<AggregateSourceElement> { let aggregateSourceElement: AggregateSourceElement; const mdRegistry = sourceWorkspaceAdapter.metadataRegistry; const sourceElementMetadataType = metadataType || MetadataTypeFactory.getMetadataTypeFromSourcePath(sourcePath, mdRegistry); if (sourceElementMetadataType) { // This will build an AggregateSourceElement with only the specified WorkspaceElement // (child element) when the metadata type has a parent. const _sourcePath = _get(sourceElementMetadataType, 'typeDefObj.parent') ? sourcePath : path.dirname(sourcePath); const aggregateMetadataName = sourceElementMetadataType.getAggregateMetadataName(); const aggregateFullName = sourceElementMetadataType.getAggregateFullNameFromFilePath(sourcePath); const key = AggregateSourceElement.getKeyFromMetadataNameAndFullName(aggregateMetadataName, aggregateFullName); // Get the AggregateSourceElement, which will only populate with the specified WorkspaceElement // when sourcePath is part of an ASE. const sourceElements = await sourceWorkspaceAdapter.getAggregateSourceElements( false, undefined, undefined, _sourcePath ); const packageName = SfdxProject.getInstance().getPackageNameFromPath(sourcePath); aggregateSourceElement = loadSourceElement(sourceElements, key, mdRegistry, packageName); } else { throw SfdxError.create('salesforce-alm', 'source', 'SourcePathInvalid', [sourcePath]); } return aggregateSourceElement; }; /** * Get the source elements from the source path, whether for a particular file or a directory */ export const getSourceElementsFromSourcePath = async function ( optionsSourcePath: string, sourceWorkspaceAdapter: SourceWorkspaceAdapter ): Promise<AggregateSourceElements> { const aggregateSourceElements = new AggregateSourceElements(); const mdRegistry = sourceWorkspaceAdapter.metadataRegistry; for (let sourcepath of optionsSourcePath.split(',')) { // resolve to an absolute path sourcepath = path.resolve(sourcepath.trim()); // Throw an error if the source path isn't accessible. try { await fs.access(sourcepath, fs.constants.R_OK); } catch (e) { throw SfdxError.create('salesforce-alm', 'source', 'SourcePathInvalid', [sourcepath]); } // Get the MetadataType so we can resolve the path. Some paths such as individual static // resources need to use a different path when getting source elements. const metadataType = MetadataTypeFactory.getMetadataTypeFromSourcePath(sourcepath, mdRegistry); if (metadataType) { sourcepath = metadataType.resolveSourcePath(sourcepath); } // Get a single source element or a directory of source elements and add it to the map. if (srcDevUtil.containsFileExt(sourcepath)) { const ase: AggregateSourceElement = await getSourceElementForFile( sourcepath, sourceWorkspaceAdapter, metadataType ); const aseKey = ase.getKey(); const pkg = ase.getPackageName(); if (aggregateSourceElements.has(pkg)) { const sourceElements = aggregateSourceElements.get(pkg); if (sourceElements.has(aseKey)) { const _ase = sourceElements.get(aseKey); _ase.addWorkspaceElement(ase.getWorkspaceElements()[0]); sourceElements.set(aseKey, _ase); } else { sourceElements.set(aseKey, ase); } } else { aggregateSourceElements.setIn(pkg, aseKey, ase); } } else { const sourceElementsInPath = await getSourceElementsInPath(sourcepath, sourceWorkspaceAdapter); aggregateSourceElements.merge(sourceElementsInPath); } } return aggregateSourceElements; }; /** * Return the specified aggregate source element or error if it does not exist * * @param {AggregateSourceElements} sourceElements All the source elements in the workspace * @param {string} key The key of the particular source element we are looking for * @param {string} packageName * @param {MetadataRegistry} metadataRegistry * @returns {AggregateSourceElement} */ export const loadSourceElement = function ( sourceElements: AggregateSourceElements, key: string, metadataRegistry: MetadataRegistry, packageName?: string ): AggregateSourceElement { const aggregateSourceElement = packageName ? sourceElements.getSourceElement(packageName, key) : sourceElements.findSourceElementByKey(key); if (!aggregateSourceElement) { // Namespaces also contain '__' so only split on the first occurrence of '__' let [mdType, ...rest] = key.split('__'); const mdName = rest.join('__'); const metadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName(mdType, metadataRegistry); if (!metadataType) { throw SfdxError.create('salesforce-alm', 'source', 'MetadataTypeDoesNotExist', [mdType]); } const hasParentType = metadataType.getMetadataName() !== metadataType.getAggregateMetadataName(); if (hasParentType) { // In this case, we are dealing with a decomposed subtype, so need to check for a parent const parentName = metadataType.getAggregateMetadataName(); const parentMetadataType = MetadataTypeFactory.getAggregateMetadataType(parentName, metadataRegistry); const parentFullName = metadataType.getAggregateFullNameFromWorkspaceFullName(mdName); const newKey = AggregateSourceElement.getKeyFromMetadataNameAndFullName( parentMetadataType.getAggregateMetadataName(), parentFullName ); // Get the parent AggregateSourceElement with all WorkspaceElements removed // except for the child specified by the `key`. return sourceElements.findParentElement(newKey, mdType, mdName); } else if (metadataType instanceof InFolderMetadataType) { mdType = MdapiPackage.convertFolderTypeKey(mdType); return loadSourceElement(sourceElements, `${mdType}__${mdName}`, metadataRegistry, packageName); } else if (metadataType instanceof NondecomposedTypesWithChildrenMetadataType) { // eslint-disable-next-line @typescript-eslint/no-shadow const mdType = metadataType.getMetadataName(); let name = `${mdType}__${mdName.split('.')[0]}`; if (metadataType instanceof CustomLabelsMetadataType) { // for now, all CustomLabels are in CustomLabels.labels.meta-xml. // the key for the ASE is then CustomLabels_CustomLabels // it will deploy all CustomLabels, regardless of what is specified in the manifest name = `${mdType}__${mdType}`; } if (name === key) { // the name isn't changing which causes a max stack call size error, const errConfig = new SfdxErrorConfig('salesforce-alm', 'source_deploy', 'SourceElementDoesNotExist'); errConfig.setErrorTokens([mdType, mdName]); throw SfdxError.create(errConfig); } return loadSourceElement(sourceElements, name, metadataRegistry, packageName); } else { const errConfig = new SfdxErrorConfig('salesforce-alm', 'source_deploy', 'SourceElementDoesNotExist'); errConfig.setErrorTokens([mdType, mdName]); throw SfdxError.create(errConfig); } } return aggregateSourceElement; }; /** * Return the aggregate source elements found in the provided source path * * @param {Array<string>} sourcePath The path to look for source elements in * @param sourceWorkspaceAdapter * @returns {AggregateSourceElements} */ export const getSourceElementsInPath = function ( sourcePath: string, sourceWorkspaceAdapter: any ): Promise<AggregateSourceElements> { return sourceWorkspaceAdapter.getAggregateSourceElements(false, undefined, undefined, sourcePath); }; /** * Used to determine if an error is the result of parsing bad XML. If so return a new parsing error. * * @param path The file path. * @param error The error to inspect. */ // eslint-disable-next-line @typescript-eslint/no-shadow export const checkForXmlParseError = function (path: string, error: Error) { if (path && error instanceof SfdxError && error.name === 'xmlParseErrorsReported') { const data = (error.data as XmlLineError[]) || []; const message = `${path}:${os.EOL}${data.reduce( // eslint-disable-next-line @typescript-eslint/no-shadow (messages: string, message: XmlLineError) => `${messages}${os.EOL}${message.message}`, '' )}`; return SfdxError.create('salesforce-alm', 'source', 'XmlParsingError', [message]); } return error; }; /** * @param options */ export const containsMdBundle = function (options: any): boolean { if (options.metadata) { // for retreiveFromMetadata return options.metadata.indexOf('Bundle') >= 0; } else { // for retrieveFromSourcepath for (const pair of options) { if (pair.type.indexOf('Bundle') >= 0) { return true; } } return false; } }; /** * Filters the component success responses from a deploy or retrieve to exclude * components that do not have SourceMembers created for them in the org, such * as standard objects (e.g., Account) and standard fields before syncing with * remote source tracking. Also modifies the fullName (e.g., MyApexClass) of * certain metadata types to match their corresponding SourceMember names. * * Filtering rules applied: * 1. Component successes without an `id` entry do not have `SourceMember` * records created for them. * E.g., standard objects, package.xml, CustomLabels, etc. * 2. In-Folder types (E.g., Documents) will have the file extension removed * since the SourceMember's MemberName does not include it. * E.g., "MyDocFolder/MyDoc.png" --> "MyDocFolder/MyDoc" * 3. Component success fullNames will be URI decoded. * E.g., "Account %28Sales%29" --> "Account (Sales)" * * NOTE: Currently this is only called after a source:push. * * @param successes the component successes of a deploy/retrieve response * @param remoteSourceTrackingService * @param metadataRegistry */ export const updateSourceTracking = async function ( successes: any[], remoteSourceTrackingService: RemoteSourceTrackingService, metadataRegistry: MetadataRegistry ): Promise<void> { const metadataTrackableElements: string[] = []; successes.forEach((component) => { // Assume only components with id's are trackable (SourceMembers are created) if (component.id) { const componentMetadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName( component.componentType, metadataRegistry ); let fullName = component.fullName; if (componentMetadataType instanceof InFolderMetadataType && component.fileName) { // This removes any file extension from component.fullName fullName = componentMetadataType.getFullNameFromFilePath(component.fileName); } metadataTrackableElements.push(decodeURIComponent(fullName)); } }); // Sync source tracking for the trackable pushed components await remoteSourceTrackingService.sync(metadataTrackableElements); };
the_stack
import * as assert from 'assert'; import {describe, it, afterEach, beforeEach} from 'mocha'; import * as nock from 'nock'; import * as sinon from 'sinon'; import {AwsClient} from '../src/auth/awsclient'; import {StsSuccessfulResponse} from '../src/auth/stscredentials'; import {BaseExternalAccountClient} from '../src/auth/baseexternalclient'; import { assertGaxiosResponsePresent, getAudience, getTokenUrl, getServiceAccountImpersonationUrl, mockGenerateAccessToken, mockStsTokenExchange, } from './externalclienthelper'; nock.disableNetConnect(); const ONE_HOUR_IN_SECS = 3600; describe('AwsClient', () => { let clock: sinon.SinonFakeTimers; // eslint-disable-next-line @typescript-eslint/no-var-requires const awsSecurityCredentials = require('../../test/fixtures/aws-security-credentials-fake.json'); const referenceDate = new Date('2020-08-11T06:55:22.345Z'); const amzDate = '20200811T065522Z'; const dateStamp = '20200811'; const awsRegion = 'us-east-2'; const accessKeyId = awsSecurityCredentials.AccessKeyId; const secretAccessKey = awsSecurityCredentials.SecretAccessKey; const token = awsSecurityCredentials.Token; const awsRole = 'gcp-aws-role'; const audience = getAudience(); const metadataBaseUrl = 'http://169.254.169.254'; const awsCredentialSource = { environment_id: 'aws1', region_url: `${metadataBaseUrl}/latest/meta-data/placement/availability-zone`, url: `${metadataBaseUrl}/latest/meta-data/iam/security-credentials`, regional_cred_verification_url: 'https://sts.{region}.amazonaws.com?' + 'Action=GetCallerIdentity&Version=2011-06-15', }; const awsOptions = { type: 'external_account', audience, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', token_url: getTokenUrl(), credential_source: awsCredentialSource, }; const awsOptionsWithSA = Object.assign( { service_account_impersonation_url: getServiceAccountImpersonationUrl(), }, awsOptions ); const stsSuccessfulResponse: StsSuccessfulResponse = { access_token: 'ACCESS_TOKEN', issued_token_type: 'urn:ietf:params:oauth:token-type:access_token', token_type: 'Bearer', expires_in: ONE_HOUR_IN_SECS, scope: 'scope1 scope2', }; // Signature retrieved from "signed POST request" test in test.awsclient.ts. const expectedSignedRequest = { url: 'https://sts.us-east-2.amazonaws.com' + '?Action=GetCallerIdentity&Version=2011-06-15', method: 'POST', headers: { Authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/` + `${dateStamp}/${awsRegion}/sts/aws4_request, SignedHeaders=host;` + 'x-amz-date;x-amz-security-token, Signature=' + '73452984e4a880ffdc5c392355733ec3f5ba310d5e0609a89244440cadfe7a7a', host: 'sts.us-east-2.amazonaws.com', 'x-amz-date': amzDate, 'x-amz-security-token': token, }, }; const expectedSubjectToken = encodeURIComponent( JSON.stringify({ url: expectedSignedRequest.url, method: expectedSignedRequest.method, headers: [ { key: 'x-goog-cloud-target-resource', value: awsOptions.audience, }, { key: 'x-amz-date', value: expectedSignedRequest.headers['x-amz-date'], }, { key: 'Authorization', value: expectedSignedRequest.headers.Authorization, }, { key: 'host', value: expectedSignedRequest.headers.host, }, { key: 'x-amz-security-token', value: expectedSignedRequest.headers['x-amz-security-token'], }, ], }) ); // Signature retrieved from "signed request when AWS credentials have no // token" test in test.awsclient.ts. const expectedSignedRequestNoToken = { url: 'https://sts.us-east-2.amazonaws.com' + '?Action=GetCallerIdentity&Version=2011-06-15', method: 'POST', headers: { Authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/` + `${dateStamp}/${awsRegion}/sts/aws4_request, SignedHeaders=host;` + 'x-amz-date, Signature=' + 'd095ba304919cd0d5570ba8a3787884ee78b860f268ed040ba23831d55536d56', host: 'sts.us-east-2.amazonaws.com', 'x-amz-date': amzDate, }, }; const expectedSubjectTokenNoToken = encodeURIComponent( JSON.stringify({ url: expectedSignedRequestNoToken.url, method: expectedSignedRequestNoToken.method, headers: [ { key: 'x-goog-cloud-target-resource', value: awsOptions.audience, }, { key: 'x-amz-date', value: expectedSignedRequestNoToken.headers['x-amz-date'], }, { key: 'Authorization', value: expectedSignedRequestNoToken.headers.Authorization, }, { key: 'host', value: expectedSignedRequestNoToken.headers.host, }, ], }) ); beforeEach(() => { clock = sinon.useFakeTimers(referenceDate); }); afterEach(() => { if (clock) { clock.restore(); } }); it('should be a subclass of ExternalAccountClient', () => { assert(AwsClient.prototype instanceof BaseExternalAccountClient); }); describe('Constructor', () => { const requiredCredentialSourceFields = [ 'environment_id', 'regional_cred_verification_url', ]; requiredCredentialSourceFields.forEach(required => { it(`should throw when credential_source is missing ${required}`, () => { const expectedError = new Error( 'No valid AWS "credential_source" provided' ); const invalidCredentialSource = Object.assign({}, awsCredentialSource); // eslint-disable-next-line @typescript-eslint/no-explicit-any delete (invalidCredentialSource as any)[required]; const invalidOptions = { type: 'external_account', audience, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', token_url: getTokenUrl(), credential_source: invalidCredentialSource, }; assert.throws(() => { return new AwsClient(invalidOptions); }, expectedError); }); }); it('should throw when an unsupported environment ID is provided', () => { const expectedError = new Error( 'No valid AWS "credential_source" provided' ); const invalidCredentialSource = Object.assign({}, awsCredentialSource); invalidCredentialSource.environment_id = 'azure1'; const invalidOptions = { type: 'external_account', audience, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', token_url: getTokenUrl(), credential_source: invalidCredentialSource, }; assert.throws(() => { return new AwsClient(invalidOptions); }, expectedError); }); it('should throw when an unsupported environment version is provided', () => { const expectedError = new Error( 'aws version "3" is not supported in the current build.' ); const invalidCredentialSource = Object.assign({}, awsCredentialSource); invalidCredentialSource.environment_id = 'aws3'; const invalidOptions = { type: 'external_account', audience, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', token_url: getTokenUrl(), credential_source: invalidCredentialSource, }; assert.throws(() => { return new AwsClient(invalidOptions); }, expectedError); }); it('should not throw when valid AWS options are provided', () => { assert.doesNotThrow(() => { return new AwsClient(awsOptions); }); }); }); describe('for security_credentials retrieved tokens', () => { describe('retrieveSubjectToken()', () => { it('should resolve on success', async () => { const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) .get('/latest/meta-data/iam/security-credentials') .reply(200, awsRole) .get(`/latest/meta-data/iam/security-credentials/${awsRole}`) .reply(200, awsSecurityCredentials); const client = new AwsClient(awsOptions); const subjectToken = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectToken); scope.done(); }); it('should resolve on success with permanent creds', async () => { const permanentAwsSecurityCredentials = Object.assign( {}, awsSecurityCredentials ); delete permanentAwsSecurityCredentials.Token; const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) .get('/latest/meta-data/iam/security-credentials') .reply(200, awsRole) .get(`/latest/meta-data/iam/security-credentials/${awsRole}`) .reply(200, permanentAwsSecurityCredentials); const client = new AwsClient(awsOptions); const subjectToken = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectTokenNoToken); scope.done(); }); it('should re-calculate role name on successive calls', async () => { const otherRole = 'some-other-role'; const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) .get('/latest/meta-data/iam/security-credentials') .reply(200, awsRole) .get(`/latest/meta-data/iam/security-credentials/${awsRole}`) .reply(200, awsSecurityCredentials) .get('/latest/meta-data/iam/security-credentials') .reply(200, otherRole) .get(`/latest/meta-data/iam/security-credentials/${otherRole}`) .reply(200, awsSecurityCredentials); const client = new AwsClient(awsOptions); const subjectToken = await client.retrieveSubjectToken(); const subjectToken2 = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectToken); assert.deepEqual(subjectToken2, expectedSubjectToken); scope.done(); }); it('should reject when AWS region is not determined', async () => { // Simulate error during region retrieval. const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(500); const client = new AwsClient(awsOptions); await assert.rejects(client.retrieveSubjectToken(), { code: '500', }); scope.done(); }); it('should reject when AWS role name is not determined', async () => { // Simulate error during region retrieval. const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) .get('/latest/meta-data/iam/security-credentials') .reply(403); const client = new AwsClient(awsOptions); await assert.rejects(client.retrieveSubjectToken(), { code: '403', }); scope.done(); }); it('should reject when AWS security creds are not found', async () => { // Simulate error during security credentials retrieval. const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) .get('/latest/meta-data/iam/security-credentials') .reply(200, awsRole) .get(`/latest/meta-data/iam/security-credentials/${awsRole}`) .reply(408); const client = new AwsClient(awsOptions); await assert.rejects(client.retrieveSubjectToken(), { code: '408', }); scope.done(); }); it('should reject when "credential_source.url" is missing', async () => { const expectedError = new Error( 'Unable to determine AWS role name due to missing ' + '"options.credential_source.url"' ); const missingUrlCredentialSource = Object.assign( {}, awsCredentialSource ); delete missingUrlCredentialSource.url; const invalidOptions = { type: 'external_account', audience, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', token_url: getTokenUrl(), credential_source: missingUrlCredentialSource, }; const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`); const client = new AwsClient(invalidOptions); await assert.rejects(client.retrieveSubjectToken(), expectedError); scope.done(); }); it('should reject when "credential_source.region_url" is missing', async () => { const expectedError = new Error( 'Unable to determine AWS region due to missing ' + '"options.credential_source.region_url"' ); const missingRegionUrlCredentialSource = Object.assign( {}, awsCredentialSource ); delete missingRegionUrlCredentialSource.region_url; const invalidOptions = { type: 'external_account', audience, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', token_url: getTokenUrl(), credential_source: missingRegionUrlCredentialSource, }; const client = new AwsClient(invalidOptions); await assert.rejects(client.retrieveSubjectToken(), expectedError); }); }); describe('getAccessToken()', () => { it('should resolve on retrieveSubjectToken success', async () => { const scopes: nock.Scope[] = []; scopes.push( mockStsTokenExchange([ { statusCode: 200, response: stsSuccessfulResponse, request: { grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', audience, scope: 'https://www.googleapis.com/auth/cloud-platform', requested_token_type: 'urn:ietf:params:oauth:token-type:access_token', subject_token: expectedSubjectToken, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', }, }, ]) ); scopes.push( nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) .get('/latest/meta-data/iam/security-credentials') .reply(200, awsRole) .get(`/latest/meta-data/iam/security-credentials/${awsRole}`) .reply(200, awsSecurityCredentials) ); const client = new AwsClient(awsOptions); const actualResponse = await client.getAccessToken(); // Confirm raw GaxiosResponse appended to response. assertGaxiosResponsePresent(actualResponse); delete actualResponse.res; assert.deepStrictEqual(actualResponse, { token: stsSuccessfulResponse.access_token, }); scopes.forEach(scope => scope.done()); }); it('should handle service account access token', async () => { const saSuccessResponse = { accessToken: 'SA_ACCESS_TOKEN', expireTime: new Date( referenceDate.getTime() + ONE_HOUR_IN_SECS * 1000 ).toISOString(), }; const scopes: nock.Scope[] = []; scopes.push( nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) .get('/latest/meta-data/iam/security-credentials') .reply(200, awsRole) .get(`/latest/meta-data/iam/security-credentials/${awsRole}`) .reply(200, awsSecurityCredentials), mockStsTokenExchange([ { statusCode: 200, response: stsSuccessfulResponse, request: { grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', audience, scope: 'https://www.googleapis.com/auth/cloud-platform', requested_token_type: 'urn:ietf:params:oauth:token-type:access_token', subject_token: expectedSubjectToken, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', }, }, ]), mockGenerateAccessToken([ { statusCode: 200, response: saSuccessResponse, token: stsSuccessfulResponse.access_token, scopes: ['https://www.googleapis.com/auth/cloud-platform'], }, ]) ); const client = new AwsClient(awsOptionsWithSA); const actualResponse = await client.getAccessToken(); // Confirm raw GaxiosResponse appended to response. assertGaxiosResponsePresent(actualResponse); delete actualResponse.res; assert.deepStrictEqual(actualResponse, { token: saSuccessResponse.accessToken, }); scopes.forEach(scope => scope.done()); }); it('should reject on retrieveSubjectToken error', async () => { const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) .get('/latest/meta-data/iam/security-credentials') .reply(500); const client = new AwsClient(awsOptions); await assert.rejects(client.getAccessToken(), { code: '500', }); scope.done(); }); }); }); describe('for environment variables retrieved tokens', () => { let envAwsAccessKeyId: string | undefined; let envAwsSecretAccessKey: string | undefined; let envAwsSessionToken: string | undefined; let envAwsRegion: string | undefined; let envAwsDefaultRegion: string | undefined; beforeEach(() => { // Store external state. envAwsAccessKeyId = process.env.AWS_ACCESS_KEY_ID; envAwsSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY; envAwsSessionToken = process.env.AWS_SESSION_TOKEN; envAwsRegion = process.env.AWS_REGION; envAwsDefaultRegion = process.env.AWS_DEFAULT_REGION; // Reset environment variables. delete process.env.AWS_ACCESS_KEY_ID; delete process.env.AWS_SECRET_ACCESS_KEY; delete process.env.AWS_SESSION_TOKEN; delete process.env.AWS_REGION; delete process.env.AWS_DEFAULT_REGION; }); afterEach(() => { // Restore environment variables. if (envAwsAccessKeyId) { process.env.AWS_ACCESS_KEY_ID = envAwsAccessKeyId; } else { delete process.env.AWS_ACCESS_KEY_ID; } if (envAwsSecretAccessKey) { process.env.AWS_SECRET_ACCESS_KEY = envAwsSecretAccessKey; } else { delete process.env.AWS_SECRET_ACCESS_KEY; } if (envAwsSessionToken) { process.env.AWS_SESSION_TOKEN = envAwsSessionToken; } else { delete process.env.AWS_SESSION_TOKEN; } if (envAwsRegion) { process.env.AWS_REGION = envAwsRegion; } else { delete process.env.AWS_REGION; } if (envAwsDefaultRegion) { process.env.AWS_DEFAULT_REGION = envAwsDefaultRegion; } else { delete process.env.AWS_DEFAULT_REGION; } }); describe('retrieveSubjectToken()', () => { it('should resolve on success for permanent creds', async () => { process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`); const client = new AwsClient(awsOptions); const subjectToken = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectTokenNoToken); scope.done(); }); it('should resolve on success for temporary creds', async () => { process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; process.env.AWS_SESSION_TOKEN = token; const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`); const client = new AwsClient(awsOptions); const subjectToken = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectToken); scope.done(); }); it('should reject when AWS region is not determined', async () => { process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; // Simulate error during region retrieval. const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(500); const client = new AwsClient(awsOptions); await assert.rejects(client.retrieveSubjectToken(), { code: '500', }); scope.done(); }); it('should resolve when AWS_REGION is set as environment variable', async () => { process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; process.env.AWS_REGION = awsRegion; const client = new AwsClient(awsOptions); const subjectToken = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectTokenNoToken); }); it('should resolve when AWS_DEFAULT_REGION is set as environment variable', async () => { process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; process.env.AWS_DEFAULT_REGION = awsRegion; const client = new AwsClient(awsOptions); const subjectToken = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectTokenNoToken); }); it('should prioritize AWS_REGION over AWS_DEFAULT_REGION environment variable', async () => { process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; process.env.AWS_REGION = awsRegion; process.env.AWS_DEFAULT_REGION = 'fail-if-used'; const client = new AwsClient(awsOptions); const subjectToken = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectTokenNoToken); }); it('should resolve without optional credentials_source fields', async () => { process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; process.env.AWS_REGION = awsRegion; const requiredOnlyCredentialSource = Object.assign( {}, awsCredentialSource ); // Remove all optional fields. delete requiredOnlyCredentialSource.region_url; delete requiredOnlyCredentialSource.url; const requiredOnlyOptions = { type: 'external_account', audience, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', token_url: getTokenUrl(), credential_source: requiredOnlyCredentialSource, }; const client = new AwsClient(requiredOnlyOptions); const subjectToken = await client.retrieveSubjectToken(); assert.deepEqual(subjectToken, expectedSubjectTokenNoToken); }); }); describe('getAccessToken()', () => { it('should resolve on retrieveSubjectToken success', async () => { const scopes: nock.Scope[] = []; scopes.push( mockStsTokenExchange([ { statusCode: 200, response: stsSuccessfulResponse, request: { grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', audience, scope: 'https://www.googleapis.com/auth/cloud-platform', requested_token_type: 'urn:ietf:params:oauth:token-type:access_token', subject_token: expectedSubjectTokenNoToken, subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', }, }, ]) ); scopes.push( nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(200, `${awsRegion}b`) ); process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; const client = new AwsClient(awsOptions); const actualResponse = await client.getAccessToken(); // Confirm raw GaxiosResponse appended to response. assertGaxiosResponsePresent(actualResponse); delete actualResponse.res; assert.deepStrictEqual(actualResponse, { token: stsSuccessfulResponse.access_token, }); scopes.forEach(scope => scope.done()); }); it('should reject on retrieveSubjectToken error', async () => { process.env.AWS_ACCESS_KEY_ID = accessKeyId; process.env.AWS_SECRET_ACCESS_KEY = secretAccessKey; const scope = nock(metadataBaseUrl) .get('/latest/meta-data/placement/availability-zone') .reply(500); const client = new AwsClient(awsOptions); await assert.rejects(client.getAccessToken(), { code: '500', }); scope.done(); }); }); }); });
the_stack
'use strict'; import * as child_process from 'child_process'; import { DebugSession, Thread, Breakpoint, Source, StackFrame, Variable, Handles, InitializedEvent, StoppedEvent, TerminatedEvent, BreakpointEvent, OutputEvent } from 'vscode-debugadapter'; import {DebugProtocol} from 'vscode-debugprotocol'; import * as path from 'path'; import * as fs from 'fs'; import log from '../log'; let evalResultParser = require('./eval_result_parser.js'); let promisify = require('tiny-promisify'); let freeport = promisify(require('freeport')); let iconv = require('iconv-lite'); let DECODED_STDOUT = Symbol(); let DECODED_STDERR = Symbol(); interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments { cd: string; includePath?: string[]; program: string; console: "internalConsole" | "integratedTerminal" | "externalTerminal", arguments?: string[]; env?: {[index: string]: string}; envFile?: string; stopOnEntry: boolean; socket?: string; symbols?: string; script?: string; encoding?: string; ocamldebugEncoding?: string; _showLogs?: boolean; } export interface VariableContainer { expand(session: OCamlDebugSession): Promise<Variable[]>; setValue(session: OCamlDebugSession, name: string, value: string): Promise<string>; } export class Expander implements VariableContainer { private _expanderFunction: () => Promise<Variable[]>; constructor(func: () => Promise<Variable[]>) { this._expanderFunction = func; } async expand(session: OCamlDebugSession): Promise<Variable[]> { return this._expanderFunction(); } async setValue(session: OCamlDebugSession, name: string, value: string): Promise<string> { throw new Error("Setting value not supported"); } } class OCamlDebugSession extends DebugSession { private static BREAKPOINT_ID = Symbol(); private _launchArgs: LaunchRequestArguments; private _supportRunInTerminal: boolean = false; private _debuggeeProc: child_process.ChildProcess; private _debuggerProc: child_process.ChildProcess; private _wait = Promise.resolve(); private _remoteMode: boolean = false; private _socket: string; private _breakpoints: Map<string, Breakpoint[]>; private _functionBreakpoints: Breakpoint[]; private _variableHandles: Handles<VariableContainer>; private _modules: string[] = []; private _filenames: string[] = []; private _filenameToPath = new Map<string, string>(); constructor() { super(); this.setRunAsServer(false); } log(msg: string) { log(msg); if (this._launchArgs._showLogs) { this.sendEvent(new OutputEvent(`${msg}\n`)); } } ocdCommand(cmd, callback, callback2?) { if (Array.isArray(cmd)) { cmd = cmd.join(' '); } this._wait = this._wait.then(() => { this.log(`cmd: ${cmd}`); this._debuggerProc.stdin.write(cmd + '\n'); return this.readUntilPrompt(callback2).then((output) => { callback(output) }); }); } readUntilPrompt(callback?) { return new Promise((resolve) => { let buffer = ''; let onStdoutData = (chunk) => { buffer += chunk.replace(/\r\n/g, '\n'); if (callback) callback(buffer); if (buffer.slice(-6) === '(ocd) ') { let output = buffer.slice(0, -6); output = output.replace(/\n$/, ''); this.log(`ocd: ${JSON.stringify(output)}`); resolve(output); this._debuggerProc[DECODED_STDOUT].removeListener('data', onStdoutData); this._debuggerProc[DECODED_STDERR].removeListener('data', onStderrData); } }; let onStderrData = (chunk) => { // TODO: Find better way to handle this. // Ignore non-error message from stderr: 'done.\n'. if (chunk === 'done.\n') return; this.sendEvent(new OutputEvent(chunk)); } this._debuggerProc[DECODED_STDOUT].on('data', onStdoutData); this._debuggerProc[DECODED_STDERR].on('data', onStderrData); }); } parseEvent(output) { if (output.indexOf('Program exit.') >= 0) { this.sendEvent(new TerminatedEvent()); } else if (output.indexOf('Program end.') >= 0) { let index = output.indexOf('Program end.'); let reason = output.substring(index + 'Program end.'.length); this.sendEvent(new OutputEvent(reason)); this.sendEvent(new TerminatedEvent()); } else { let reason = output.indexOf('Breakpoint:') >= 0 ? 'breakpoint' : 'step'; this.sendEvent(new StoppedEvent(reason, 0)); } } getModuleFromFilename(filename) { // FIXME: respect `directory` command of ocamldebug let candidate = path.basename(filename).split(/\./g)[0].replace(/^[a-z]/, (c) => c.toUpperCase()); let modules = this._modules.filter((module) => { let path = module.split(/\./g); return path[path.length - 1] === candidate; }); return modules.length >= 1 ? modules[0] : candidate; } getSource(filename: string) { if (this._filenameToPath.has(filename)) { return new Source(filename, this._filenameToPath.get(filename)); } let index = this._filenames.indexOf(filename); if (index === -1) { index = this._filenames.length; this._filenames.push(filename); } let sourcePath = null; let testPath = path.resolve(path.dirname(this._launchArgs.program), filename); // TODO: check against list command. if (fs.existsSync(testPath)) { sourcePath = testPath; } return new Source(filename, sourcePath, index + 1, 'source'); } protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void { response.body.supportsConfigurationDoneRequest = true; response.body.supportsFunctionBreakpoints = true; response.body.supportsEvaluateForHovers = true; response.body.supportsStepBack = true; this._supportRunInTerminal = args.supportsRunInTerminalRequest; this.sendResponse(response); } protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments): void { if (this._debuggerProc) { this._debuggerProc.stdin.end('kill\nquit\n', () => { this._debuggerProc.kill(); this._debuggerProc = null; }); } if (this._debuggeeProc) { this._debuggeeProc.stdout.removeAllListeners(); this._debuggeeProc.stderr.removeAllListeners(); this._debuggeeProc.kill(); } this._remoteMode = false; this._socket = null; this._debuggeeProc = null; this._breakpoints = null; this._functionBreakpoints = null; this._variableHandles.reset(); this._filenames = []; this._filenameToPath.clear(); super.disconnectRequest(response, args); } private loadEnv(envFile: string, env: {[index: string]: string}) { const envMap : ({[index: string]: string}) = {}; if (envFile) { let content = fs.readFileSync(envFile, 'utf8') content.split('\n').forEach( line => { const r = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/); if (r !== null) { const key = r[1]; if (!process.env[key]) { // .env variables never overwrite existing variables (see #21169) let value = r[2] || ''; if (value.length > 0 && value.charAt(0) === '"' && value.charAt(value.length-1) === '"') { value = value.replace(/\\n/gm, '\n'); } envMap[key] = value.replace(/(^['"]|['"]$)/g, ''); } } }); } if (env) { Object.assign(envMap, env); } return envMap; } protected async launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments) { let checkEncoding = (name: string, encoding: string) => { if (encoding) { if (iconv.encodingExists(encoding)) { return encoding; } this.sendEvent(new OutputEvent(`Encoding "${encoding}" specified by option "${name}" isn't supported. Fallback to "utf-8" encoding.\n`)); } return 'utf-8'; }; let env = this.loadEnv(args.envFile, args.env); let launchDebuggee = () => { if (this._supportRunInTerminal && (args.console === 'integratedTerminal' || args.console === 'externalTerminal')) { this.runInTerminalRequest({ title: 'OCaml Debug Console', kind: args.console === 'integratedTerminal' ? 'integrated' : 'external', env: env, cwd: args.cd || path.dirname(args.program), args: [args.program, ...(args.arguments || [])] }, 5000, (runResp) => { if (!runResp.success) { // TOOD: Use sendErrorResponse instead. this.sendEvent(new OutputEvent(runResp.message)); this.sendEvent(new TerminatedEvent()); } }); } else { this._debuggeeProc = child_process.spawn(args.program, args.arguments || [], { env: Object.assign({}, process.env, env), cwd: args.cd || path.dirname(args.program) }); let debuggeeEncoding = checkEncoding('encoding', args.encoding); this._debuggeeProc[DECODED_STDOUT] = iconv.decodeStream(debuggeeEncoding); this._debuggeeProc.stdout.pipe(this._debuggeeProc[DECODED_STDOUT]); this._debuggeeProc[DECODED_STDOUT].on('data', (chunk) => { this.sendEvent(new OutputEvent(chunk, 'stdout')); }); this._debuggeeProc[DECODED_STDERR] = iconv.decodeStream(debuggeeEncoding); this._debuggeeProc.stderr.pipe(this._debuggeeProc[DECODED_STDERR]); this._debuggeeProc[DECODED_STDERR].on('data', (chunk) => { this.sendEvent(new OutputEvent(chunk, 'stderr')); }); this._debuggeeProc.on('exit', () => { this.sendEvent(new TerminatedEvent()); }); } }; if (args.noDebug) { launchDebuggee(); this.sendEvent(new InitializedEvent()); return; } let ocdArgs = []; if (args.cd) { ocdArgs.push('-cd', args.cd); } if (args.includePath) { args.includePath.forEach((path) => { ocdArgs.push('-I', path); }); } this._remoteMode = !!args.socket; if (this._remoteMode) { this._socket = args.socket; } else { let port = await freeport(); this._socket = `127.0.0.1:${port}`; } env["CAML_DEBUG_SOCKET"] = this._socket; ocdArgs.push('-s', this._socket); // ocdArgs.push('-machine-readable'); ocdArgs.push(path.normalize(args.symbols || args.program)); this._launchArgs = args; this._debuggerProc = child_process.spawn('ocamldebug', ocdArgs); this._debuggerProc.on('exit', () => { this.sendEvent(new TerminatedEvent()); }); let debuggerEncoding = checkEncoding('ocamldebugEncoding', args.ocamldebugEncoding); this._debuggerProc[DECODED_STDOUT] = iconv.decodeStream(debuggerEncoding); this._debuggerProc.stdout.pipe(this._debuggerProc[DECODED_STDOUT]); this._debuggerProc[DECODED_STDERR] = iconv.decodeStream(debuggerEncoding); this._debuggerProc.stderr.pipe(this._debuggerProc[DECODED_STDERR]); this._breakpoints = new Map(); this._functionBreakpoints = []; this._variableHandles = new Handles<VariableContainer>(); this._wait = this.readUntilPrompt().then(() => { }); this.ocdCommand(['set', 'loadingmode', 'manual'], () => { }); let once = false; let onceSocketListened = (message: string) => { if (once) return; once = true; if (this._remoteMode) { this.sendEvent(new OutputEvent(message)); } else { launchDebuggee(); } }; this.ocdCommand(['goto', 0], () => { this.ocdCommand(['info', 'modules'], (text: string) => { let modules = text .replace(/^Used modules:/, '') .replace(/[\s\r\n]+/g, ' ') .trim().split(' '); this._modules = modules; this.sendResponse(response); this.sendEvent(new InitializedEvent()); }); }, (buffer: string) => { if (buffer.includes('Waiting for connection...')) { let message = /Waiting for connection\.\.\..*$/m.exec(buffer)[0]; onceSocketListened(message); } }); } protected async configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments) { if (this._launchArgs.script) { let output = await new Promise((resolve) => { this.ocdCommand(['source', `"${this._launchArgs.script}"`], resolve); }); if (output) { this.sendEvent(new OutputEvent(output as string)); } } if (this._launchArgs.stopOnEntry) { this.ocdCommand(['goto', 0], this.parseEvent.bind(this)); } else { this.ocdCommand(['run'], this.parseEvent.bind(this)); } this.sendResponse(response); } private doSetBreakpoint(param: string, source?: DebugProtocol.Source) { return new Promise((resolve) => { this.ocdCommand(['break', param], (output) => { let match = /^Breakpoint (\d+) at \d+: file ([^,]+), line (\d+), characters (\d+)-(\d+)$/m.exec(output); let breakpoint = null; if (match) { let filename = match[2]; // Ugly hack. if (source && !this._filenameToPath.has(filename) && source.path && source.path.endsWith(filename)) { this._filenameToPath.set(filename, source.path); } breakpoint = new Breakpoint( true, +match[3], +match[4], this.getSource(filename) ); breakpoint[OCamlDebugSession.BREAKPOINT_ID] = +match[1]; } else { breakpoint = new Breakpoint(false); } resolve(breakpoint); }); }); } private doDeleteBreakpoint(id: number) { return new Promise((resolve, reject) => { this.ocdCommand(['delete', id], () => { resolve(); }); }); } private async clearBreakpoints(breakpoints: Breakpoint[]) { for (let breakpoint of breakpoints) { if (breakpoint.verified) { let breakpointId = breakpoint[OCamlDebugSession.BREAKPOINT_ID]; await this.doDeleteBreakpoint(breakpointId); } } } protected async setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments) { let breakpoints = []; let module; if (args.source.sourceReference > 0) { module = this.getModuleFromFilename(this._filenames[args.source.sourceReference - 1]); } else if (args.source.path) { module = this.getModuleFromFilename(args.source.path); } let prevBreakpoints = this._breakpoints.get(module) || []; await this.clearBreakpoints(prevBreakpoints); for (let {line, column} of args.breakpoints) { let breakpoint = await this.doSetBreakpoint('@ ' + [module, line, column].join(' '), args.source); breakpoints.push(breakpoint); } this._breakpoints.set(module, breakpoints); response.body = { breakpoints }; this.sendResponse(response); } protected async setFunctionBreakPointsRequest(response: DebugProtocol.SetFunctionBreakpointsResponse, args: DebugProtocol.SetFunctionBreakpointsArguments) { let breakpoints = []; let prevBreakpoints = this._functionBreakpoints; await this.clearBreakpoints(prevBreakpoints); for (let {name} of args.breakpoints) { let breakpoint = await this.doSetBreakpoint(name); breakpoints.push(breakpoint); } this._functionBreakpoints = breakpoints; response.body = { breakpoints }; this.sendResponse(response); } protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments) { this.ocdCommand('run', this.parseEvent.bind(this)); this.sendResponse(response); } protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments) { this.ocdCommand('next', this.parseEvent.bind(this)); this.sendResponse(response); } protected stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments): void { this.ocdCommand(['step', 1], this.parseEvent.bind(this)); this.sendResponse(response); } protected stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments): void { this.ocdCommand('finish', this.parseEvent.bind(this)); this.sendResponse(response); } protected stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): void { this.ocdCommand('backstep', this.parseEvent.bind(this)); this.sendResponse(response); } protected threadsRequest(response: DebugProtocol.ThreadsResponse) { response.body = { threads: [new Thread(0, 'main')] }; this.sendResponse(response); } protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments) { this.ocdCommand(['backtrace', 100], (text: string) => { let stackFrames = []; let lines = text.trim().split(/\n/g); if (lines[0] === 'Backtrace:') { lines = lines.slice(1); } if (lines[lines.length - 1].includes('(Encountered a function with no debugging information)')) { lines.pop(); } lines.forEach((line) => { let match = /^#(\d+) ([^ ]+) ([^:]+):([^:]+):([^:]+)$/.exec(line); if (match) { stackFrames.push(new StackFrame( +match[1], '', this.getSource(match[3]), +match[4], +match[5] )); } }); response.body = { stackFrames }; this.sendResponse(response); }); } private parseEvalResult(text: string): Variable { let repr = (value: any) => { switch (value.kind) { case 'plain': return value.value; case 'con': return `${value.con} ${repr(value.arg)}`; case 'tuple': return `(${value.items.map(repr).join(', ')})`; case 'array': return `<array>`; case 'list': return `<list>`; case 'record': return `<record>`; } }; let expander = (value) => { return async () => { switch (value.kind) { case 'con': return [createVariable("0", value.arg)]; case 'tuple': return value.items.map((item, index) => createVariable(`%${index + 1}`, item)); case 'array': case 'list': return value.items.map((item, index) => createVariable(`${index}`, item)); case 'record': return value.items.map(({name, value}) => createVariable(name, value)); } }; }; let createVariable = (name: string, value: any): Variable => { let text = repr(value); let numIndexed; let numNamed; switch (value.kind) { case 'plain': return new Variable(name, text); case 'con': numNamed = 0; numIndexed = 1; break; case 'record': case 'tuple': numNamed = value.items.length; numIndexed = 0; break; case 'list': case 'array': numIndexed = value.items.length; numNamed = 0; break; } return new Variable(name, text, this._variableHandles.create(new Expander(expander(value))), numIndexed, numNamed ); }; try { let data = evalResultParser.parse(text); let variable = createVariable(data.name, data.value); // Showing type here instead of short representation. if (data.value.kind !== 'plain' && data.value.kind !== 'con') { (variable as DebugProtocol.Variable).value = data.type; } (variable as DebugProtocol.Variable).type = data.type; return variable; } catch (ex) { let start = ex.location.start.offset; let end = Math.max(ex.location.end.offset, Math.min(start + 16, text.length)); let peek = text.substring(start, end); this.log(`Error (${ex}) occurs while parsing at "${peek}...".`); return null; } } protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments) { let reference = args.variablesReference; let variablesContainer = this._variableHandles.get(reference); let variables = []; if (variablesContainer) { try { variables = await variablesContainer.expand(this); } catch (ex) { } } let filteredVariables = variables; if (args.filter === 'named') { filteredVariables = variables.filter((variable) => !/^[0-9]+$/.test(variable.name)); } else if (args.filter === 'indexed') { filteredVariables = variables.filter((variable) => { if (/^[0-9]+$/.test(variable.name)) { if (!args.count) { return true; } let index = parseInt(variable.name); let start = args.start || 0; return index >= start && index < start + args.count; } return false; }); } response.body = { variables: filteredVariables }; this.sendResponse(response); } protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments) { this.ocdCommand(['frame', args.frameId], () => { this.ocdCommand(['print', `(${args.expression})`], (result) => { let variable = this.parseEvalResult(result); if (variable) { response.body = { result: variable.value, variablesReference: variable.variablesReference, type: (variable as DebugProtocol.Variable).type, indexedVariables: (variable as DebugProtocol.Variable).indexedVariables, namedVariables: (variable as DebugProtocol.Variable).namedVariables, }; this.sendResponse(response); } else { this.sendResponse(response); } }); }); } retrieveSource(module) { return new Promise<string>((resolve) => { this.ocdCommand(['list', module, 1, 100000], (output: string) => { let lines = output.split(/\n/g); let lastLine = lines[lines.length - 1]; if (lastLine === 'Position out of range.') { lines.pop(); } let content = lines.map((line) => { // FIXME: make sure do not accidently replace "<|a|>" in a string or comment. return line.replace(/^\d+ /, '').replace(/<\|[ab]\|>/, ''); }).join('\n'); resolve(content); }); }); } protected async sourceRequest(response: DebugProtocol.SourceResponse, args: DebugProtocol.SourceArguments) { let filename = this._filenames[args.sourceReference - 1]; let module = this.getModuleFromFilename(filename); let content = await this.retrieveSource(module); response.body = { content }; this.sendResponse(response); } } DebugSession.run(OCamlDebugSession);
the_stack
import { Events } from "./events"; export namespace Cookies { /** * A cookie's 'SameSite' state (https://tools.ietf.org/html/draft-west-first-party-cookies). * 'no_restriction' corresponds to a cookie set without a 'SameSite' attribute, 'lax' to 'SameSite=Lax', * and 'strict' to 'SameSite=Strict'. */ type SameSiteStatus = "no_restriction" | "lax" | "strict"; /** * Represents information about an HTTP cookie. */ interface Cookie { /** * The name of the cookie. */ name: string; /** * The value of the cookie. */ value: string; /** * The domain of the cookie (e.g. "www.google.com", "example.com"). */ domain: string; /** * True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie). */ hostOnly: boolean; /** * The path of the cookie. */ path: string; /** * True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS). */ secure: boolean; /** * True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts). */ httpOnly: boolean; /** * The cookie's same-site status (i.e. whether the cookie is sent with cross-site requests). */ sameSite: SameSiteStatus; /** * True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date. */ session: boolean; /** * The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies. * Optional. */ expirationDate?: number; /** * The ID of the cookie store containing this cookie, as provided in getAllCookieStores(). */ storeId: string; /** * The first-party domain of the cookie. */ firstPartyDomain: string; } /** * Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store from a * non-incognito window. */ interface CookieStore { /** * The unique identifier for the cookie store. */ id: string; /** * Identifiers of all the browser tabs that share this cookie store. */ tabIds: number[]; /** * Indicates if this is an incognito cookie store */ incognito: boolean; } /** * The underlying reason behind the cookie's change. If a cookie was inserted, or removed via an explicit call to * $(ref:cookies.remove), "cause" will be "explicit". If a cookie was automatically removed due to expiry, * "cause" will be "expired". If a cookie was removed due to being overwritten with an already-expired expiration date, * "cause" will be set to "expired_overwrite". If a cookie was automatically removed due to garbage collection, * "cause" will be "evicted". If a cookie was automatically removed due to a "set" call that overwrote it, * "cause" will be "overwrite". Plan your response accordingly. */ type OnChangedCause = "evicted" | "expired" | "explicit" | "expired_overwrite" | "overwrite"; /** * Details to identify the cookie being retrieved. */ interface GetDetailsType { /** * The URL with which the cookie to retrieve is associated. This argument may be a full URL, * in which case any data following the URL path (e.g. the query string) is simply ignored. * If host permissions for this URL are not specified in the manifest file, the API call will fail. */ url: string; /** * The name of the cookie to retrieve. */ name: string; /** * The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store * will be used. * Optional. */ storeId?: string; /** * The first-party domain which the cookie to retrieve is associated. This attribute is required if First-Party Isolation * is enabled. * Optional. */ firstPartyDomain?: string; } /** * Information to filter the cookies being retrieved. */ interface GetAllDetailsType { /** * Restricts the retrieved cookies to those that would match the given URL. * Optional. */ url?: string; /** * Filters the cookies by name. * Optional. */ name?: string; /** * Restricts the retrieved cookies to those whose domains match or are subdomains of this one. * Optional. */ domain?: string; /** * Restricts the retrieved cookies to those whose path exactly matches this string. * Optional. */ path?: string; /** * Filters the cookies by their Secure property. * Optional. */ secure?: boolean; /** * Filters out session vs. persistent cookies. * Optional. */ session?: boolean; /** * The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used. * Optional. */ storeId?: string; /** * Restricts the retrieved cookies to those whose first-party domains match this one. * This attribute is required if First-Party Isolation is enabled. To not filter by a specific first-party domain, * use `null` or `undefined`. * Optional. */ firstPartyDomain?: string | null; } /** * Details about the cookie being set. */ interface SetDetailsType { /** * The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of * the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail. */ url: string; /** * The name of the cookie. Empty by default if omitted. * Optional. */ name?: string; /** * The value of the cookie. Empty by default if omitted. * Optional. */ value?: string; /** * The domain of the cookie. If omitted, the cookie becomes a host-only cookie. * Optional. */ domain?: string; /** * The path of the cookie. Defaults to the path portion of the url parameter. * Optional. */ path?: string; /** * Whether the cookie should be marked as Secure. Defaults to false. * Optional. */ secure?: boolean; /** * Whether the cookie should be marked as HttpOnly. Defaults to false. * Optional. */ httpOnly?: boolean; /** * The cookie's same-site status. * Optional. */ sameSite?: SameSiteStatus; /** * The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, * the cookie becomes a session cookie. * Optional. */ expirationDate?: number; /** * The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's * cookie store. * Optional. */ storeId?: string; /** * The first-party domain of the cookie. This attribute is required if First-Party Isolation is enabled. * Optional. */ firstPartyDomain?: string; } /** * Information to identify the cookie to remove. */ interface RemoveDetailsType { /** * The URL associated with the cookie. If host permissions for this URL are not specified in the manifest file, * the API call will fail. */ url: string; /** * The name of the cookie to remove. */ name: string; /** * The ID of the cookie store to look in for the cookie. If unspecified, the cookie is looked for by default in the current * execution context's cookie store. * Optional. */ storeId?: string; /** * The first-party domain associated with the cookie. This attribute is required if First-Party Isolation is enabled. * Optional. */ firstPartyDomain?: string; } /** * Contains details about the cookie that's been removed. If removal failed for any reason, this will be "null", * and $(ref:runtime.lastError) will be set. */ interface RemoveCallbackDetailsType { /** * The URL associated with the cookie that's been removed. */ url: string; /** * The name of the cookie that's been removed. */ name: string; /** * The ID of the cookie store from which the cookie was removed. */ storeId: string; /** * The first-party domain associated with the cookie that's been removed. */ firstPartyDomain: string; } interface OnChangedChangeInfoType { /** * True if a cookie was removed. */ removed: boolean; /** * Information about the cookie that was set or removed. */ cookie: Cookie; /** * The underlying reason behind the cookie's change. */ cause: OnChangedCause; } interface Static { /** * Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, * the one with the longest path will be returned. For cookies with the same path length, * the cookie with the earliest creation time will be returned. * * @param details Details to identify the cookie being retrieved. */ get(details: GetDetailsType): Promise<Cookie>; /** * Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted, * with those with the longest path first. If multiple cookies have the same path length, * those with the earliest creation time will be first. * * @param details Information to filter the cookies being retrieved. */ getAll(details: GetAllDetailsType): Promise<Cookie[]>; /** * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. * * @param details Details about the cookie being set. */ set(details: SetDetailsType): Promise<Cookie>; /** * Deletes a cookie by name. * * @param details Information to identify the cookie to remove. */ remove(details: RemoveDetailsType): Promise<RemoveCallbackDetailsType>; /** * Lists all existing cookie stores. */ getAllCookieStores(): Promise<CookieStore[]>; /** * Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a * two step process: the cookie to be updated is first removed entirely, generating a notification with "cause" of * "overwrite" . Afterwards, a new cookie is written with the updated values, generating a second notification with * "cause" "explicit". * * @param changeInfo */ onChanged: Events.Event<(changeInfo: OnChangedChangeInfoType) => void>; } }
the_stack
import { Observable } from "data/observable"; import { ObservableArray } from "data/observable-array"; /** * List of batch operation execution types. */ export declare enum BatchOperationExecutionContext { /** * Global "before" action. */ before = 0, /** * Operation action is executed. */ execution = 1, /** * Global "after" action. */ after = 2, /** * "Success" action is executed. */ success = 3, /** * "Error" action is executed. */ error = 4, /** * "Completed" action is executed. */ complete = 5, /** * Global "finish all" action. */ finished = 6, /** * Global "cancelled" action. */ cancelled = 7, } /** * Describes a batch. */ export interface IBatch { /** * Adds one or more items for the object in 'items' property. * * @chainable * * @param any ...items One or more item to add. */ addItems(...items: any[]): IBatch; /** * Adds a logger. * * @chainable * * @param {Function} action The logger action. */ addLogger(action: (ctx: IBatchLogContext) => void): IBatch; /** * Defines the global action that is invoke AFTER each operation. * * @chainable * * @param {Function} action The action to invoke. */ after(action: (ctx: IBatchOperationContext) => void): IBatch; /** * Defines the global action that is invoke BEFORE each operation. * * @chainable * * @param {Function} action The action to invoke. */ before(action: (ctx: IBatchOperationContext) => void): IBatch; /** * Gets or sets the ID of the batch. * * @property */ id: string; /** * Defines if "checkIfFinished" method should be autmatically invoked after * each operation. * * @chainable * * @param {Boolean} [flag] Automatically invoke "checkIfFinished" method or not. Default: (true) */ invokeFinishedCheckForAll(flag?: boolean): IBatch; /** * Gets or sets the default invoke stradegy for an operation. */ invokeStrategy: InvokeStrategy; /** * Gets the batch wide (observable) array of items. * * @property */ items: ObservableArray<any>; /** * Gets the batch wide (observable) object. * * @property */ object: Observable; /** * Gets or sets the name of the batch. * * @property */ name: string; /** * Sets the invoke stradegy for an operation. * * @chainable * * @param {InvokeStrategy} stradegy The (new) value. */ setInvokeStrategy(stradegy: InvokeStrategy): IBatch; /** * Sets properties for the object in 'object' property. * * @chainable * * @param {Object} properties The object that contains the properties. */ setObjectProperties(properties: any): IBatch; /** * Sets the initial result value. * * @chainable * * @param any value The value. */ setResult(value: any): IBatch; /** * Sets the initial result and execution value. * * @chainable * * @param any value The value. */ setResultAndValue(value: any): IBatch; /** * Sets the initial execution value. * * @chainable * * @param any value The value. */ setValue(value: any): IBatch; /** * Starts all operations. * * @return any The result of the last / of all operations. */ start(): any; /** * Defines the logic that is invoked after all operations have been finished. * * @chainable * * @param {Function} action The action. */ whenAllFinished(action: (ctx: IBatchOperationContext) => void): IBatch; /** * Defined the logic that is invoked when batch have been cancelled. * * @chainable * * @param {Function} action The action. */ whenCancelled(action: (ctx: IBatchOperationContext) => void): IBatch; } /** * Describes a batch log context. */ export interface IBatchLogContext { /** * Gets the underlying batch. * * @property */ batch?: IBatch; /** * Gets the underlying batch operation context. * * @property */ context?: IBatchOperationContext; /** * Gets the log message (value). */ message: any; /** * Gets the underlying batch operation. * * @property */ operation?: IBatchOperation; /** * Gets the timestamp. */ time: Date; } /** * Describes a logger. */ export interface IBatchLogger { /** * Logs a message. * * @chainable * * @param any msg The message to log. */ log(msg: any): IBatchLogger; } /** * Describes a batch operation. */ export interface IBatchOperation { /** * Adds one or more items for the object in 'items' property. * * @chainable * * @param any ...items One or more item to add. */ addItems(...items: any[]): IBatchOperation; /** * Adds a logger. * * @chainable * * @param {Function} action The logger action. */ addLogger(action: (ctx: IBatchLogContext) => void): IBatchOperation; /** * Defines the global action that is invoke AFTER each operation. * * @chainable * * @param {Function} action The action to invoke. */ after(action: (ctx: IBatchOperationContext) => void): IBatchOperation; /** * Gets the underlying batch. * * @property */ batch: IBatch; /** * Gets or sets the ID of the underlying batch. * * @property */ batchId: string; /** * Gets or sets the name of the underlying batch. * * @property */ batchName: string; /** * Defines the global action that is invoke BEFORE each operation. * * @chainable * * @param {Function} action The action to invoke. */ before(action: (ctx: IBatchOperationContext) => void): IBatchOperation; /** * Defines the "completed" action. * * @chainable * * @param {Function} completedAction The "completed" action. */ complete(completedAction: (ctx: IBatchOperationContext) => void): IBatchOperation; /** * Defines the "error" action. * * @chainable * * @param {Function} errorAction The "error" action. */ error(errorAction: (ctx: IBatchOperationContext) => void): IBatchOperation; /** * Gets or sets the ID of the operation. * * @property */ id: string; /** * Ignores error of that operation. * * @chainable * * @param {Boolean} [flag] The flag to set. Default: (true) */ ignoreErrors(flag?: boolean): IBatchOperation; /** * Defines if "checkIfFinished" method should be autmatically invoked after * each operation. * * @chainable * * @param {Boolean} [flag] Automatically invoke "checkIfFinished" method or not. Default: (true) */ invokeFinishedCheckForAll(flag?: boolean): IBatchOperation; /** * Gets or sets the invoke stradegy for that operation. */ invokeStrategy: InvokeStrategy; /** * Gets the batch wide (observable) array of items. * * @property */ items: ObservableArray<any>; /** * Gets the batch wide (observable) object. * * @property */ object: Observable; /** * Gets or sets the name of the operation. * * @property */ name: string; /** * Defines the next operation. * * @chainable * * @param {Function} action The logic of the next operation. */ next(action: (ctx: IBatchOperationContext) => void): IBatchOperation; /** * Sets the ID of the underlying batch. * * @param {String} id The new ID. * * @chainable */ setBatchId(id: string): IBatchOperation; /** * Sets the name of the underlying batch. * * @param {String} name The new name. * * @chainable */ setBatchName(name: string): IBatchOperation; /** * Sets the ID of the operation. * * @param {String} id The new ID. * * @chainable */ setId(id: string): IBatchOperation; /** * Sets the invoke stradegy for that operation. * * @chainable * * @param {InvokeStrategy} stradegy The (new) value. */ setInvokeStrategy(stradegy: InvokeStrategy): IBatchOperation; /** * Sets the name of the operation. * * @param {String} name The new name. * * @chainable */ setName(name: string): IBatchOperation; /** * Sets properties for the object in 'object' property. * * @chainable * * @param {Object} properties The object that contains the properties. */ setObjectProperties(properties: any): IBatchOperation; /** * Sets the initial result value for all operations. * * @chainable * * @param any value The value. */ setResult(value: any): IBatchOperation; /** * Sets the initial result and execution value for all operations. * * @chainable * * @param any value The value. */ setResultAndValue(value: any): IBatchOperation; /** * Sets the initial execution value for all operations. * * @chainable * * @param any value The value. */ setValue(value: any): IBatchOperation; /** * Starts all operations. * * @return any The result of the last / of all operations. */ start(): any; /** * Defines the "success" action. * * @chainable * * @param {Function} successAction The "success" action. */ success(successAction: (ctx: IBatchOperationContext) => void): IBatchOperation; /** * Alias for 'next()'. * * @chainable * * @param {Function} action The logic of the next operation. */ then(action: (ctx: IBatchOperationContext) => void): IBatchOperation; /** * Defines the logic that is invoked after all operations have been finished. * * @chainable * * @param {Function} action The action. */ whenAllFinished(action: (ctx: IBatchOperationContext) => void): IBatchOperation; /** * Defined the logic that is invoked when batch have been cancelled. * * @chainable * * @param {Function} action The action. */ whenCancelled(action: (ctx: IBatchOperationContext) => void): IBatchOperation; } /** * Describes a context of a batch operation. */ export interface IBatchOperationContext extends IBatchLogger { /** * Gets the underlying batch. * * @property */ batch: IBatch; /** * Gets the ID of the underlying batch. * * @property */ batchId: string; /** * Gets the name of the underlying batch. * * @property */ batchName: string; /** * Cancels all upcoming operations. * * @chainable * * @param {Boolean} [flag] Cancel upcoming operations or not. Default: (true) */ cancel(flag?: boolean): IBatchOperationContext; /** * Marks that operation as finished. * * @chainable */ checkIfFinished(): IBatchOperationContext; /** * Gets the name of the execution context. * * @property */ context: string; /** * Gets the thrown error. * * @property */ error?: any; /** * Gets the current execution context. * * @property */ executionContext?: BatchOperationExecutionContext; /** * Gets the ID of the underlying operation. * * @property */ id: string; /** * Gets the zero based index. * * @property */ index: number; /** * Defines if action should be invoked or not. */ invokeAction: boolean; /** * Defines if global "after" action should be invoked or not. */ invokeAfter: boolean; /** * Defines if global "before" action should be invoked or not. */ invokeBefore: boolean; /** * Defines if "completed" action should be invoked or not. */ invokeComplete: boolean; /** * Defines if "error" action should be invoked or not. */ invokeError: boolean; /** * Invokes the next operation. * * @chainable */ invokeNext(): IBatchOperationContext; /** * Defines if "success" action should be invoked or not. */ invokeSuccess: boolean; /** * Gets if the operation is NOT the first AND NOT the last one. * * @property */ isBetween: boolean; /** * Gets if that operation is the FIRST one. * * @property */ isFirst: boolean; /** * Gets if that operation is the LAST one. * * @property */ isLast: boolean; /** * Gets the batch wide (observable) array of items. * * @property */ items: ObservableArray<any>; /** * Gets the name of the underlying operation. * * @property */ name: string; /** * Gets or sets the invoke stradegy for the next operation. */ nextInvokeStradegy: InvokeStrategy; /** * Gets or sets the value for the next operation. * * @property */ nextValue: any; /** * Gets the batch wide (observable) object. * * @property */ object: Observable; /** * Gets the underlying operation. * * @property */ operation: IBatchOperation; /** * Gets the value from the previous operation. * * @property */ prevValue: any; /** * Gets or sets the result for all operations. * * @property */ result: any; /** * Sets the invoke stradegy for the next operation. * * @chainable * * @param {InvokeStrategy} stradegy The (new) value. */ setNextInvokeStradegy(stradegy: InvokeStrategy): IBatchOperationContext; /** * Sets the values for 'result' any 'value' properties. * * @chainable * * @param any value The value to set. */ setResultAndValue(value: any): IBatchOperationContext; /** * Sets the number of operations to skip. * * @chainable * * @param {Number} cnt The number of operations to skip. Default: 1 */ skip(cnt?: number): IBatchOperationContext; /** * Skips all upcoming operations. * * @chainable * * @param {Boolean} [flag] Skip all upcoming operations or not. Default: (true) */ skipAll(flag?: boolean): IBatchOperationContext; /** * Defines if next operation should be skipped or not. * * @chainable * * @param {Boolean} [flag] Skip next operation or not. Default: (true) */ skipNext(flag?: boolean): IBatchOperationContext; /** * Skips all upcoming operations that matches a predicate. * * @chainable * * @param {Function} predicate The predicate to use. */ skipWhile(predicate: (ctx: IBatchOperationContext) => boolean): IBatchOperationContext; /** * Gets or sets the value for that and all upcoming operations. */ value: any; } /** * List of invoke stradegies. */ export declare enum InvokeStrategy { /** * Automatic */ Automatic = 0, /** * From batch operation. */ Manually = 1, } /** * Creates a new batch. * * @function newBatch * * @return {IBatchOperation} The first operation of the created batch. */ export declare function newBatch(firstAction: (ctx: IBatchOperationContext) => void): IBatchOperation;
the_stack
import * as React from 'react'; // tslint:disable-next-line: no-submodule-imports import { act } from 'react-dom/test-utils'; import { mount } from 'enzyme'; import { PluginHost } from '@devexpress/dx-react-core'; import { pluginDepsToComponents, executeComputedAction } from '@devexpress/dx-testing'; import { ConfirmationDialog } from './confirmation-dialog'; describe('ConfirmationDialog', () => { const defaultDeps = { template: { schedulerRoot: {}, }, plugins: ['EditingState'], getter: { editingAppointment: {}, }, action: { toggleAppointmentFormVisibility: jest.fn(), toggleAppointmentTooltipVisibility: jest.fn(), stopEditAppointment: jest.fn(), finishDeleteAppointment: jest.fn(), cancelAddedAppointment: jest.fn(), cancelChangedAppointment: jest.fn(), }, }; const defaultProps = { layoutComponent: () => null, overlayComponent: ({ children }) => <div>{children}</div>, containerComponent: ({ children }) => <div>{children}</div>, buttonComponent: () => null, }; afterEach(() => { jest.resetAllMocks(); }); it('should render Layout component', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); const layout = tree.find(defaultProps.layoutComponent); expect(layout.props()) .toMatchObject({ isDeleting: false, buttonComponent: defaultProps.buttonComponent, handleCancel: expect.any(Function), handleConfirm: expect.any(Function), getMessage: expect.any(Function), }); }); it('should render Overlay component', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); const overlay = tree.find(defaultProps.overlayComponent); expect(overlay.props()) .toEqual({ target: expect.any(Object), visible: false, onHide: expect.any(Function), children: expect.any(Object), }); }); it('should render Container component', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); const container = tree.find(defaultProps.containerComponent); expect(container.exists()) .toBeTruthy(); }); it('should provide openCancelConfirmationDialog action', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); expect(() => executeComputedAction(tree, (computedActions) => { computedActions.openCancelConfirmationDialog('appointmentForm'); })).not.toThrow(); }); it('should provide openDeleteConfirmationDialog action', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps, { getter: {} })} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); expect(() => executeComputedAction(tree, (computedActions) => { computedActions.openDeleteConfirmationDialog({ caller: 'abc', appointmentData: { title: 'a' }, }); })).not.toThrow(); }); it('shouldn\'t provide openCancelConfirmationDialog action if ignoreCancel is true', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} ignoreCancel /> </PluginHost> )); expect(() => executeComputedAction(tree, (computedActions) => { computedActions.openCancelConfirmationDialog(); })).toThrow(); }); it('shouldn\'t provide confirmCancelChanges action if ignoreDelete is true', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} ignoreDelete /> </PluginHost> )); expect(() => executeComputedAction(tree, (computedActions) => { computedActions.openDeleteConfirmationDialog(); })).toThrow(); }); it('should confirm cancel action dispatched by the AppointmentForm and close it', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); // open the dialog executeComputedAction(tree, (computedActions) => { computedActions.openCancelConfirmationDialog('toggleAppointmentFormVisibility'); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleConfirm')(); }); expect(defaultDeps.action.toggleAppointmentFormVisibility) .toBeCalled(); expect(defaultDeps.action.cancelChangedAppointment) .toBeCalled(); expect(defaultDeps.action.stopEditAppointment) .toBeCalled(); }); it('should confirm cancel action dispatched by the AppointmentTooltip and close it', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); // open the dialog executeComputedAction(tree, (computedActions) => { computedActions.openCancelConfirmationDialog('toggleAppointmentTooltipVisibility'); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleConfirm')(); }); expect(defaultDeps.action.toggleAppointmentTooltipVisibility) .toBeCalled(); expect(defaultDeps.action.cancelChangedAppointment) .toBeCalled(); expect(defaultDeps.action.stopEditAppointment) .toBeCalled(); }); it('should confirm delete action dispatched by the AppointmentForm and close it', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); // open the dialog executeComputedAction(tree, (computedActions) => { computedActions.openDeleteConfirmationDialog({ hideActionName: 'toggleAppointmentFormVisibility', appointmentData: {}, }); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleConfirm')(); }); expect(defaultDeps.action.toggleAppointmentFormVisibility) .toBeCalled(); expect(defaultDeps.action.finishDeleteAppointment) .toBeCalled(); expect(defaultDeps.action.cancelChangedAppointment) .toBeCalled(); expect(defaultDeps.action.stopEditAppointment) .toBeCalled(); }); it('should confirm delete action dispatched by the AppointmentTooltip and close it', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); // open the dialog executeComputedAction(tree, (computedActions) => { computedActions.openDeleteConfirmationDialog({ hideActionName: 'toggleAppointmentTooltipVisibility', appointmentData: {}, }); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleConfirm')(); }); expect(defaultDeps.action.toggleAppointmentTooltipVisibility) .toBeCalled(); expect(defaultDeps.action.finishDeleteAppointment) .toBeCalled(); expect(defaultDeps.action.cancelChangedAppointment) .toBeCalled(); expect(defaultDeps.action.stopEditAppointment) .toBeCalled(); }); it('should cancel the cancel action dispatched by the AppointmentForm', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); // open the dialog executeComputedAction(tree, (computedActions) => { computedActions.openCancelConfirmationDialog('toggleAppointmentFormVisibility'); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleCancel')(); }); expect(defaultDeps.action.toggleAppointmentFormVisibility) .not.toBeCalled(); expect(defaultDeps.action.cancelChangedAppointment) .not.toBeCalled(); expect(defaultDeps.action.stopEditAppointment) .not.toBeCalled(); }); it('should cancel the cancel action dispatched by the AppointmentTooltip', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); // open the dialog executeComputedAction(tree, (computedActions) => { computedActions.openCancelConfirmationDialog('toggleAppointmentTooltipVisibility'); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleCancel')(); }); expect(defaultDeps.action.toggleAppointmentTooltipVisibility) .not.toBeCalled(); expect(defaultDeps.action.cancelChangedAppointment) .not.toBeCalled(); expect(defaultDeps.action.stopEditAppointment) .not.toBeCalled(); }); it('should cancel the delete action dispatched by the AppointmentForm', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); executeComputedAction(tree, (computedActions) => { computedActions.openDeleteConfirmationDialog({ hideActionName: 'toggleAppointmentFormVisibility', appointmentData: {}, }); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleCancel')(); }); expect(defaultDeps.action.toggleAppointmentFormVisibility) .not.toBeCalled(); expect(defaultDeps.action.finishDeleteAppointment) .not.toBeCalled(); expect(defaultDeps.action.cancelChangedAppointment) .not.toBeCalled(); expect(defaultDeps.action.stopEditAppointment) .not.toBeCalled(); }); it('should cancel the delete action dispatched by the AppointmentTooltip', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents(defaultDeps)} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); executeComputedAction(tree, (computedActions) => { computedActions.openDeleteConfirmationDialog({ hideActionName: 'toggleAppointmentTooltipVisibility', appointmentData: {}, }); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleCancel')(); }); expect(defaultDeps.action.toggleAppointmentTooltipVisibility) .not.toBeCalled(); expect(defaultDeps.action.finishDeleteAppointment) .not.toBeCalled(); expect(defaultDeps.action.cancelChangedAppointment) .not.toBeCalled(); expect(defaultDeps.action.stopEditAppointment) .not.toBeCalled(); }); it('should correctly cancel a new appointment and close AppointmentForm', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents({ ...defaultDeps, getter: { ...defaultDeps.getter, editingAppointment: undefined }, })} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); executeComputedAction(tree, (computedActions) => { computedActions.openCancelConfirmationDialog('toggleAppointmentFormVisibility'); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleConfirm')(); }); expect(defaultDeps.action.toggleAppointmentFormVisibility) .toBeCalled(); expect(defaultDeps.action.cancelAddedAppointment) .toBeCalled(); }); it('should correctly delete a new appointment and close AppointmentForm', () => { const tree = mount(( <PluginHost> {pluginDepsToComponents({ ...defaultDeps, getter: { ...defaultDeps.getter, editingAppointment: undefined }, })} <ConfirmationDialog {...defaultProps} /> </PluginHost> )); executeComputedAction(tree, (computedActions) => { computedActions.openDeleteConfirmationDialog({ hideActionName: 'toggleAppointmentFormVisibility', appointmentData: {}, }); }); tree.update(); act(() => { tree.find(defaultProps.layoutComponent).prop('handleConfirm')(); }); expect(defaultDeps.action.toggleAppointmentFormVisibility) .toBeCalled(); expect(defaultDeps.action.finishDeleteAppointment) .toBeCalled(); expect(defaultDeps.action.cancelAddedAppointment) .toBeCalled(); }); });
the_stack
import {Observable, Subject} from 'rxjs'; import { ClearCacheOptions, DispatchFailReason, DispatchOptions, DispatchValueProducer, EventUnitClear, EventUnitClearCache, EventUnitClearPersistedValue, EventUnitClearValue, EventUnitDispatch, EventUnitDispatchFail, EventUnitFreeze, EventUnitJump, EventUnitReset, EventUnitResetValue, EventUnitUnfreeze, EventUnitUnmute, UnitConfig, UnitEvents, UnitStreamObservableProducer, } from '../models'; import {Base} from './abstract-base'; import {Configuration} from './configuration'; import {Stream} from './stream'; import {remove, retrieve, save} from './persistence'; import {debounce, deepCopy, deepFreeze, isNumber} from '../utils/funcs'; import {checkSerializability} from '../checks/common'; /** * UnitBase serves as the base for all the ActiveJS Units: GenericUnit, BoolUnit, ListUnit, etc. * It extends {@link Base}. * * This is an internal construct, normally you'd never have to use this class directly. * However, if you're just reading the documentation, or want to learn more about how ActiveJS works, * or want to extend this class to build something on your own, please continue. * * UnitBase creates the foundation of all the ActiveJS Units. * It implements the features like: * - dispatching, clearing and resetting the value * - caching the dispatched values * - navigating through the cached values, by methods like goBack, goForward, jump etc. * - observable events to listen to including but not limited to the above mentioned actions * - freezing/unfreezing the Unit * - muting/unmuting the Unit * - persisting and retrieving the value to/from persistent-storage * - debouncing the dispatch * - resetting the Unit * - etc. * * @category 2. Abstract */ export abstract class UnitBase<T> extends Base<T> { /** * Configured options. * Combination of global-options {@link GlobalUnitConfig} and the options passed on instantiation. */ readonly config: Readonly<UnitConfig<T>>; // tslint:disable:variable-name /** * @internal please do not use. */ protected readonly eventsSubject: Subject<UnitEvents<T>>; /** * On-demand observable events. */ readonly events$: Observable<UnitEvents<T>>; /** * @internal please do not use. */ private _isFrozen = false; /** * Indicates whether the Unit is frozen or not. * See {@link freeze} for more details. * * Note: It's not the same as [Object.isFrozen](https://cutt.ly/WyFdzPD). */ get isFrozen(): boolean { return this._isFrozen; } /** * @internal please do not use. */ private emitOnUnmute: boolean; /** * @internal please do not use. */ private _isMuted = false; /** * Indicates whether the Unit is muted or not. * See {@link mute} for more details. */ get isMuted(): boolean { return this._isMuted; } /** * Indicates whether the value is undefined or not. * * It should be preferred if the Unit is configured to be immutable, as it doesn't create a copy. */ get isEmpty(): boolean { return this.rawValue() === this.defaultValue(); } /** * Size of the cache, dictating how many values can be cached at a given time. * * @default `2` * @minimum `1` * @maximum `Infinity` */ readonly cacheSize: number; /** * @internal please do not use. */ protected readonly _cachedValues: T[] = []; /** * Count of all the cached values. */ get cachedValuesCount(): number { return this._cachedValues.length; } /** * @internal please do not use. */ private _cacheIndex = 0; /** * Index of the current {@link value} in the {@link UnitBase.cachedValues} */ get cacheIndex(): number { return this._cacheIndex; } /** * @internal please do not use. */ private _initialValue: T = undefined; /** * @internal please do not use. */ protected _value: T; /** * The initialValue provided on instantiation. * Creates a copy if the Unit is configured to be immutable. * * @category Access Value */ initialValue(): T { return this.deepCopyMaybe(this.initialValueRaw()); } /** * Current value of the Unit. * Creates a copy if the Unit is configured to be immutable. * * @default * BoolUnit: `false` \ * NumUnit: `0` \ * StringUnit: `''` \ * ListUnit: `[]` \ * DictUnit: `{}` \ * GenericUnit: `undefined` * * @category Access Value */ value(): T { return this.deepCopyMaybe(this.rawValue()); // apply the fallback and kill reference } /** * If the Unit has a non-primitive value, * use it to get access to the current {@link value}, without creating a deep-copy. * * This can come in handy if the Unit is configured to be immutable, and you want to perform a non-mutating action * without creating a deep-copy of the value. * * @category Access Value */ rawValue(): T { return this.applyFallbackValue(this._value); } /** * All the cached values. * Creates a copy if the Unit is configured to be immutable. * * @category Access Value */ cachedValues(): T[] { return this._cachedValues.map(value => this.deepCopyMaybe(value)); } /** * @internal please do not use. */ private initialValueRaw(): T { return this.applyFallbackValue(this._initialValue); } /** * @internal please do not use. */ protected defaultValue(): T { return undefined; } // tslint:enable:variable-name /** * @internal please do not use. */ protected constructor(config?: UnitConfig<T>) { super({ ...Configuration.UNITS, ...config, }); const { cacheSize, initialValue, dispatchDebounce, dispatchDebounceMode, persistent, }: UnitConfig<T> = this.config; this.cacheSize = isNumber(cacheSize) ? Math.max(1, cacheSize) : 2; // min 1, default 2 if (persistent === true) { this.restoreValueFromPersistentStorage(initialValue); } else { this.checkSerializabilityMaybe(initialValue); this.dispatchInitialValue(this.deepCopyMaybe(initialValue)); } if (dispatchDebounce === true || isNumber(dispatchDebounce)) { this.dispatchMiddleware = debounce( this.dispatchMiddleware.bind(this), dispatchDebounce as number, dispatchDebounceMode ); } } /** * A helper method that creates a stream by subscribing to the Observable returned by the param `observableProducer` callback. * * Ideally the callback function creates an Observable by applying `Observable.pipe`. * * Just know that you should catch the error in a sub-pipe (ie: do not let it propagate to the main-pipe), otherwise * as usual the stream will stop working, and will not react on any further emissions. * * @param observableProducer A callback function that should return an Observable. * * @category Common */ createStream<R>(observableProducer: UnitStreamObservableProducer<this, R>): Stream { const observable = observableProducer(this); return new Stream(observable); } /** * Given a value, this function determines whether it should be dispatched or not. \ * The dispatch is denied in following circumstances: * - If the Unit is frozen. {@link isFrozen} * - If {@link UnitConfig.distinctDispatchCheck} is set to `true`, and the new-value === current-value, * - If {@link UnitConfig.customDispatchCheck} returns a `falsy` value. * * If the Unit is not frozen, you can bypass other dispatch-checks by passing param `force = true`. * * This function is used internally, when a value is dispatched {@link dispatch}. \ * Even initialValue {@link UnitConfig.initialValue} dispatch has to pass this check. * * You can also use it to check if the value will be dispatched or not before dispatching it. * * @param value The value to be dispatched. * @param force Whether dispatch-checks should be bypassed or not. * @returns A boolean indicating whether the param `value` would pass the dispatch-checks if dispatched. * * @category Common Units */ wouldDispatch(value: T, force = false): boolean { if (this.isFrozen) { return false; } if (force === true) { return true; } if ( typeof this.config.customDispatchCheck === 'function' && !this.config.customDispatchCheck(this.rawValue(), value) ) { return false; } return this.distinctCheck(value); } dispatch(value: T, options?: DispatchOptions): boolean | undefined; dispatch( // tslint:disable-next-line:unified-signatures valueProducer: DispatchValueProducer<T>, options?: DispatchOptions ): boolean | undefined; /** * Method to dispatch new value by passing the value directly, or \ * by passing a value-producer-function that produces the value using the current {@link value}. * * Given a value, it either gets dispatched if it's allowed by {@link wouldDispatch}, \ * or it gets ignored if not allowed. * * If the Unit is not configured to be immutable, then \ * the value-producer-function (param `valueOrProducer`) should not mutate the current {@link value}, \ * which is provided as an argument to the function. * * If you mutate the value, then the cached-value might also get mutated, \ * as the cached-value is saved by reference, which can result in unpredictable state. * * @param valueOrProducer A new-value, or a pure function that produces a new-value. * @param options Dispatch options. * @returns `true` if value got dispatched, otherwise `false`. * If {@link UnitConfig.dispatchDebounce} is enabled, then it'll return `undefined`. * * @triggers {@link EventUnitDispatch}, or {@link EventUnitDispatchFail}, depending on the success of dispatch. * @category Common Action/Units */ dispatch( valueOrProducer: DispatchValueProducer<T> | T, options?: DispatchOptions ): boolean | undefined { if (options?.bypassDebounce === true) { return this.dispatchActual(valueOrProducer, options); } return this.dispatchMiddleware(valueOrProducer, options); } /** * To manually re-emit the last emitted value again. \ * It doesn't work if the Unit is frozen {@link isFrozen} or muted {@link isMuted}. * * Note: Even if the Unit is immutable, it does not create a copy of the Unit's value, * it merely re-emits the last emitted value. * * @returns `true` if replayed successfully, otherwise `false`. * * @triggers {@link EventReplay} * @category Common */ replay(): boolean { if (this.isFrozen || this.isMuted) { return false; } super.replay(); return true; } /** * Go back in the cache and re-emit the previous value from the cache, \ * without creating a new entry in the cache. * * It can be used as Undo. * * It doesn't work if the Unit is frozen {@link isFrozen}. * It only works if there's a previously dispatched value in the cache. \ * ie: the {@link cacheIndex} is not 0 * * @returns `true` if the cache-navigation was successful, otherwise `false`. * * @triggers {@link EventUnitJump} * @category Cache Navigation */ goBack(): boolean { return this.jump(-1); } /** * After going back in the cache (ie: re-emitting an old value from the cache), \ * use this method to go to the next value, without creating a new entry in the cache. * * It can be used as Redo. * * It doesn't work if the Unit is frozen {@link isFrozen}. * It only works if the current {@link value} is not the last value in the cache. \ * ie: the {@link cacheIndex} is not equal to `cachedValuesCount - 1` * * @returns `true` if the cache-navigation was successful, otherwise `false` * * @triggers {@link EventUnitJump} * @category Cache Navigation */ goForward(): boolean { return this.jump(1); } /** * Use this method to re-emit the first value in the cache, \ * without creating a new entry in the cache. * * It doesn't work if the Unit is frozen {@link isFrozen}. * It only works if the {@link cacheIndex} is not already at the last value in the cache. \ * ie: the {@link cacheIndex} is not 0. * * @returns `true` if the cache-navigation was successful, otherwise `false` * * @triggers {@link EventUnitJump} * @category Cache Navigation */ jumpToStart(): boolean { return this.jump(-this.cacheIndex); } /** * After going back in the cache (ie: re-emitting an old value from the cache), \ * use this method to re-dispatch the last (latest) value in the cache, \ * without creating a new entry in the cache. * * It doesn't work if the Unit is frozen {@link isFrozen}. * It only works if the {@link cacheIndex} is not already at the last value in the cache. * * @returns `true` if the cache-navigation was successful, otherwise `false` * * @triggers {@link EventUnitJump} * @category Cache Navigation */ jumpToEnd(): boolean { return this.jump(this.cachedValuesCount - 1 - this.cacheIndex); } /** * Use this method to re-emit a value from the cache, by jumping specific steps backwards or forwards, \ * without creating a new entry in the cache. * * It doesn't work if the Unit is frozen {@link isFrozen} or `steps` is not a `number`. * It only works if the new calculated index is in the bounds of {@link cachedValues}, \ * ie: the new-index is >= 0, and less than {@link cachedValuesCount}, but \ * not equal to current {@link cacheIndex}. * * @param steps Number of steps to jump in the cache, negative to jump backwards, positive to jump forwards * @returns `true` if the cache-navigation was successful, otherwise `false`. * * @triggers {@link EventUnitJump} * @category Cache Navigation */ jump(steps: number): boolean { if (this.isFrozen || !isNumber(steps)) { return false; } const newIndex = this.cacheIndex + steps; // no point going forward if (newIndex < 0 || newIndex === this.cacheIndex || newIndex > this.cachedValuesCount - 1) { return false; } this._cacheIndex = newIndex; this.updateValueAndCache(this._cachedValues[this.cacheIndex], null, true); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitJump(steps, newIndex)); } return true; } /** * Get cached value at a given index. * * @param index The index of cached value * @returns The cached value if it exists, otherwise undefined * * @category Common Units */ getCachedValue(index: number): T | undefined { return this._cachedValues.hasOwnProperty(index) ? this.deepCopyMaybe(this._cachedValues[index]) : undefined; } /** * Clears the cached values, current {@link value} stays intact, but it gets removed from the cache. \ * Meaning, if you dispatch a new value you can't {@link goBack}. \ * To keep the last value in the cache, pass `{leaveLast: true}` in the param `options`. * * It only works if the Unit is not frozen and there's something left to clear after evaluating the param `options`. * * Similar to preserving the last value, you can preserve the first value by passing `{leaveFirst: true}`. * Or preserve both first and last value by passing both options together. * * @param options Clear cache options * @returns `true` if the cache was cleared, otherwise `false` * * @triggers {@link EventUnitClearCache} * @category Common Units */ clearCache(options?: ClearCacheOptions): boolean { const leaveFirst: boolean = options?.leaveFirst === true; const leaveLast: boolean = options?.leaveLast === true; if ( this.isFrozen || this.cachedValuesCount === 0 || (this.cachedValuesCount === 1 && (leaveFirst || leaveLast)) || (this.cachedValuesCount === 2 && leaveFirst && leaveLast) ) { return false; } const start = leaveFirst ? 1 : 0; const deleteCount = this.cachedValuesCount - start - (leaveLast ? 1 : 0); this._cachedValues.splice(start, deleteCount); this._cacheIndex = Math.max(0, this.cachedValuesCount - 1); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitClearCache(options)); } return true; } /** * Clears the value by dispatching the default value. \ * It only works if the Unit is not frozen, and {@link emitCount} is not 0, and value is not empty {@link isEmpty}. * * @returns `true` if the value was cleared, otherwise `false` * * @triggers {@link EventUnitClearValue} * @category Common Units */ clearValue(): boolean { if (this.isFrozen || this.emitCount === 0 || this.isEmpty) { return false; } this.updateValueAndCache(this.defaultValue()); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitClearValue()); } return true; } /** * Holistically clears the Unit, \ * unfreezes using {@link unfreeze}, \ * clears the value using {@link clearValue}, \ * completely clears cache using {@link clearCache}, \ * in that specific order. * * @param options Clear cache options for {@link clearCache}. * * @triggers {@link EventUnitClear} * @category Common Units */ clear(options?: ClearCacheOptions): void { this.unfreeze(); this.clearValue(); this.clearCache(options); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitClear(options)); } } /** * Resets the value by dispatching the initial-value, {@link UnitConfig.initialValue} if provided, \ * otherwise dispatches the default value. * * It only works if the Unit is not frozen, \ * and the {@link value} is not equal to the {@link initialValue}. * * @returns `true` if the reset was successful, otherwise `false` * * @triggers {@link EventUnitResetValue} * @category Common Units */ resetValue(): boolean { if (this.isFrozen || this.rawValue() === this.initialValueRaw()) { return false; } this.updateValueAndCache(this.initialValueRaw()); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitResetValue()); } return true; } /** * Holistically resets the Unit, \ * unfreezes using {@link unfreeze}, \ * resets the value using {@link resetValue}, \ * clears cache using {@link clearCache} and by default leaves last value; \ * in that specific order. * * @param options Clear cache options for {@link clearCache}. default is `{leaveLast: true}` * * @triggers {@link EventUnitReset} * @category Common Units */ reset(options: ClearCacheOptions = {leaveLast: true}): void { this.unfreeze(); this.resetValue(); this.clearCache(options); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitReset(options)); } } /** * Temporarily disables most of the functions of the Unit, except {@link unfreeze}, \ * {@link mute}/{@link unmute}, {@link clear} and {@link reset}. * * It's not the same as `Object.freeze`. * * Freezing prevents any new values from getting dispatched, \ * it disables all the mutating functions. \ * Which eventually ensures that no event is emitted while the Unit is frozen, \ * however all the read operations and operations that do not emit a value are allowed. * * @triggers {@link EventUnitFreeze} * @category Common Units */ freeze(): void { // tslint:disable-next-line:no-console console.trace(); if (this.isFrozen) { return; } this._isFrozen = true; if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitFreeze()); } } /** * Unfreezes the Unit, and re-enables all the functions disabled by {@link freeze}. \ * It only works if the Unit is frozen. * * @triggers {@link EventUnitUnfreeze} * @category Common Units */ unfreeze(): void { if (!this.isFrozen) { return; } this._isFrozen = false; if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitUnfreeze()); } } /** * Mute the Unit, to stop emitting values as well as events, so that the subscribers are not triggered. \ * All other functionalities stay unaffected. ie: cache it still updated, value is still updated. * * Note: If you subscribe to the default Observable while the Unit is muted, \ * it will replay the last value emitted before muting the Unit, \ * because new values are not being emitted. * * @category Common Units */ mute(): void { this._isMuted = true; } /** * Unmute the Unit, to resume emitting values, and events. \ * If a value was dispatched while the Unit was muted, the most recent value immediately gets emitted, \ * so that subscribers can be in sync again. \ * However, other {@link events$} are lost, and they will only emit on the next event. * * It only works if the Unit is muted. \ * Moreover, it works even if the Unit is frozen, \ * but no value will be emitted because no values would have been dispatched while the Unit was frozen. * * @triggers {@link EventUnitUnmute} * @category Common Units */ unmute(): void { if (!this.isMuted) { return; } this._isMuted = false; if (this.emitOnUnmute) { this.emit(); this.emitOnUnmute = null; } if (this.eventsSubject?.observers.length) { this.eventsSubject.next(new EventUnitUnmute()); } } /** * Clears persisted value from persistent storage. \ * It doesn't turn off persistence, future values will get persisted again. * * It only works if the Unit is configured to be persistent. ie: `options.persistent` is true. * * @returns `true` if the Unit is configured to be persistent, otherwise `false`. * * @triggers {@link EventUnitClearPersistedValue} * @category Common Units */ clearPersistedValue(): boolean { if (this.config.persistent === true) { remove(this.config.id, this.config.storage); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitClearPersistedValue()); } return true; } return false; } /** * @internal please do not use. */ protected abstract isValidValue(value: any): boolean; /** * @internal please do not use. */ protected deepCopyMaybe<U>(o: U): U { return this.config.immutable === true ? deepCopy(o) : o; } /** * @internal please do not use. */ protected checkSerializabilityMaybe(o: any): void { if (Configuration.ENVIRONMENT.checkSerializability === true) { checkSerializability(o); } } /** * @internal please do not use. */ protected updateValueAndCache(value: T, options?: DispatchOptions, skipCache = false): void { const {cacheReplace}: DispatchOptions = options || {}; if (Configuration.ENVIRONMENT.checkImmutability === true) { deepFreeze(value); } if (!skipCache) { this.updateCache(value, cacheReplace); } this._value = value; if (this.isMuted) { this.emitOnUnmute = true; } else { this.emitOnUnmute = null; this.emit(); } this.updateValueInPersistentStorage(); } /** * @internal please do not use. */ protected applyFallbackValue(value: T): T { return value === undefined ? this.defaultValue() : value; } /** * @internal please do not use. */ private distinctCheck(value: T): boolean { return this.config.distinctDispatchCheck !== true || value !== this.rawValue(); } /** * @internal please do not use. */ private dispatchMiddleware( valueOrProducer: DispatchValueProducer<T> | T, options?: DispatchOptions ): boolean { return this.dispatchActual(valueOrProducer, options); } /** * @internal please do not use. */ private dispatchActual( valueOrProducer: DispatchValueProducer<T> | T, options?: DispatchOptions ): boolean { const {force}: DispatchOptions = options || {}; const value: T = typeof valueOrProducer === 'function' ? (valueOrProducer as DispatchValueProducer<T>)(this.value()) : valueOrProducer; this.checkSerializabilityMaybe(value); if (this.wouldDispatch(value, force)) { this.updateValueAndCache(this.deepCopyMaybe(value), options); // clone and dispatch if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventUnitDispatch(value, options)); } return true; } if (this.eventsSubject?.observers.length && !this.isMuted) { const failReason: DispatchFailReason = (this.isFrozen && DispatchFailReason.FROZEN_UNIT) || (this.isValidValue(value) && (this.distinctCheck(value) ? DispatchFailReason.CUSTOM_DISPATCH_CHECK : DispatchFailReason.DISTINCT_CHECK)) || DispatchFailReason.INVALID_VALUE; this.eventsSubject.next(new EventUnitDispatchFail(value, failReason, options)); } return false; } /** * @internal please do not use. */ private shouldDispatchInitialValue(initialValue: T): boolean { // not checking undefined in wouldDispatch to allow undefined values later on (for GenericUnit) return initialValue !== undefined && this.isValidValue(initialValue); } /** * @internal please do not use. */ private updateCache(value: T, cacheReplace?: boolean): void { if (cacheReplace === true) { this._cachedValues[this.cacheIndex] = value; } else { if (this.cachedValuesCount === 0 || this.cacheIndex === this.cachedValuesCount - 1) { this._cachedValues.push(value); if (this.cachedValuesCount > this.cacheSize) { this._cachedValues.shift(); } this._cacheIndex = this.cachedValuesCount - 1; } else { this._cachedValues.splice( this.cacheIndex + 1, this.cachedValuesCount - 1 - this.cacheIndex, value ); ++this._cacheIndex; } } } /** * @internal please do not use. */ private dispatchInitialValue(initialValue) { if (this.shouldDispatchInitialValue(initialValue)) { this._initialValue = initialValue; this.updateValueAndCache(this.initialValueRaw()); } else { this.updateValueAndCache(this.defaultValue()); } } /** * @internal please do not use. */ private updateValueInPersistentStorage() { if (this.config.persistent === true) { save(this.config.id, this.rawValue(), this.config.storage); } } /** * @internal please do not use. */ private restoreValueFromPersistentStorage(initialValue): void { const savedState = retrieve(this.config.id, this.config.storage); if (savedState) { this.dispatchInitialValue(savedState.value); } else { this.checkSerializabilityMaybe(initialValue); this.dispatchInitialValue(this.deepCopyMaybe(initialValue)); } } }
the_stack
import { hashUnknown } from './internal/hashCode'; /** * Represents a value that can compare its equality with another value. */ export interface Equatable { /** * Determines whether this value is equal to another value. * @param other The other value. * @returns `true` if this value is equal to `other`; otherwise, `false`. */ [Equatable.equals](other: unknown): boolean; /** * Compute a hash code for an value. * @returns The numeric hash-code for the value. */ [Equatable.hash](): number; } /** * Utility functions and well-known symbols used to define an `Equatable`. */ export namespace Equatable { // #region Equatable /** * A well-known symbol used to define an equality test method on a value. */ export const equals = Symbol.for("@esfx/equatable:Equatable.equals"); /** * A well-known symbol used to define a hashing method on a value. */ export const hash = Symbol.for("@esfx/equatable:Equatable.hash"); // #endregion Equatable export const name = "Equatable"; /** * Determines whether a value is Equatable. * @param value The value to test. * @returns `true` if the value is an Equatable; otherwise, `false`. */ export function hasInstance(value: unknown): value is Equatable { let obj: object; return value !== undefined && value !== null && equals in (obj = Object(value)) && hash in obj; } Object.defineProperty(Equatable, Symbol.hasInstance, { configurable: true, writable: true, value: hasInstance }); } /* @internal */ export namespace Equatable { const reportIsEquatableDeprecation = createDeprecation("Use 'Equatable.hasInstance' instead."); /** * @deprecated Use `Equatable.hasInstance` instead. */ export function isEquatable(value: unknown): value is Equatable { reportIsEquatableDeprecation(); return Equatable.hasInstance(value); } } /** * Represents a value that can compare itself relationally with another value. */ export interface Comparable { /** * Compares this value with another value, returning a value indicating one of the following conditions: * * - A negative value indicates this value is lesser. * * - A positive value indicates this value is greater. * * - A zero value indicates this value is the same. * * @param other The other value to compare against. * @returns A number indicating the relational comparison result. */ [Comparable.compareTo](other: unknown): number; } /** * Utility functions and well-known symbols used to define a `Comparable`. */ export namespace Comparable { // #region Comparable /** * A well-known symbol used to define a relational comparison method on a value. */ export const compareTo = Symbol.for("@esfx/equatable:Comparable.compareTo"); // #endregion Comparable export const name = "Comparable"; /** * Determines whether a value is Comparable. * @param value The value to test. * @returns `true` if the value is a Comparable; otherwise, `false`. */ export function hasInstance(value: unknown): value is Comparable { return value !== null && value !== undefined && compareTo in Object(value); } Object.defineProperty(Comparable, Symbol.hasInstance, { configurable: true, writable: true, value: hasInstance }); } /* @internal */ export namespace Comparable { const reportIsComparableDeprecation = createDeprecation("Use 'Comparable.hasInstance' instead."); /** * @deprecated Use `Comparable.hasInstance` instead. */ export function isComparable(value: unknown): value is Comparable { reportIsComparableDeprecation(); return Comparable.hasInstance(value); } } /** * Represents a value that can compare its structural equality with another value. */ export interface StructuralEquatable { /** * Determines whether this value is structurally equal to another value using the supplied `Equaler`. * @param other The other value. * @param equaler The `Equaler` to use to test equality. * @returns `true` if this value is structurally equal to `other`; otherwise, `false`. */ [StructuralEquatable.structuralEquals](other: unknown, equaler: Equaler<unknown>): boolean; /** * Compute a structural hash code for a value using the supplied `Equaler`. * @param equaler The `Equaler` to use to generate hashes for values in the structure. * @returns The numeric hash-code of the structure. */ [StructuralEquatable.structuralHash](equaler: Equaler<unknown>): number; } /** * Utility functions and well-known symbols used to define a `StructuralEquatable`. */ export namespace StructuralEquatable { // #region StructuralEquatable /** * A well-known symbol used to define a structural equality test method on a value. */ export const structuralEquals = Symbol.for("@esfx/equatable:StructualEquatable.structuralEquals"); /** * A well-known symbol used to define a structural hashing method on a value. */ export const structuralHash = Symbol.for("@esfx/equatable:StructuralEquatable.structuralHash"); // #endregion StructuralEquatable export const name = "StructuralEquatable"; /** * Determines whether a value is StructuralEquatable. * @param value The value to test. * @returns `true` if the value is StructuralEquatable; otherwise, `false`. */ export function hasInstance(value: unknown): value is StructuralEquatable { let obj: object; return value !== null && value !== undefined && structuralEquals in (obj = Object(value)) && structuralHash in obj; } Object.defineProperty(StructuralEquatable, Symbol.hasInstance, { configurable: true, writable: true, value: hasInstance }); } /* @internal */ export namespace StructuralEquatable { const reportIsStructuralEquatableDeprecation = createDeprecation("Use 'StructuralEquatable.hasInstance' instead."); /** * @deprecated Use `StructuralEquatable.hasInstance` instead. */ export function isStructuralEquatable(value: unknown): value is StructuralEquatable { reportIsStructuralEquatableDeprecation(); return StructuralEquatable.hasInstance(value); } } /** * Represents a value that can compare its structure relationally with another value. */ export interface StructuralComparable { /** * Compares the structure of this value with another value using the supplied comparer, * returning a value indicating one of the following conditions: * - A negative value indicates this value is lesser. * - A positive value indicates this value is greater. * - A zero value indicates this value is the same. * @param other The other value to compare against. * @param comparer The compare to use to compare values in the structure. * @returns A numeric value indicating the relational comparison result. */ [StructuralComparable.structuralCompareTo](other: unknown, comparer: Comparer<unknown>): number; } /** * Utility functions and well-known symbols used to define a `StructuralComparable`. */ export namespace StructuralComparable { // #region StructuralComparable /** * A well-known symbol used to define a structural comparison method on a value. */ export const structuralCompareTo = Symbol.for("@esfx/equatable:StructuralComparable.structuralCompareTo"); // #endregion StructuralComparable export const name = "StructuralComparable"; /** * Determines whether a value is StructuralComparable. * @param value The value to test. * @returns `true` if the value is StructuralComparable; otherwise, `false`. */ export function hasInstance(value: unknown): value is StructuralComparable { return value !== null && value !== undefined && structuralCompareTo in Object(value); } Object.defineProperty(StructuralComparable, Symbol.hasInstance, { configurable: true, writable: true, value: hasInstance }); } /* @internal */ export namespace StructuralComparable { const reportIsStructuralComparableDeprecation = createDeprecation("Use 'StructuralComparable.hasInstance' instead."); /** * @deprecated Use `StructuralComparable.hasInstance` instead. */ export function isStructuralComparable(value: unknown): value is StructuralComparable { reportIsStructuralComparableDeprecation(); return StructuralComparable.hasInstance(value); } } /** * Describes a function that can be used to compare the equality of two values. * @typeParam T The type of value that can be compared. */ export type EqualityComparison<T> = (x: T, y: T) => boolean; /** * Describes a function that can be used to compute a hash code for a value. * @typeParam T The type of value that can be hashed. */ export type HashGenerator<T> = (x: T) => number; /** * Represents an object that can be used to compare the equality of two values. * @typeParam T The type of each value that can be compared. */ export interface Equaler<T> { /** * Tests whether two values are equal to each other. * @param x The first value. * @param y The second value. * @returns `true` if the values are equal; otherwise, `false`. */ equals(x: T, y: T): boolean; /** * Generates a hash code for a value. * @param x The value to hash. * @returns The numeric hash-code for the value. */ hash(x: T): number; } /** * Provides various implementations of `Equaler`. */ export namespace Equaler { const equalerPrototype = Object.defineProperty({}, Symbol.toStringTag, { configurable: true, value: "Equaler" }); /** * Gets the default `Equaler`. */ export const defaultEqualer: Equaler<unknown> = create( (x, y) => Equatable.hasInstance(x) ? x[Equatable.equals](y) : Equatable.hasInstance(y) ? y[Equatable.equals](x) : Object.is(x, y), (x) => Equatable.hasInstance(x) ? x[Equatable.hash]() : hashUnknown(x) ); /** * Gets a default `Equaler` that supports `StructuralEquatable` values. */ export const structuralEqualer: Equaler<unknown> = create( (x, y) => StructuralEquatable.hasInstance(x) ? x[StructuralEquatable.structuralEquals](y, structuralEqualer) : StructuralEquatable.hasInstance(y) ? y[StructuralEquatable.structuralEquals](x, structuralEqualer) : defaultEqualer.equals(x, y), (x) => StructuralEquatable.hasInstance(x) ? x[StructuralEquatable.structuralHash](structuralEqualer) : defaultEqualer.hash(x)); /** * An `Equaler` that compares array values rather than the arrays themselves. */ export const tupleEqualer: Equaler<readonly unknown[]> = create( (x, y) => { if (!Array.isArray(x) && x !== null && x !== undefined || !Array.isArray(y) && y !== null && y !== undefined) { throw new TypeError("Array expected"); } if (x === y) { return true; } if (!x || !y || x.length !== y.length) { return false; } for (let i = 0; i < x.length; i++) { if (!Equaler.defaultEqualer.equals(x[i], y[i])) { return false; } } return true; }, (x) => { if (x === null || x === undefined) { return 0; } if (!Array.isArray(x)) { throw new TypeError("Array expected"); } let hc = 0; for (const item of x) { hc = combineHashes(hc, Equaler.defaultEqualer.hash(item)); } return hc; }); /** * An `Equaler` that compares array values that may be `StructuralEquatable` rather than the arrays themselves. */ export const tupleStructuralEqualer: Equaler<readonly unknown[]> = create( (x, y) => { if (!Array.isArray(x) && x !== null && x !== undefined || !Array.isArray(y) && y !== null && y !== undefined) { throw new TypeError("Array expected"); } if (x === y) { return true; } if (!x || !y || x.length !== y.length) { return false; } for (let i = 0; i < x.length; i++) { if (!Equaler.structuralEqualer.equals(x[i], y[i])) { return false; } } return true; }, (x) => { if (x === null || x === undefined) { return 0; } if (!Array.isArray(x)) { throw new TypeError("Array expected"); } let hc = 0; for (const item of x) { hc = combineHashes(hc, Equaler.structuralEqualer.hash(item)); } return hc; }); /** * Creates an `Equaler` from a comparison function and an optional hash generator. * @typeParam T The type of value that can be compared. * @param equalityComparison A callback used to compare the equality of two values. * @param hashGenerator A callback used to compute a numeric hash-code for a value. * @returns An Equaler for the provided callbacks. */ export function create<T>(equalityComparison: EqualityComparison<T>, hashGenerator: HashGenerator<T> = defaultEqualer.hash): Equaler<T> { return Object.setPrototypeOf({ equals: equalityComparison, hash: hashGenerator }, equalerPrototype); } /** * Combines two hash codes. * @param x The first hash code. * @param y The second hash code. * @param rotate The number of bits (between 0 and 31) to left-rotate the first hash code before XOR'ing it with the second (default 7). */ export function combineHashes(x: number, y: number, rotate: number = 7) { if (typeof x !== "number") throw new TypeError("Integer expected: x"); if (typeof y !== "number") throw new TypeError("Integer expected: y"); if (typeof rotate !== "number") throw new TypeError("Integer expected: rotate"); if (isNaN(x) || !isFinite(x)) throw new RangeError("Argument must be a finite number value: x"); if (isNaN(y) || !isFinite(y)) throw new RangeError("Argument must be a finite number value: y"); if (isNaN(rotate) || !isFinite(rotate)) throw new RangeError("Argument must be a finite number value: rotate"); while (rotate < 0) rotate += 32; while (rotate >= 32) rotate -= 32; return ((x << rotate) | (x >>> (32 - rotate))) ^ y; } export function hasInstance(value: unknown): value is Equaler<unknown> { return typeof value === "object" && value !== null && typeof (value as Equaler<unknown>).equals === "function" && typeof (value as Equaler<unknown>).hash === "function"; } Object.defineProperty(Equaler, Symbol.hasInstance, { configurable: true, writable: true, value: hasInstance }); } export import defaultEqualer = Equaler.defaultEqualer; export import structuralEqualer = Equaler.structuralEqualer; export import tupleEqualer = Equaler.tupleEqualer; export import tupleStructuralEqualer = Equaler.tupleEqualer; export import combineHashes = Equaler.combineHashes; /** * Describes a function that can be used to compare the relational equality of two values, returning a * value indicating one of the following conditions: * - A negative value indicates `x` is lesser than `y`. * - A positive value indicates `x` is greater than `y`. * - A zero value indicates `x` and `y` are equivalent. * @typeParam T The type of value that can be compared. */ export type Comparison<T> = (x: T, y: T) => number; /** * Represents an object that can be used to perform a relational comparison between two values. * @typeParam T The type of value that can be compared. */ export interface Comparer<T> { /** * Compares two values, returning a value indicating one of the following conditions: * - A negative value indicates `x` is lesser than `y`. * - A positive value indicates `x` is greater than `y`. * - A zero value indicates `x` and `y` are equivalent. * @param x The first value to compare. * @param y The second value to compare. * @returns A number indicating the relational comparison result. */ compare(x: T, y: T): number; } /** * Provides various implementations of `Comparer`. */ export namespace Comparer { const comparerProtototype = Object.defineProperty({}, Symbol.toStringTag, { configurable: true, value: "Comparer" }); /** * The default `Comparer`. */ export const defaultComparer: Comparer<unknown> = create((x, y) => Comparable.hasInstance(x) ? x[Comparable.compareTo](y) : Comparable.hasInstance(y) ? -y[Comparable.compareTo](x) : (x as any) < (y as any) ? -1 : (x as any) > (y as any) ? 1 : 0); /** * A default `Comparer` that supports `StructuralComparable` values. */ export const structuralComparer: Comparer<unknown> = create((x, y) => StructuralComparable.hasInstance(x) ? x[StructuralComparable.structuralCompareTo](y, structuralComparer) : StructuralComparable.hasInstance(y) ? -y[StructuralComparable.structuralCompareTo](x, structuralComparer) : defaultComparer.compare(x, y)); /** * A default `Comparer` that compares array values rather than the arrays themselves. */ export const tupleComparer: Comparer<readonly unknown[]> = create((x, y) => { if (!Array.isArray(x) && x !== null && x !== undefined || !Array.isArray(y) && y !== null && y !== undefined) { throw new TypeError("Array expected"); } let r: number; if (r = defaultComparer.compare(x.length, y.length)) { return r; } for (let i = 0; i < x.length; i++) { if (r = defaultComparer.compare(x[i], y[i])) { return r; } } return 0; }); /** * A default `Comparer` that compares array values that may be `StructuralComparable` rather than the arrays themselves. */ export const tupleStructuralComparer: Comparer<readonly unknown[]> = create((x, y) => { if (!Array.isArray(x) && x !== null && x !== undefined || !Array.isArray(y) && y !== null && y !== undefined) { throw new TypeError("Array expected"); } let r: number; if (r = defaultComparer.compare(x.length, y.length)) { return r; } for (let i = 0; i < x.length; i++) { if (r = structuralComparer.compare(x[i], y[i])) { return r; } } return 0; }); /** * Creates a `Comparer` from a comparison function. * @typeParam T The type of value that can be compared. * @param comparison A Comparison function used to create a Comparer. * @returns The Comparer for the provided comparison function. */ export function create<T>(comparison: Comparison<T>): Comparer<T> { return Object.setPrototypeOf({ compare: comparison }, comparerProtototype); } export function hasInstance(value: unknown): value is Comparer<unknown> { return typeof value === "object" && value !== null && typeof (value as Comparer<unknown>).compare === "function"; } Object.defineProperty(Comparer, Symbol.hasInstance, { configurable: true, writable: true, value: hasInstance }); } export import defaultComparer = Comparer.defaultComparer; export import structuralComparer = Comparer.structuralComparer; export import tupleComparer = Comparer.tupleComparer; export import tupleStructuralComparer = Comparer.tupleStructuralComparer; /** * Gets the raw hashcode for a value. This bypasses any `[Equatable.hash]` properties on an object. * @param value Any value. * @returns The hashcode for the value. */ export function rawHash(value: unknown): number { return hashUnknown(value); } function createDeprecation(message: string) { let hasReportedWarning = false; return () => { if (!hasReportedWarning) { hasReportedWarning = true; if (typeof process === "object" && process.emitWarning) { process.emitWarning(message, "Deprecation"); } else if (typeof console === "object") { console.warn(`Deprecation: ${message}`) } } } }
the_stack
import { createAutocomplete } from '@algolia/autocomplete-core'; import { noop } from '@algolia/autocomplete-shared'; import userEvent from '@testing-library/user-event'; import insightsClient from 'search-insights'; import { createPlayground, createSource, runAllMicroTasks, } from '../../../../test/utils'; import { createAlgoliaInsightsPlugin } from '../createAlgoliaInsightsPlugin'; jest.useFakeTimers(); describe('createAlgoliaInsightsPlugin', () => { test('has a name', () => { const plugin = createAlgoliaInsightsPlugin({ insightsClient }); expect(plugin.name).toBe('aa.algoliaInsightsPlugin'); }); test('exposes passed options and excludes default ones', () => { const plugin = createAlgoliaInsightsPlugin({ insightsClient, onItemsChange: noop, }); expect(plugin.__autocomplete_pluginOptions).toEqual({ insightsClient: expect.any(Function), onItemsChange: expect.any(Function), }); }); test('exposes the Search Insights API on the context', () => { const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient }); const onStateChange = jest.fn(); createPlayground(createAutocomplete, { onStateChange, plugins: [insightsPlugin], }); expect(onStateChange).toHaveBeenLastCalledWith( expect.objectContaining({ state: expect.objectContaining({ context: expect.objectContaining({ algoliaInsightsPlugin: expect.objectContaining({ insights: expect.objectContaining({ init: expect.any(Function), setUserToken: expect.any(Function), clickedObjectIDsAfterSearch: expect.any(Function), clickedObjectIDs: expect.any(Function), clickedFilters: expect.any(Function), convertedObjectIDsAfterSearch: expect.any(Function), convertedObjectIDs: expect.any(Function), convertedFilters: expect.any(Function), viewedObjectIDs: expect.any(Function), viewedFilters: expect.any(Function), }), }), }), }), }) ); }); describe('onItemsChange', () => { test('sends a `viewedObjectIDs` event by default', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [ { label: '1', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); jest.runAllTimers(); expect(insightsClient).toHaveBeenCalledWith('viewedObjectIDs', { eventName: 'Items Viewed', index: 'index1', objectIDs: ['1'], }); }); test('sends a custom event', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient, onItemsChange({ insights, insightsEvents }) { const events = insightsEvents.map((insightsEvent) => ({ ...insightsEvent, eventName: 'Product Viewed from Autocomplete', })); insights.viewedObjectIDs(...events); }, }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [ { label: '1', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); jest.runAllTimers(); expect(insightsClient).toHaveBeenCalledWith('viewedObjectIDs', { eventName: 'Product Viewed from Autocomplete', index: 'index1', objectIDs: ['1'], }); }); test('does not send an event without parameters', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient, onItemsChange({ insights }) { insights.viewedObjectIDs(); }, }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [ { label: '1', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); jest.runAllTimers(); expect(insightsClient).not.toHaveBeenCalled(); }); test('debounces calls', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, getSources() { return [ createSource({ getItems: ({ query }) => [ { label: 'hello', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, { label: 'hey', objectID: '2', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, { label: 'help', objectID: '3', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ].filter(({ label }) => label.startsWith(query)), }), ]; }, }); inputElement.focus(); userEvent.type(inputElement, 'h'); userEvent.type(inputElement, 'e'); userEvent.type(inputElement, 'l'); await runAllMicroTasks(); jest.runAllTimers(); userEvent.type(inputElement, 'p'); await runAllMicroTasks(); jest.runAllTimers(); // The first calls triggered with "h", "he" and "hel" were debounced, // so the item with label "hey" was never reported as viewed. expect(insightsClient).toHaveBeenCalledWith('viewedObjectIDs', { eventName: 'Items Viewed', index: 'index1', objectIDs: ['1', '3'], }); // The call triggered with "help" occurred after the timeout, so the item // with label "help" was reported as viewed a second time. expect(insightsClient).toHaveBeenCalledWith('viewedObjectIDs', { eventName: 'Items Viewed', index: 'index1', objectIDs: ['3'], }); }); test('does not send an event with non-Algolia Insights hits', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [{ label: '1' }], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); jest.runAllTimers(); expect(insightsClient).not.toHaveBeenCalled(); }); test('does not send an event when there are no results', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); jest.runAllTimers(); expect(insightsClient).not.toHaveBeenCalled(); }); }); describe('onSelect', () => { test('sends a `clickedObjectIDsAfterSearch` event by default', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [ { label: '1', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); userEvent.type(inputElement, '{enter}'); await runAllMicroTasks(); expect(insightsClient).toHaveBeenCalledWith( 'clickedObjectIDsAfterSearch', { eventName: 'Item Selected', index: 'index1', objectIDs: ['1'], positions: [0], queryID: 'queryID1', } ); }); test('sends a custom event', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient, onSelect({ insights, insightsEvents }) { const events = insightsEvents.map((insightsEvent) => ({ ...insightsEvent, eventName: 'Product Selected from Autocomplete', })); insights.clickedObjectIDsAfterSearch(...events); }, }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [ { label: '1', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); userEvent.type(inputElement, '{enter}'); await runAllMicroTasks(); expect(insightsClient).toHaveBeenCalledWith( 'clickedObjectIDsAfterSearch', { eventName: 'Product Selected from Autocomplete', index: 'index1', objectIDs: ['1'], positions: [0], queryID: 'queryID1', } ); }); test('does not send an event without parameters', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient, onSelect({ insights }) { insights.clickedObjectIDsAfterSearch(); }, }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [ { label: '1', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); userEvent.type(inputElement, '{enter}'); await runAllMicroTasks(); expect(insightsClient).not.toHaveBeenCalled(); }); test('does not send an event with non-Algolia Insights hits', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [{ label: '1' }], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); userEvent.type(inputElement, '{enter}'); await runAllMicroTasks(); expect(insightsClient).not.toHaveBeenCalled(); }); }); describe('onActive', () => { test('does not send an event by default', async () => { const insightsClient = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [ { label: '1', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); expect(insightsClient).not.toHaveBeenCalled(); }); test('sends a custom event', async () => { const insightsClient = jest.fn(); const track = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient, onActive({ insightsEvents }) { insightsEvents.forEach((insightsEvent) => { track('Product Browsed from Autocomplete', insightsEvent); }); }, }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [ { label: '1', objectID: '1', __autocomplete_indexName: 'index1', __autocomplete_queryID: 'queryID1', }, ], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); expect(track).toHaveBeenCalledWith('Product Browsed from Autocomplete', { eventName: 'Item Active', index: 'index1', objectIDs: ['1'], positions: [0], queryID: 'queryID1', }); }); test('does not send an event with non-Algolia Insights hits', async () => { const insightsClient = jest.fn(); const track = jest.fn(); const insightsPlugin = createAlgoliaInsightsPlugin({ insightsClient, onActive({ insightsEvents }) { insightsEvents.forEach((insightsEvent) => { track('Product Browsed from Autocomplete', insightsEvent); }); }, }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [insightsPlugin], defaultActiveItemId: 0, openOnFocus: true, getSources() { return [ createSource({ getItems: () => [{ label: '1' }], }), ]; }, }); inputElement.focus(); await runAllMicroTasks(); expect(track).not.toHaveBeenCalled(); }); }); });
the_stack
import HierarchicalLayout from '../HierarchicalLayout'; import GraphAbstractHierarchyCell from '../datatypes/GraphAbstractHierarchyCell'; import GraphHierarchyModel from './GraphHierarchyModel'; import HierarchicalLayoutStage from './HierarchicalLayoutStage'; import MedianCellSorter from '../util/MedianCellSorter'; import SwimlaneLayout from '../SwimlaneLayout'; /** * Sets the horizontal locations of node and edge dummy nodes on each layer. * Uses median down and up weighings as well heuristic to straighten edges as * far as possible. * * Constructor: mxMedianHybridCrossingReduction * * Creates a coordinate assignment. * * Arguments: * * intraCellSpacing - the minimum buffer between cells on the same rank * interRankCellSpacing - the minimum distance between cells on adjacent ranks * orientation - the position of the root node(s) relative to the graph * initialX - the leftmost coordinate node placement starts at */ class MedianHybridCrossingReduction extends HierarchicalLayoutStage { constructor(layout: HierarchicalLayout | SwimlaneLayout) { super(); this.layout = layout; } /** * Reference to the enclosing <HierarchicalLayout>. */ layout: HierarchicalLayout | SwimlaneLayout; /** * The maximum number of iterations to perform whilst reducing edge * crossings. Default is 24. */ maxIterations = 24; /** * Stores each rank as a collection of cells in the best order found for * each layer so far */ nestedBestRanks: GraphAbstractHierarchyCell[][] | null = null; /** * The total number of crossings found in the best configuration so far */ currentBestCrossings = 0; /** * The total number of crossings found in the best configuration so far */ iterationsWithoutImprovement = 0; /** * The total number of crossings found in the best configuration so far */ maxNoImprovementIterations = 2; /** * Performs a vertex ordering within ranks as described by Gansner et al * 1993 */ execute(parent: any) { const model = <GraphHierarchyModel>this.layout.getDataModel(); let ranks = <GraphAbstractHierarchyCell[][]>model.ranks; // Stores initial ordering as being the best one found so far this.nestedBestRanks = []; for (let i = 0; i < ranks.length; i += 1) { this.nestedBestRanks[i] = ranks[i].slice(); } let iterationsWithoutImprovement = 0; let currentBestCrossings = this.calculateCrossings(model); for ( let i = 0; i < this.maxIterations && iterationsWithoutImprovement < this.maxNoImprovementIterations; i++ ) { this.weightedMedian(i, model); this.transpose(i, model); const candidateCrossings = this.calculateCrossings(model); if (candidateCrossings < currentBestCrossings) { currentBestCrossings = candidateCrossings; iterationsWithoutImprovement = 0; // Store the current rankings as the best ones for (let j = 0; j < this.nestedBestRanks.length; j += 1) { const rank = ranks[j]; for (let k = 0; k < rank.length; k += 1) { const cell = rank[k]; this.nestedBestRanks[j][<number>cell.getGeneralPurposeVariable(j)] = cell; } } } else { // Increase count of iterations where we haven't improved the // layout iterationsWithoutImprovement += 1; // Restore the best values to the cells for (let j = 0; j < this.nestedBestRanks.length; j += 1) { const rank = ranks[j]; for (let k = 0; k < rank.length; k += 1) { const cell = rank[k]; cell.setGeneralPurposeVariable(j, k); } } } if (currentBestCrossings === 0) { // Do nothing further break; } } // Store the best rankings but in the model ranks = []; const rankList: GraphAbstractHierarchyCell[][] = []; for (let i = 0; i < model.maxRank + 1; i += 1) { rankList[i] = []; ranks[i] = rankList[i]; } for (let i = 0; i < this.nestedBestRanks.length; i += 1) { for (let j = 0; j < this.nestedBestRanks[i].length; j += 1) { rankList[i].push(this.nestedBestRanks[i][j]); } } model.ranks = ranks; } /** * Calculates the total number of edge crossing in the current graph. * Returns the current number of edge crossings in the hierarchy graph * model in the current candidate layout * * @param model the internal model describing the hierarchy */ calculateCrossings(model: GraphHierarchyModel) { const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; const numRanks = ranks.length; let totalCrossings = 0; for (let i = 1; i < numRanks; i += 1) { totalCrossings += this.calculateRankCrossing(i, model); } return totalCrossings; } /** * Calculates the number of edges crossings between the specified rank and * the rank below it. Returns the number of edges crossings with the rank * beneath * * @param i the topmost rank of the pair ( higher rank value ) * @param model the internal model describing the hierarchy */ calculateRankCrossing(i: number, model: GraphHierarchyModel) { let totalCrossings = 0; const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; const rank = ranks[i]; const previousRank = ranks[i - 1]; const tmpIndices = []; // Iterate over the top rank and fill in the connection information for (let j = 0; j < rank.length; j += 1) { const node = rank[j]; const rankPosition = <number>node.getGeneralPurposeVariable(i); const connectedCells = <GraphAbstractHierarchyCell[]>node.getPreviousLayerConnectedCells(i); const nodeIndices = []; for (let k = 0; k < connectedCells.length; k += 1) { const connectedNode = connectedCells[k]; const otherCellRankPosition = <number>connectedNode.getGeneralPurposeVariable(i - 1); nodeIndices.push(otherCellRankPosition); } nodeIndices.sort((x: number, y: number) => { return x - y; }); tmpIndices[rankPosition] = nodeIndices; } let indices: number[] = []; for (let j = 0; j < tmpIndices.length; j++) { indices = indices.concat(tmpIndices[j]); } let firstIndex = 1; while (firstIndex < previousRank.length) { firstIndex <<= 1; } const treeSize = 2 * firstIndex - 1; firstIndex -= 1; const tree = []; for (let j = 0; j < treeSize; ++j) { tree[j] = 0; } for (let j = 0; j < indices.length; j += 1) { const index = indices[j]; let treeIndex = index + firstIndex; ++tree[treeIndex]; while (treeIndex > 0) { if (treeIndex % 2) { totalCrossings += tree[treeIndex + 1]; } treeIndex = (treeIndex - 1) >> 1; ++tree[treeIndex]; } } return totalCrossings; } /** * Takes each possible adjacent cell pair on each rank and checks if * swapping them around reduces the number of crossing * * @param mainLoopIteration the iteration number of the main loop * @param model the internal model describing the hierarchy */ transpose(mainLoopIteration: number, model: GraphHierarchyModel) { let improved = true; // Track the number of iterations in case of looping let count = 0; const maxCount = 10; while (improved && count++ < maxCount) { // On certain iterations allow allow swapping of cell pairs with // equal edge crossings switched or not switched. This help to // nudge a stuck layout into a lower crossing total. const nudge = mainLoopIteration % 2 === 1 && count % 2 === 1; improved = false; const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; for (let i = 0; i < ranks.length; i += 1) { const rank = ranks[i]; const orderedCells = []; for (let j = 0; j < rank.length; j++) { const cell = rank[j]; let tempRank = <number>cell.getGeneralPurposeVariable(i); // FIXME: Workaround to avoid negative tempRanks if (tempRank < 0) { tempRank = j; } orderedCells[tempRank] = cell; } let leftCellAboveConnections: GraphAbstractHierarchyCell[] | null = null; let leftCellBelowConnections: GraphAbstractHierarchyCell[] | null = null; let rightCellAboveConnections: GraphAbstractHierarchyCell[] | null = null; let rightCellBelowConnections: GraphAbstractHierarchyCell[] | null = null; let leftAbovePositions: number[] | null = null; let leftBelowPositions: number[] | null = null; let rightAbovePositions: number[] | null = null; let rightBelowPositions: number[] | null = null; let leftCell = null; let rightCell = null; for (let j = 0; j < rank.length - 1; j++) { // For each intra-rank adjacent pair of cells // see if swapping them around would reduce the // number of edges crossing they cause in total // On every cell pair except the first on each rank, we // can save processing using the previous values for the // right cell on the new left cell if (j === 0) { leftCell = orderedCells[j]; leftCellAboveConnections = <GraphAbstractHierarchyCell[]>leftCell.getNextLayerConnectedCells(i); leftCellBelowConnections = <GraphAbstractHierarchyCell[]>leftCell.getPreviousLayerConnectedCells(i); leftAbovePositions = []; leftBelowPositions = []; for (let k = 0; k < leftCellAboveConnections.length; k++) { leftAbovePositions[k] = <number>leftCellAboveConnections[k].getGeneralPurposeVariable(i + 1); } for (let k = 0; k < leftCellBelowConnections.length; k++) { leftBelowPositions[k] = <number>leftCellBelowConnections[k].getGeneralPurposeVariable(i - 1); } } else { leftCellAboveConnections = rightCellAboveConnections; leftCellBelowConnections = rightCellBelowConnections; leftAbovePositions = rightAbovePositions; leftBelowPositions = rightBelowPositions; leftCell = rightCell; } rightCell = orderedCells[j + 1]; rightCellAboveConnections = <GraphAbstractHierarchyCell[]>rightCell.getNextLayerConnectedCells(i); rightCellBelowConnections = <GraphAbstractHierarchyCell[]>rightCell.getPreviousLayerConnectedCells( i ); rightAbovePositions = []; rightBelowPositions = []; for (let k = 0; k < rightCellAboveConnections.length; k++) { rightAbovePositions[k] = <number>rightCellAboveConnections[k].getGeneralPurposeVariable(i + 1); } for (let k = 0; k < rightCellBelowConnections.length; k++) { rightBelowPositions[k] = <number>rightCellBelowConnections[k].getGeneralPurposeVariable(i - 1); } let totalCurrentCrossings = 0; let totalSwitchedCrossings = 0; for (let k = 0; k < (<number[]>leftAbovePositions).length; k += 1) { for (let ik = 0; ik < rightAbovePositions.length; ik += 1) { if ((<number[]>leftAbovePositions)[k] > rightAbovePositions[ik]) { totalCurrentCrossings += 1; } if ((<number[]>leftAbovePositions)[k] < rightAbovePositions[ik]) { totalSwitchedCrossings += 1; } } } for (let k = 0; k < (<number[]>leftBelowPositions).length; k += 1) { for (let ik = 0; ik < rightBelowPositions.length; ik += 1) { if ((<number[]>leftBelowPositions)[k] > rightBelowPositions[ik]) { totalCurrentCrossings += 1; } if ((<number[]>leftBelowPositions)[k] < rightBelowPositions[ik]) { totalSwitchedCrossings += 1; } } } if ( totalSwitchedCrossings < totalCurrentCrossings || (totalSwitchedCrossings === totalCurrentCrossings && nudge) ) { const temp = <number>(<GraphAbstractHierarchyCell>leftCell).getGeneralPurposeVariable(i); (<GraphAbstractHierarchyCell>leftCell).setGeneralPurposeVariable(i, <number>rightCell.getGeneralPurposeVariable(i)); rightCell.setGeneralPurposeVariable(i, temp); // With this pair exchanged we have to switch all of // values for the left cell to the right cell so the // next iteration for this rank uses it as the left // cell again rightCellAboveConnections = leftCellAboveConnections; rightCellBelowConnections = leftCellBelowConnections; rightAbovePositions = leftAbovePositions; rightBelowPositions = leftBelowPositions; rightCell = leftCell; if (!nudge) { // Don't count nudges as improvement or we'll end // up stuck in two combinations and not finishing // as early as we should improved = true; } } } } } } /** * Sweeps up or down the layout attempting to minimise the median placement * of connected cells on adjacent ranks * * @param iteration the iteration number of the main loop * @param model the internal model describing the hierarchy */ weightedMedian(iteration: number, model: GraphHierarchyModel) { // Reverse sweep direction each time through this method const downwardSweep = iteration % 2 === 0; if (downwardSweep) { for (let j = model.maxRank - 1; j >= 0; j -= 1) { this.medianRank(j, downwardSweep); } } else { for (let j = 1; j < model.maxRank; j += 1) { this.medianRank(j, downwardSweep); } } } /** * Attempts to minimise the median placement of connected cells on this rank * and one of the adjacent ranks * * @param rankValue the layer number of this rank * @param downwardSweep whether or not this is a downward sweep through the graph */ medianRank(rankValue: number, downwardSweep: boolean) { const nestedBestRanks = <{ [key: number]: GraphAbstractHierarchyCell[] }>this.nestedBestRanks; const numCellsForRank = nestedBestRanks[rankValue].length; const medianValues = []; const reservedPositions: { [key: number]: boolean } = {}; for (let i = 0; i < numCellsForRank; i += 1) { const cell = nestedBestRanks[rankValue][i]; const sorterEntry = new MedianCellSorter(); sorterEntry.cell = cell; // Flip whether or not equal medians are flipped on up and down // sweeps // TODO re-implement some kind of nudge // medianValues[i].nudge = !downwardSweep; var nextLevelConnectedCells; if (downwardSweep) { nextLevelConnectedCells = cell.getNextLayerConnectedCells(rankValue); } else { nextLevelConnectedCells = cell.getPreviousLayerConnectedCells( rankValue ); } var nextRankValue; if (downwardSweep) { nextRankValue = rankValue + 1; } else { nextRankValue = rankValue - 1; } if ( nextLevelConnectedCells != null && nextLevelConnectedCells.length !== 0 ) { sorterEntry.medianValue = this.medianValue( nextLevelConnectedCells, nextRankValue ); medianValues.push(sorterEntry); } else { // Nodes with no adjacent vertices are flagged in the reserved array // to indicate they should be left in their current position. reservedPositions[<number>cell.getGeneralPurposeVariable(rankValue)] = true; } } medianValues.sort(new MedianCellSorter().compare); // Set the new position of each node within the rank using // its temp variable for (let i = 0; i < numCellsForRank; i += 1) { if (reservedPositions[i] == null) { const cell = <GraphAbstractHierarchyCell>(<MedianCellSorter>medianValues.shift()).cell; cell.setGeneralPurposeVariable(rankValue, i); } } } /** * Calculates the median rank order positioning for the specified cell using * the connected cells on the specified rank. Returns the median rank * ordering value of the connected cells * * @param connectedCells the cells on the specified rank connected to the * specified cell * @param rankValue the rank that the connected cell lie upon */ medianValue(connectedCells: GraphAbstractHierarchyCell[], rankValue: number) { const medianValues = []; let arrayCount = 0; for (let i = 0; i < connectedCells.length; i += 1) { const cell = connectedCells[i]; medianValues[arrayCount++] = <number>cell.getGeneralPurposeVariable(rankValue); } // Sort() sorts lexicographically by default (i.e. 11 before 9) so force // numerical order sort medianValues.sort((a, b) => { return a - b; }); if (arrayCount % 2 === 1) { // For odd numbers of adjacent vertices return the median return medianValues[Math.floor(arrayCount / 2)]; } if (arrayCount === 2) { return (medianValues[0] + medianValues[1]) / 2.0; } const medianPoint = arrayCount / 2; const leftMedian = medianValues[medianPoint - 1] - medianValues[0]; const rightMedian = medianValues[arrayCount - 1] - medianValues[medianPoint]; return ( (medianValues[medianPoint - 1] * rightMedian + medianValues[medianPoint] * leftMedian) / (leftMedian + rightMedian) ); } } export default MedianHybridCrossingReduction;
the_stack
// See: https://github.com/aws/aws-encryption-sdk-c/blob/master/tests/unit/t_hkdf.c export const tv0Ikm = new Uint8Array([ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, ]) export const tv0Salt = new Uint8Array([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, ]) export const tv0Info = new Uint8Array([ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, ]) export const tv0OkmDesired = new Uint8Array([ 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65, ]) // Test vector 1: Test with SHA-256 and longer inputs/outputs export const tv1Ikm = new Uint8Array([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, ]) export const tv1Salt = new Uint8Array([ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x82, 0x56, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, ]) export const tv1Info = new Uint8Array([ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]) export const tv1OkmDesired = new Uint8Array([ 0x56, 0xa0, 0x54, 0x34, 0x1d, 0x0d, 0x47, 0xfa, 0x0b, 0x49, 0xd0, 0x1d, 0x01, 0x35, 0x2d, 0xc2, 0x11, 0x0c, 0xfd, 0x75, 0x10, 0xfb, 0x06, 0x7c, 0x9b, 0x5a, 0xe9, 0x69, 0x94, 0x56, 0x29, 0x63, 0x43, 0xc7, 0xfd, 0xd5, 0xa9, 0xfe, 0xe2, 0x68, 0xd7, 0x9e, 0xea, 0xfa, 0x86, 0x3c, 0xf1, 0x17, 0x58, 0xda, 0x18, 0xb0, 0x47, 0x88, 0xa0, 0xd2, 0xc5, 0x9f, 0x3b, 0x03, 0x42, 0xa3, 0x82, 0x2e, 0xd7, 0xa6, 0xdf, 0xf1, 0x6c, 0x3b, 0x61, 0x3b, 0x58, 0x9e, 0xcf, 0x0f, 0x71, 0x0b, 0xdf, 0x2b, 0x15, 0x39, ]) // Test vector 2: Test with SHA-256 and zero-length salt/info export const tv2Ikm = new Uint8Array([ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, ]) export const tv2OkmDesired = new Uint8Array([ 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 0x80, 0x2a, 0x06, 0x3c, 0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73, 0x8d, 0x2d, 0x9d, 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8, ]) // Test vector 3: Basic test case with SHA-384 export const tv3Ikm = new Uint8Array([ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, ]) export const tv3Salt = new Uint8Array([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, ]) export const tv3Info = new Uint8Array([ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, ]) export const tv3OkmDesired = new Uint8Array([ 0x9b, 0x50, 0x97, 0xa8, 0x60, 0x38, 0xb8, 0x05, 0x30, 0x90, 0x76, 0xa4, 0x4b, 0x3a, 0x9f, 0x38, 0x06, 0x3e, 0x25, 0xb5, 0x16, 0xdc, 0xbf, 0x36, 0x9f, 0x39, 0x4c, 0xfa, 0xb4, 0x36, 0x85, 0xf7, 0x48, 0xb6, 0x45, 0x77, 0x63, 0xe4, 0xf0, 0x20, 0x4f, 0xc5, ]) // Test vector 4: Test with SHA-384 and longer inputs/outputs export const tv4Ikm = new Uint8Array([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, ]) export const tv4Salt = new Uint8Array([ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, ]) export const tv4Info = new Uint8Array([ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]) export const tv4OkmDesired = new Uint8Array([ 0x48, 0x4c, 0xa0, 0x52, 0xb8, 0xcc, 0x72, 0x4f, 0xd1, 0xc4, 0xec, 0x64, 0xd5, 0x7b, 0x4e, 0x81, 0x8c, 0x7e, 0x25, 0xa8, 0xe0, 0xf4, 0x56, 0x9e, 0xd7, 0x2a, 0x6a, 0x05, 0xfe, 0x06, 0x49, 0xee, 0xbf, 0x69, 0xf8, 0xd5, 0xc8, 0x32, 0x85, 0x6b, 0xf4, 0xe4, 0xfb, 0xc1, 0x79, 0x67, 0xd5, 0x49, 0x75, 0x32, 0x4a, 0x94, 0x98, 0x7f, 0x7f, 0x41, 0x83, 0x58, 0x17, 0xd8, 0x99, 0x4f, 0xdb, 0xd6, 0xf4, 0xc0, 0x9c, 0x55, 0x00, 0xdc, 0xa2, 0x4a, 0x56, 0x22, 0x2f, 0xea, 0x53, 0xd8, 0x96, 0x7a, 0x8b, 0x2e, ]) // Test vector 5: Test with SHA-384 and zero-length salt/info export const tv5Ikm = new Uint8Array([ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, ]) export const tv5OkmDesired = new Uint8Array([ 0xc8, 0xc9, 0x6e, 0x71, 0x0f, 0x89, 0xb0, 0xd7, 0x99, 0x0b, 0xca, 0x68, 0xbc, 0xde, 0xc8, 0xcf, 0x85, 0x40, 0x62, 0xe5, 0x4c, 0x73, 0xa7, 0xab, 0xc7, 0x43, 0xfa, 0xde, 0x9b, 0x24, 0x2d, 0xaa, 0xcc, 0x1c, 0xea, 0x56, 0x70, 0x41, 0x5b, 0x52, 0x84, 0x9c, ]) // Test vector 6: Test with NOSHA export const tv6Ikm = new Uint8Array([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, ]) // Test vector 7: Test with SHA-256 for N = ceil(L/HashLen) = 255 export const tv7Ikm = new Uint8Array([ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, ]) export const tv7Salt = new Uint8Array([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, ]) export const tv7Info = new Uint8Array([ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, ]) export const tv7OkmDesired = new Uint8Array([ 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65, 0xb4, 0xb0, 0xa8, 0x5a, 0x99, 0x3b, 0x89, 0xb9, 0xb6, 0x56, 0x83, 0xd6, 0x0f, 0x01, 0x06, 0xd2, 0x8f, 0xff, 0x03, 0x9d, 0x0b, 0x6f, 0x34, 0x08, 0x90, 0x0c, 0x0f, 0x2a, 0x9d, 0x44, 0x63, 0xde, 0x83, 0x62, 0x20, 0x56, 0xbe, 0x50, 0xa8, 0x81, 0xbe, 0xbf, 0x2b, 0x98, 0x3a, 0xb4, 0x3e, 0x06, 0x99, 0x12, 0xf0, 0xa5, 0x75, 0x82, 0xfc, 0xb1, 0x8c, 0xa7, 0xa7, 0xfe, 0x40, 0xa3, 0x3c, 0x76, 0x6c, 0x82, 0x98, 0x12, 0xaf, 0x32, 0x7c, 0x32, 0xe1, 0x26, 0x58, 0x9d, 0x3c, 0x64, 0xf4, 0x19, 0xdd, 0xff, 0xf9, 0xd8, 0xc7, 0x87, 0xf6, 0x95, 0xcf, 0xea, 0x76, 0x96, 0x81, 0x67, 0x25, 0xe3, 0x92, 0xc6, 0x3b, 0x53, 0x7e, 0x66, 0x5a, 0x6b, 0x15, 0xe1, 0xe4, 0x5a, 0x2d, 0xf8, 0x0e, 0x62, 0x54, 0xa7, 0xa3, 0xed, 0xc8, 0x43, 0xde, 0x19, 0xe5, 0xb0, 0xd8, 0x97, 0xe8, 0x04, 0x82, 0x9e, 0xf3, 0xed, 0xed, 0xa2, 0x0b, 0xbc, 0xda, 0x7c, 0xf1, 0x31, 0x62, 0x16, 0x2a, 0x1d, 0xa8, 0x86, 0x95, 0xf3, 0xe3, 0xa1, 0xb5, 0xf5, 0x24, 0xe5, 0xbb, 0x98, 0x5f, 0x73, 0xc6, 0x6d, 0x66, 0xdf, 0x92, 0x70, 0x57, 0x4f, 0x90, 0xb7, 0x34, 0x8e, 0xc9, 0x65, 0xfd, 0x51, 0x45, 0x75, 0x28, 0xfd, 0x72, 0xac, 0x47, 0x58, 0xbe, 0x57, 0x3c, 0x6d, 0x8d, 0x02, 0x94, 0xe1, 0x7b, 0xc9, 0xf2, 0x67, 0xbf, 0x9f, 0x1c, 0xaa, 0x8d, 0x38, 0x48, 0x67, 0x7c, 0xb9, 0xb0, 0xfa, 0xed, 0x8a, 0x51, 0xf2, 0x41, 0x50, 0xfd, 0xc8, 0x60, 0x3a, 0xfa, 0x82, 0xe8, 0xd5, 0xd5, 0x82, 0x4a, 0x71, 0x6e, 0x3f, 0xb9, 0x5b, 0x0a, 0xcc, 0xe9, 0xa7, 0x56, 0x06, 0xd0, 0x6f, 0xe3, 0x58, 0x89, 0xef, 0xaa, 0x6d, 0x4e, 0x0c, 0x4b, 0x3d, 0xd2, 0xdf, 0xde, 0x00, 0xed, 0x9b, 0x12, 0xd3, 0xe1, 0xf3, 0x40, 0xa7, 0xae, 0x4e, 0x49, 0x51, 0xbd, 0x67, 0xff, 0xfb, 0x2d, 0xb3, 0x93, 0xa0, 0x3e, 0x3e, 0xf9, 0x2c, 0x90, 0xbf, 0xdf, 0xde, 0xb3, 0x10, 0xb7, 0x52, 0xbb, 0x86, 0x38, 0x1a, 0xd9, 0x02, 0x1e, 0xee, 0x15, 0x15, 0x5e, 0xbb, 0x3e, 0xbf, 0x54, 0x66, 0x44, 0x2e, 0x67, 0xdf, 0xb4, 0x7e, 0xf1, 0xf3, 0xb8, 0x2f, 0x59, 0x0e, 0xc2, 0xca, 0x99, 0x68, 0xc2, 0xd3, 0x5a, 0x32, 0x5f, 0x27, 0xb7, 0x61, 0x72, 0x56, 0x03, 0xf7, 0x40, 0xc9, 0xcd, 0x10, 0x96, 0x15, 0x88, 0xf1, 0x88, 0x9c, 0xd2, 0x6c, 0xa6, 0xca, 0xac, 0x70, 0x33, 0x57, 0xf9, 0x89, 0xbc, 0x4f, 0x5b, 0x48, 0x3b, 0x53, 0x8e, 0xae, 0x52, 0xbf, 0x88, 0x88, 0xdc, 0xe1, 0xc4, 0x13, 0xb5, 0x9c, 0x24, 0xa2, 0x8b, 0xc1, 0xfc, 0x85, 0x39, 0x79, 0xdb, 0x54, 0xdd, 0x8a, 0xc0, 0xcf, 0xae, 0x72, 0x9d, 0x9b, 0xd3, 0xa8, 0xe9, 0xa1, 0xc0, 0x6f, 0x07, 0xf6, 0xf1, 0xc2, 0xb9, 0xd7, 0x7a, 0x6d, 0x0f, 0x21, 0x2b, 0x24, 0xa4, 0x3c, 0xc8, 0x10, 0x99, 0xc0, 0xc0, 0x65, 0x8f, 0x9e, 0x24, 0x67, 0xa7, 0x0e, 0x46, 0x3d, 0x9e, 0xf7, 0x6c, 0xef, 0x0e, 0x6b, 0xf2, 0xca, 0xe3, 0xd7, 0x84, 0x71, 0x54, 0x73, 0xdb, 0x41, 0x27, 0x62, 0xd1, 0x09, 0x87, 0x24, 0x85, 0xf9, 0x9b, 0x2c, 0x90, 0x14, 0x61, 0x0e, 0xd6, 0x12, 0xe6, 0x5f, 0x0f, 0x15, 0x63, 0x5e, 0x00, 0x0b, 0x3e, 0x15, 0x3d, 0x88, 0x00, 0xba, 0x09, 0x27, 0x31, 0x9b, 0x95, 0x47, 0x3d, 0x2e, 0xdf, 0x96, 0xc7, 0x39, 0x3a, 0x61, 0xa2, 0xa6, 0xb7, 0x7c, 0xd9, 0x35, 0x1c, 0x6f, 0x80, 0x4d, 0x89, 0x8d, 0xe8, 0x62, 0xfb, 0x5e, 0x9b, 0x30, 0x1f, 0xf3, 0x63, 0xf5, 0xa1, 0x8f, 0x8e, 0xa2, 0xea, 0x23, 0x1f, 0xf4, 0x84, 0x77, 0x31, 0x14, 0xd7, 0x38, 0xca, 0xab, 0xb7, 0x7d, 0xe6, 0x0b, 0x38, 0x22, 0xbc, 0x88, 0xb9, 0x8f, 0x31, 0xdf, 0xa4, 0xe5, 0xcb, 0x9a, 0xb1, 0xeb, 0x09, 0xb4, 0xd1, 0xd4, 0xfa, 0xee, 0x63, 0x3f, 0xbb, 0x57, 0x4d, 0x3a, 0xb2, 0xfd, 0xb8, 0xa1, 0xa1, 0x5b, 0x01, 0x37, 0x73, 0xb5, 0x03, 0xc7, 0xfa, 0x99, 0x9d, 0xed, 0x73, 0x81, 0x8c, 0x72, 0xb4, 0x67, 0x33, 0xbd, 0xa3, 0x75, 0x9d, 0xd5, 0xb8, 0x70, 0xd1, 0xc5, 0xdb, 0x6e, 0x73, 0xd1, 0x12, 0xe8, 0x54, 0x89, 0xce, 0x87, 0x6b, 0xb3, 0xa3, 0xe1, 0x14, 0xa7, 0xcc, 0x07, 0xf9, 0xd4, 0x9a, 0xb5, 0xe3, 0x33, 0x20, 0xb5, 0xaa, 0x45, 0x89, 0xa0, 0xbf, 0x5f, 0x74, 0x32, 0x02, 0x25, 0x90, 0xa0, 0x26, 0x19, 0xce, 0xac, 0xee, 0x97, 0x55, 0x66, 0x79, 0xfa, 0xd3, 0xc9, 0xfc, 0xdc, 0xc9, 0x97, 0x44, 0xdd, 0x0b, 0xb6, 0x82, 0x2b, 0xbf, 0x83, 0x7c, 0xb6, 0x8a, 0x0b, 0xe3, 0x2f, 0x42, 0x07, 0xbd, 0xf0, 0x97, 0x65, 0x16, 0xda, 0x46, 0x58, 0x27, 0x3f, 0x73, 0xc2, 0x5d, 0x3d, 0x42, 0x0e, 0x7e, 0x72, 0x8e, 0x8e, 0xa4, 0x85, 0x16, 0x02, 0x80, 0xe6, 0x51, 0x01, 0xe4, 0x15, 0x12, 0x4c, 0xf9, 0xd3, 0x85, 0x2f, 0x9e, 0x6c, 0x22, 0xa6, 0xda, 0x8a, 0x5b, 0x30, 0xfb, 0xc1, 0xde, 0x62, 0x5a, 0xa2, 0x52, 0xc6, 0xb4, 0x07, 0x87, 0x09, 0x66, 0x9a, 0x14, 0x76, 0xf6, 0x55, 0x01, 0xac, 0xd8, 0x61, 0xff, 0xba, 0x6c, 0xd0, 0xc3, 0x9e, 0x06, 0x4d, 0xe9, 0xdd, 0xcb, 0xf2, 0x52, 0x9c, 0xb0, 0x42, 0x81, 0xd3, 0x22, 0xda, 0xdc, 0xa6, 0xb5, 0x7a, 0x65, 0xbf, 0xa9, 0xd4, 0x3e, 0x7f, 0x7e, 0x84, 0x6f, 0x6f, 0xe2, 0x03, 0x93, 0xeb, 0xd8, 0x3d, 0x98, 0x77, 0xff, 0x22, 0x74, 0xb0, 0xf7, 0x75, 0x31, 0x13, 0x21, 0x5c, 0xf5, 0xb4, 0x4a, 0xe6, 0xaa, 0x96, 0x1f, 0x94, 0x19, 0x6c, 0x4d, 0x7d, 0x44, 0x6b, 0x19, 0x92, 0x31, 0xcf, 0x6d, 0x9f, 0xa3, 0xa8, 0x1d, 0x27, 0xdc, 0xd5, 0x3b, 0x17, 0x01, 0x7b, 0xf9, 0x4f, 0xbb, 0xbe, 0xb4, 0xb3, 0x35, 0x3c, 0x8e, 0xfb, 0x67, 0x5c, 0x39, 0x30, 0x6e, 0xdd, 0x8f, 0xcd, 0x7e, 0x02, 0xc0, 0xa3, 0xd2, 0x4f, 0x79, 0x52, 0xaf, 0xbb, 0x3f, 0x38, 0x06, 0xc9, 0x2a, 0xf0, 0x1a, 0xc2, 0xa3, 0xb7, 0x85, 0x58, 0x26, 0x97, 0xf6, 0x64, 0xc2, 0xd4, 0xde, 0x12, 0x07, 0xa8, 0x01, 0x9b, 0x49, 0x3b, 0x9b, 0xff, 0x0a, 0xd3, 0x66, 0x74, 0xc8, 0x59, 0xf7, 0x7f, 0xe6, 0x3b, 0xca, 0xee, 0xf3, 0xb3, 0x87, 0xe6, 0xf5, 0x42, 0x08, 0x88, 0xc8, 0x35, 0x03, 0xf9, 0x67, 0x07, 0xd4, 0x41, 0x5f, 0xab, 0x76, 0x33, 0x51, 0x5a, 0xe7, 0x5b, 0xbd, 0x3c, 0x37, 0x71, 0x77, 0x06, 0x9f, 0x3b, 0x8e, 0x6c, 0xe3, 0xc0, 0xd0, 0x7a, 0xfb, 0x49, 0xc7, 0x6b, 0xc2, 0xca, 0x11, 0x5e, 0x54, 0x9b, 0x14, 0x0d, 0xdf, 0x2b, 0xa3, 0x4b, 0xc1, 0xf7, 0x04, 0x6d, 0xab, 0x2e, 0xaa, 0x56, 0x01, 0xa6, 0xd3, 0xcb, 0x16, 0x9e, 0x21, 0xaa, 0xa1, 0xab, 0x45, 0x95, 0x95, 0x91, 0x9a, 0x09, 0x26, 0x1f, 0x84, 0xab, 0xd3, 0xaa, 0x69, 0x99, 0xd1, 0x60, 0x87, 0xf3, 0x36, 0x12, 0x91, 0x7f, 0x49, 0x66, 0xe6, 0x4a, 0x35, 0xbb, 0xe3, 0x41, 0x95, 0x51, 0x1f, 0x6e, 0x2b, 0x4a, 0x49, 0x61, 0x16, 0xe7, 0x77, 0xd4, 0x9a, 0x40, 0xf7, 0xdd, 0xff, 0xdb, 0xd0, 0x41, 0x4f, 0xbc, 0x78, 0xba, 0x08, 0x2b, 0x52, 0xe8, 0x67, 0x75, 0x0b, 0xa3, 0x89, 0xae, 0xac, 0x7c, 0xbc, 0x26, 0x68, 0xa6, 0xab, 0x92, 0x81, 0x6b, 0xd4, 0xed, 0x0b, 0x71, 0xbe, 0x0c, 0x42, 0xdf, 0xea, 0x61, 0x62, 0x11, 0x20, 0x6a, 0x06, 0xe4, 0x56, 0x19, 0xa4, 0x52, 0x52, 0x43, 0x97, 0x95, 0x41, 0xac, 0x1a, 0x90, 0x45, 0x8e, 0xd6, 0xf0, 0x54, 0x90, 0xa3, 0xab, 0xea, 0xc0, 0x5a, 0xf8, 0x14, 0xc4, 0x8b, 0x6c, 0x44, 0xf6, 0x7e, 0xba, 0x58, 0x37, 0x8a, 0xf8, 0x0a, 0x26, 0x49, 0x54, 0xe6, 0x90, 0xa9, 0xf3, 0x6a, 0xdc, 0xc9, 0x43, 0x93, 0x9c, 0xfc, 0x8c, 0x6f, 0x7f, 0xb9, 0x6b, 0x09, 0x1e, 0xfe, 0xba, 0xc7, 0xe9, 0xca, 0x41, 0x13, 0xbb, 0x67, 0x9d, 0x76, 0xe0, 0x93, 0xce, 0xdd, 0xd8, 0x81, 0x66, 0xc7, 0x32, 0x9c, 0x1c, 0xc4, 0x31, 0x59, 0x81, 0xa0, 0xc7, 0x61, 0x1e, 0x5d, 0x64, 0xe6, 0x14, 0x81, 0xd7, 0x42, 0x88, 0x3a, 0xc0, 0x11, 0xc7, 0xa8, 0xa9, 0x9a, 0xd9, 0x3f, 0x21, 0x41, 0xdc, 0x2b, 0x45, 0x0a, 0xf6, 0xa2, 0xb7, 0xb6, 0x05, 0x52, 0x61, 0x7b, 0x86, 0xd0, 0x08, 0x73, 0x68, 0x6d, 0x18, 0xd9, 0xf2, 0x81, 0x7d, 0x12, 0x08, 0x74, 0x4d, 0x2d, 0x9a, 0xf5, 0xc9, 0x4d, 0x47, 0xb5, 0x48, 0x4f, 0x14, 0x4d, 0xb2, 0x86, 0xba, 0x9f, 0xa7, 0xed, 0x20, 0x32, 0x7c, 0xcd, 0xec, 0x70, 0x5c, 0xf4, 0xa4, 0xef, 0x1f, 0x6d, 0x21, 0xdf, 0x5d, 0x16, 0xde, 0xa6, 0x3e, 0x1e, 0xd6, 0x84, 0xce, 0x97, 0x35, 0xb2, 0xfa, 0xd0, 0x34, 0x42, 0x99, 0xf8, 0x3f, 0x02, 0x0c, 0xb2, 0x75, 0xf1, 0x18, 0x71, 0x2f, 0x22, 0xeb, 0x95, 0x28, 0x42, 0xe5, 0x7f, 0xcc, 0x1d, 0xa3, 0x5a, 0x23, 0x97, 0xf4, 0x1c, 0xf9, 0x46, 0x5b, 0x4a, 0xcd, 0x2e, 0xeb, 0x64, 0xc2, 0xbc, 0x61, 0x33, 0xa4, 0xf1, 0x23, 0xb0, 0x08, 0x5b, 0x43, 0xcc, 0x33, 0x85, 0x9d, 0x1c, 0xed, 0xea, 0x87, 0x8c, 0x44, 0xf8, 0xc3, 0xa8, 0x30, 0x98, 0x56, 0x29, 0xb0, 0x35, 0x27, 0xc7, 0x63, 0x7a, 0x56, 0x46, 0xe1, 0x57, 0xe1, 0x8b, 0x39, 0x5d, 0x5d, 0xa1, 0xe4, 0xba, 0xc0, 0x54, 0xe5, 0xb9, 0x03, 0x49, 0xc4, 0x85, 0x89, 0xd7, 0xc0, 0x29, 0x1e, 0x54, 0xa0, 0x4b, 0xce, 0x04, 0xf5, 0x35, 0x34, 0x20, 0xb6, 0x8d, 0x42, 0x32, 0xee, 0x5a, 0x51, 0x32, 0x37, 0x84, 0x03, 0xee, 0x44, 0xcf, 0x90, 0x0f, 0x0c, 0x7f, 0xc3, 0x55, 0x12, 0x43, 0x37, 0x04, 0xf9, 0xe8, 0xaa, 0xbd, 0xcd, 0xc5, 0xa9, 0x80, 0x9c, 0x67, 0xdd, 0xac, 0xd5, 0x2e, 0x8f, 0xda, 0x6b, 0xfd, 0x4d, 0x4c, 0xbe, 0x3f, 0x97, 0x2c, 0x39, 0x25, 0xe1, 0x87, 0x7d, 0x15, 0xd9, 0x00, 0x3e, 0x53, 0x32, 0x33, 0x02, 0xb0, 0xa0, 0xa1, 0x52, 0x70, 0xc6, 0x80, 0xeb, 0x28, 0x65, 0x97, 0xbd, 0x56, 0x2e, 0xce, 0xca, 0x5a, 0xe5, 0xbc, 0x6c, 0xeb, 0xf5, 0x34, 0x16, 0x30, 0xbd, 0x58, 0xc0, 0x5f, 0x99, 0x6d, 0x5c, 0x4a, 0x92, 0x87, 0x2c, 0x82, 0xdd, 0x5b, 0x11, 0x2e, 0x31, 0x18, 0x61, 0xdd, 0x16, 0xae, 0x20, 0x0c, 0xbd, 0x34, 0xfc, 0xcc, 0x85, 0x13, 0x7a, 0xf2, 0x1a, 0x6a, 0xe9, 0xda, 0xb0, 0x58, 0x47, 0xa9, 0x4c, 0x4d, 0x47, 0x20, 0xeb, 0x00, 0xcc, 0x25, 0x47, 0x12, 0xaf, 0x63, 0xca, 0x8d, 0x5f, 0x49, 0x51, 0x66, 0xe0, 0x53, 0x61, 0x79, 0x29, 0x38, 0x04, 0xa8, 0x19, 0xa1, 0xb5, 0x6d, 0x6d, 0x20, 0x77, 0x32, 0xef, 0x9d, 0x4c, 0x57, 0x83, 0x31, 0xc2, 0x8f, 0x3c, 0xfc, 0xcc, 0x97, 0x54, 0x8a, 0xe3, 0xa1, 0x19, 0xe0, 0xb9, 0x0b, 0xf4, 0xf3, 0x47, 0x64, 0x3a, 0xbb, 0x64, 0x0a, 0x72, 0x09, 0x96, 0x31, 0x37, 0x58, 0x32, 0xec, 0x36, 0x86, 0x75, 0xe1, 0x8a, 0x70, 0x36, 0xe7, 0x0a, 0xac, 0xde, 0x28, 0x86, 0xf7, 0xdf, 0x16, 0x7f, 0xae, 0xd9, 0x59, 0xe4, 0x79, 0xd5, 0xab, 0x75, 0x26, 0x73, 0xb8, 0x97, 0x41, 0x74, 0x50, 0xb4, 0x06, 0x2c, 0x44, 0x64, 0x67, 0x3e, 0x2d, 0xa1, 0x69, 0x5b, 0xcd, 0xa3, 0xaa, 0xc2, 0x45, 0x07, 0x6e, 0x55, 0x09, 0x01, 0x4b, 0x8a, 0x5d, 0x3f, 0xdf, 0xe0, 0x23, 0x29, 0x57, 0x56, 0xa2, 0xfb, 0xde, 0x60, 0x74, 0x90, 0xe2, 0xcb, 0xdc, 0x35, 0x3a, 0xad, 0xbd, 0xfb, 0x42, 0x30, 0x46, 0xb3, 0x7c, 0x2b, 0xc7, 0x61, 0x8c, 0x11, 0x48, 0x5f, 0x9c, 0x56, 0x31, 0x79, 0x65, 0xab, 0xbf, 0xef, 0x83, 0x58, 0x52, 0x57, 0x05, 0x89, 0x84, 0x5e, 0x32, 0xaa, 0x9a, 0x97, 0x5c, 0x8c, 0x55, 0x2e, 0x3d, 0x99, 0xde, 0xe7, 0xbd, 0x8d, 0x6d, 0x01, 0xd6, 0xcc, 0xc3, 0xde, 0xbd, 0x7d, 0xa1, 0x7b, 0x86, 0xa1, 0x51, 0xe1, 0xa5, 0xf4, 0x3a, 0x66, 0x27, 0xab, 0xb7, 0xe9, 0x42, 0xc2, 0xd2, 0x08, 0x5a, 0x73, 0xca, 0xc6, 0x44, 0x3b, 0xf7, 0x88, 0x15, 0x3e, 0x22, 0xa6, 0x95, 0x7d, 0x02, 0xd4, 0x22, 0x73, 0xef, 0x91, 0x19, 0xde, 0xdc, 0xfb, 0x75, 0xc8, 0x58, 0x99, 0x04, 0x14, 0x6e, 0xe7, 0xa8, 0xed, 0x66, 0x07, 0x85, 0x33, 0x06, 0xfc, 0xb5, 0x43, 0x53, 0x09, 0xf3, 0x4f, 0xe6, 0xcc, 0x3a, 0x19, 0x25, 0x22, 0xa5, 0x91, 0x4c, 0x38, 0xdc, 0x44, 0xb4, 0x1c, 0x3c, 0x39, 0x6e, 0x94, 0xe1, 0x25, 0xc9, 0xc9, 0xba, 0x5d, 0xe0, 0xbf, 0xc5, 0x30, 0xac, 0x90, 0x76, 0x67, 0xce, 0x47, 0x67, 0xf5, 0xcb, 0x26, 0x62, 0x43, 0xfd, 0x50, 0x30, 0xf1, 0x18, 0xe7, 0x1a, 0xc6, 0x96, 0x68, 0xbc, 0x21, 0x55, 0x49, 0xe1, 0x17, 0x2c, 0xda, 0x83, 0x82, 0xde, 0x94, 0x23, 0xb5, 0x43, 0x86, 0x6f, 0x11, 0x6c, 0x39, 0x6d, 0x11, 0x2c, 0x36, 0xea, 0xaf, 0xe6, 0x08, 0x54, 0x02, 0x6a, 0x13, 0x47, 0x48, 0x16, 0xea, 0x76, 0x5b, 0x80, 0xeb, 0x92, 0x1d, 0xf4, 0xca, 0xed, 0x6d, 0xe6, 0xdf, 0x2b, 0x2b, 0xbb, 0x26, 0x89, 0xb3, 0xe3, 0xbb, 0x68, 0x99, 0x4d, 0x84, 0x7e, 0xa2, 0x97, 0xf5, 0xf8, 0x94, 0x08, 0xe7, 0xc6, 0xbf, 0x83, 0x60, 0x9d, 0x1d, 0xda, 0xb7, 0x25, 0x45, 0x3d, 0x39, 0xe3, 0x53, 0xed, 0x8e, 0x2e, 0x2a, 0xc6, 0x8e, 0x9e, 0xd8, 0xd9, 0x35, 0xba, 0xfa, 0x35, 0x7b, 0x40, 0x0b, 0x6a, 0x82, 0x9c, 0xc2, 0xd9, 0xd1, 0x38, 0xd0, 0x50, 0xb6, 0xa2, 0x8a, 0xec, 0x97, 0x91, 0x11, 0x7d, 0x8c, 0xfb, 0xf4, 0xac, 0xdf, 0xe2, 0xaf, 0x1a, 0x74, 0xfb, 0x3a, 0xc2, 0xf8, 0xe4, 0x7a, 0x50, 0xf7, 0x11, 0x25, 0xa8, 0xf8, 0x99, 0x38, 0x94, 0x0c, 0x72, 0xdc, 0xea, 0x4a, 0x50, 0x05, 0xd0, 0xee, 0xa4, 0xd0, 0x6c, 0xc6, 0x5c, 0x37, 0x2e, 0x14, 0x6f, 0x3a, 0x20, 0x11, 0x0b, 0x2b, 0xd9, 0xf1, 0x77, 0x5a, 0x57, 0xe1, 0x88, 0x3b, 0x7f, 0x66, 0x9e, 0x45, 0x00, 0x95, 0xe2, 0x6a, 0x59, 0xdf, 0x86, 0xa5, 0x22, 0x29, 0x10, 0x3b, 0xda, 0xbc, 0x18, 0x95, 0x91, 0x02, 0x79, 0x42, 0x80, 0xba, 0xfc, 0xa8, 0xe9, 0x66, 0xf8, 0x66, 0x7e, 0x31, 0x5a, 0xd4, 0x66, 0xca, 0x74, 0x61, 0x93, 0x5e, 0x27, 0xf5, 0xe9, 0x22, 0x4d, 0x07, 0x71, 0xed, 0x59, 0x0e, 0xf6, 0x9c, 0x3d, 0x1e, 0xad, 0xa3, 0x53, 0xa4, 0x0d, 0x0b, 0xbe, 0x34, 0x0b, 0xa5, 0x23, 0x46, 0xd9, 0x13, 0x97, 0x70, 0x40, 0xbe, 0xd6, 0x8e, 0x84, 0x30, 0x14, 0x33, 0x0f, 0xf2, 0x23, 0x1b, 0xaf, 0x6a, 0xde, 0xa5, 0x99, 0xe7, 0x77, 0x47, 0x9b, 0x4b, 0x4b, 0x7c, 0x6a, 0xe1, 0x8e, 0xf7, 0x07, 0x16, 0xf5, 0xd5, 0x66, 0x56, 0x3e, 0xa2, 0xdf, 0x66, 0xac, 0xd7, 0x16, 0xca, 0xb9, 0x23, 0xa3, 0x54, 0x9a, 0xbc, 0x2e, 0xcb, 0xe6, 0xac, 0x88, 0x82, 0x5f, 0x56, 0x46, 0x80, 0xe8, 0x1a, 0x69, 0x14, 0x6c, 0x22, 0x81, 0x24, 0x4a, 0x27, 0xb8, 0x57, 0x6e, 0xcc, 0xd1, 0xcd, 0xc1, 0xe5, 0x19, 0x8e, 0xa0, 0xff, 0x22, 0xd9, 0x5f, 0xe4, 0x8c, 0x79, 0x7e, 0x16, 0x79, 0x75, 0x73, 0xe9, 0x23, 0x4d, 0xce, 0x5c, 0x77, 0xf2, 0xe5, 0xcc, 0x22, 0x9b, 0x26, 0xd4, 0x32, 0x30, 0xf9, 0xbf, 0x91, 0x32, 0xbf, 0x96, 0xbe, 0x5d, 0x5b, 0x1d, 0xa3, 0x7a, 0x55, 0xfe, 0x5d, 0x0e, 0xd5, 0x81, 0x18, 0x9e, 0x85, 0xb9, 0xb1, 0x6e, 0xdc, 0x6d, 0x21, 0x2d, 0xf3, 0x19, 0xe0, 0x83, 0x1b, 0x6e, 0x40, 0x97, 0x80, 0x12, 0x07, 0x67, 0x2d, 0xf5, 0xb6, 0xab, 0xe1, 0xec, 0x15, 0x62, 0xff, 0x89, 0x2c, 0x28, 0x44, 0x7c, 0x0c, 0x15, 0xa0, 0xe6, 0x55, 0x53, 0x14, 0x02, 0xa1, 0xdb, 0x84, 0x96, 0x1f, 0x8c, 0xf4, 0x67, 0x4c, 0x90, 0xb6, 0x46, 0x4c, 0xbf, 0x10, 0xf2, 0xfe, 0x09, 0x27, 0x2e, 0x04, 0x9c, 0xf3, 0x06, 0x28, 0x77, 0x09, 0xca, 0xae, 0x37, 0x9f, 0xe1, 0x84, 0x4e, 0xa0, 0x35, 0xbd, 0x4d, 0xaa, 0xb9, 0x60, 0xa9, 0xf7, 0x7a, 0x9f, 0xc3, 0xe2, 0xff, 0xbf, 0x8e, 0x19, 0xa8, 0xa2, 0x4f, 0x8b, 0xa4, 0xa7, 0x0b, 0x40, 0x85, 0x37, 0xe3, 0xb4, 0xc0, 0x0b, 0xa6, 0xff, 0x41, 0x8d, 0x6e, 0x26, 0x5e, 0x01, 0x2b, 0xb1, 0x19, 0xfd, 0xc7, 0xaf, 0xf7, 0x05, 0x23, 0x6d, 0xb1, 0x89, 0xa2, 0x0a, 0xb1, 0xc7, 0xca, 0x70, 0x83, 0x67, 0xf8, 0xdd, 0xe8, 0x0e, 0xbd, 0x94, 0x96, 0x3d, 0x6b, 0x85, 0x04, 0x97, 0xaf, 0x78, 0x38, 0x88, 0x87, 0xc9, 0x5e, 0x8d, 0x2a, 0x67, 0x96, 0x43, 0x48, 0xc8, 0x51, 0x3d, 0x07, 0x68, 0xf8, 0x41, 0x63, 0xb3, 0x39, 0xb0, 0xf6, 0xab, 0xa5, 0xc7, 0x02, 0xff, 0xf4, 0x9c, 0x55, 0x50, 0x3b, 0x4a, 0x6d, 0x88, 0x76, 0xac, 0xfe, 0xa5, 0xe7, 0x73, 0xf5, 0x39, 0xe3, 0x90, 0x03, 0xb5, 0xf7, 0x59, 0x06, 0xbe, 0x0a, 0xf4, 0x7b, 0x74, 0x90, 0x06, 0x21, 0xfe, 0x8b, 0x1e, 0x73, 0x76, 0x48, 0xe1, 0x96, 0x24, 0xcb, 0x31, 0xdb, 0x19, 0xfe, 0xf6, 0x3b, 0x4e, 0x47, 0xde, 0x9d, 0xaa, 0x3f, 0xaf, 0xaa, 0x81, 0xec, 0x46, 0x9b, 0xf2, 0x6f, 0x28, 0x86, 0x8b, 0x94, 0xc6, 0x31, 0x84, 0x45, 0x84, 0x91, 0x87, 0x77, 0x4d, 0x6d, 0xc6, 0xd0, 0x24, 0xe2, 0xb4, 0x24, 0xe8, 0xd0, 0x08, 0x5e, 0x15, 0x9b, 0xb3, 0xae, 0x2a, 0x85, 0xd0, 0xfb, 0x93, 0x1a, 0x07, 0xdc, 0x94, 0x3d, 0x8d, 0xe4, 0xb4, 0xe8, 0x38, 0x1c, 0xa9, 0x23, 0x9e, 0x4f, 0xc0, 0x1a, 0x11, 0x5a, 0x92, 0xbb, 0xfd, 0x78, 0x86, 0x56, 0x43, 0x90, 0x6c, 0x46, 0x36, 0x30, 0x8a, 0x0d, 0x32, 0xb3, 0x01, 0x92, 0x7b, 0xeb, 0xf0, 0xf8, 0x6d, 0xad, 0x8f, 0x22, 0xb6, 0x51, 0x2e, 0x30, 0xf2, 0x3c, 0xb6, 0xe6, 0x4e, 0xa9, 0x62, 0x26, 0x0b, 0x35, 0x1a, 0x51, 0xa8, 0x42, 0xe9, 0x5f, 0x5a, 0xa1, 0x7f, 0xba, 0x68, 0x9f, 0xa1, 0xb6, 0xb2, 0xed, 0x0c, 0xe6, 0xa9, 0xb3, 0x2e, 0xd6, 0x5b, 0x9a, 0x60, 0xd4, 0x14, 0xd4, 0xe3, 0xa1, 0xbb, 0xb5, 0x29, 0xc9, 0x12, 0x95, 0xd4, 0xd8, 0x0b, 0x98, 0x09, 0xd9, 0x86, 0xdf, 0xe5, 0xc3, 0x53, 0x04, 0x8d, 0xbc, 0xdc, 0xb1, 0x70, 0xa1, 0x40, 0x7f, 0xdf, 0xad, 0xcc, 0x74, 0x60, 0x1a, 0xb6, 0xcc, 0x80, 0x92, 0xf1, 0xd4, 0x09, 0xea, 0x65, 0x2a, 0xe9, 0x55, 0xdc, 0xb9, 0x7e, 0x19, 0xaf, 0x48, 0xa5, 0xef, 0xf1, 0x7c, 0x4a, 0x0a, 0x98, 0xda, 0x01, 0x24, 0xa1, 0xfb, 0x62, 0x94, 0x2a, 0x26, 0x4d, 0x67, 0xeb, 0x96, 0xc8, 0xb6, 0xcf, 0x96, 0x12, 0xcf, 0xd0, 0xc7, 0xb1, 0xac, 0xcc, 0x09, 0x5d, 0x5d, 0x66, 0x14, 0xc1, 0xeb, 0xf7, 0x08, 0x4c, 0x54, 0xb1, 0xc7, 0x92, 0x88, 0x6d, 0xee, 0x8c, 0xb4, 0xd8, 0x47, 0x41, 0x4c, 0x3f, 0x50, 0xc1, 0xa2, 0xbb, 0x5c, 0x24, 0x25, 0xd2, 0xb1, 0xd4, 0xe4, 0x15, 0xcc, 0xcc, 0xef, 0xe1, 0x40, 0xc8, 0x76, 0xaf, 0xa6, 0xb8, 0x2b, 0xf7, 0xb1, 0xdb, 0x63, 0x58, 0x45, 0xdc, 0x8f, 0x7e, 0x90, 0x22, 0xf5, 0xed, 0x2e, 0xca, 0x92, 0xd3, 0x92, 0xa0, 0xe8, 0xab, 0x12, 0xaf, 0x96, 0xec, 0xa9, 0x2a, 0x47, 0x9a, 0x97, 0x65, 0x94, 0x65, 0x66, 0xe0, 0xc5, 0x2d, 0xdf, 0xf3, 0x61, 0xcd, 0x1d, 0x6b, 0x48, 0x00, 0x5e, 0x8d, 0x91, 0xf1, 0x1e, 0xa6, 0x61, 0x3d, 0xde, 0x31, 0x02, 0x69, 0x81, 0x2b, 0x2b, 0x30, 0x2e, 0x9e, 0xb0, 0xd0, 0x47, 0x0e, 0x53, 0xea, 0x03, 0x57, 0xc1, 0x94, 0x62, 0x3d, 0xce, 0x64, 0x03, 0x20, 0x93, 0x55, 0x2f, 0xd1, 0xc9, 0xfb, 0x96, 0xc7, 0x39, 0x61, 0xdc, 0x12, 0x87, 0xbe, 0x1e, 0xcb, 0xea, 0xbb, 0x87, 0x30, 0x3d, 0x35, 0x14, 0xac, 0x3f, 0x64, 0x8a, 0xcf, 0xcd, 0x8d, 0xe9, 0xb9, 0xbf, 0xbf, 0xc7, 0x70, 0xd0, 0xe0, 0x6f, 0x8a, 0x5b, 0xc9, 0xc7, 0x5a, 0xce, 0x8b, 0x30, 0xa1, 0xf5, 0xa0, 0xfd, 0x4b, 0x24, 0x0c, 0xf3, 0xb6, 0xfc, 0xfe, 0xb9, 0xdf, 0xbb, 0xfe, 0x21, 0x63, 0xb9, 0x6f, 0xe9, 0x65, 0x0f, 0x8c, 0x3e, 0xac, 0x2d, 0x26, 0xcc, 0xc8, 0x68, 0x6f, 0x32, 0x40, 0x91, 0x33, 0x1b, 0xcb, 0xf0, 0x7a, 0x11, 0x46, 0x78, 0x01, 0xc0, 0xa1, 0xf6, 0x78, 0xdd, 0x38, 0x66, 0xe2, 0xf3, 0x97, 0x2f, 0xfc, 0xdd, 0x7a, 0xd8, 0x26, 0x54, 0xbd, 0xb5, 0xa3, 0x94, 0xe4, 0x08, 0x5e, 0x65, 0xc6, 0x58, 0x62, 0x53, 0xcb, 0x46, 0x9a, 0x36, 0xd1, 0xf6, 0x43, 0xf9, 0x39, 0x10, 0xc9, 0x33, 0x7c, 0x1a, 0x31, 0x91, 0x42, 0xdf, 0xf8, 0x48, 0xaf, 0xa5, 0x86, 0x4a, 0x5c, 0x48, 0x30, 0x62, 0x72, 0x23, 0x55, 0x69, 0x94, 0x9c, 0x67, 0x61, 0xa9, 0x99, 0xeb, 0xef, 0xbf, 0xe7, 0xe1, 0x7e, 0x24, 0x62, 0x38, 0xa8, 0x86, 0xd7, 0x3a, 0xa0, 0x95, 0x23, 0x82, 0x7c, 0xf0, 0x5c, 0x6b, 0xa7, 0x90, 0x2f, 0x81, 0x04, 0x52, 0xaa, 0x22, 0xe2, 0xab, 0x07, 0x7b, 0x22, 0x80, 0xec, 0xa2, 0x75, 0x6c, 0x53, 0x64, 0xb4, 0xe2, 0x28, 0xfb, 0xe3, 0xad, 0xab, 0xc4, 0x51, 0x52, 0xf2, 0x94, 0xc1, 0x0a, 0xb7, 0x33, 0x8e, 0x52, 0x4c, 0x70, 0x50, 0xce, 0x09, 0xed, 0xe3, 0x0a, 0x73, 0xb6, 0x4c, 0x59, 0xe0, 0xb8, 0x5e, 0x0d, 0xd2, 0xdb, 0x88, 0x74, 0xdd, 0x3b, 0xc3, 0x4c, 0x90, 0x2e, 0x95, 0x3b, 0x37, 0xf3, 0x81, 0xc7, 0x2e, 0xb4, 0xa4, 0x15, 0x00, 0x30, 0x38, 0xc9, 0x43, 0x1e, 0xbe, 0x91, 0xa1, 0x82, 0x7c, 0xf8, 0x1d, 0x67, 0x6f, 0x0e, 0x71, 0x10, 0x36, 0xf6, 0x3c, 0x01, 0xca, 0x8f, 0x43, 0xfd, 0xb7, 0x8d, 0xf7, 0x52, 0x54, 0x21, 0x9b, 0xb1, 0x5f, 0x40, 0x84, 0xbb, 0xd2, 0xa7, 0x1a, 0xd3, 0xaa, 0xee, 0xb6, 0xef, 0x40, 0xbf, 0x1f, 0x47, 0x3d, 0xba, 0x91, 0xa8, 0x85, 0x2a, 0x13, 0x14, 0xf2, 0xdc, 0x84, 0x9f, 0xeb, 0xca, 0x97, 0xe6, 0xdb, 0x3e, 0x39, 0x14, 0xe6, 0x99, 0xe5, 0x80, 0x14, 0x20, 0xe4, 0x0b, 0xb3, 0x32, 0x5a, 0x9e, 0x69, 0xa7, 0x4c, 0x8c, 0xb7, 0x1f, 0x9f, 0xb7, 0x2c, 0x82, 0x20, 0x92, 0xf0, 0x0d, 0x39, 0x97, 0x41, 0x3c, 0xb4, 0xa1, 0x60, 0x67, 0x08, 0x44, 0xcc, 0x9c, 0xca, 0x0b, 0x44, 0xb6, 0xb1, 0x35, 0x49, 0xcc, 0xa7, 0xaf, 0xc1, 0x14, 0x01, 0xaa, 0x6f, 0xf9, 0x1d, 0x8e, 0xc6, 0x1e, 0x93, 0x19, 0xf1, 0x03, 0x16, 0x93, 0x48, 0x7b, 0xf5, 0x6d, 0xb5, 0x43, 0xa2, 0xa4, 0x9a, 0x47, 0x1c, 0x30, 0x0b, 0xcc, 0x02, 0x8f, 0x96, 0x06, 0x48, 0x09, 0x6c, 0xbb, 0x10, 0xd1, 0xb8, 0x01, 0xb7, 0x83, 0xdb, 0x76, 0x01, 0x3d, 0x0c, 0x3c, 0xbb, 0x2f, 0x1e, 0x01, 0x9a, 0xea, 0x7f, 0x17, 0xc2, 0xc7, 0xc2, 0xcc, 0xe2, 0x7c, 0xde, 0xa6, 0xf9, 0x58, 0x36, 0xbf, 0x76, 0xdd, 0x1b, 0xee, 0x3d, 0x86, 0x17, 0xaf, 0xda, 0xc5, 0x2a, 0xd2, 0x2b, 0xb3, 0xfa, 0x00, 0xf5, 0x66, 0xde, 0xc4, 0x5f, 0xfa, 0x3e, 0x98, 0x31, 0x83, 0xb5, 0x79, 0x4d, 0x17, 0x32, 0xf4, 0x6a, 0xcd, 0xe3, 0xa3, 0xdd, 0xfa, 0xe8, 0x6a, 0xe6, 0x3e, 0x86, 0xeb, 0x79, 0xe1, 0xfd, 0xd2, 0x7b, 0xcc, 0x39, 0xda, 0x06, 0xe4, 0x80, 0x09, 0x0d, 0xf5, 0x62, 0xda, 0x9e, 0xe5, 0x89, 0xee, 0xe7, 0x0d, 0xc5, 0xb9, 0xd6, 0x88, 0xf9, 0xad, 0x6c, 0xec, 0x7a, 0x00, 0x46, 0x9a, 0xd8, 0x49, 0xc3, 0x40, 0xc3, 0x4b, 0xcc, 0x21, 0xbc, 0x31, 0xf4, 0xee, 0xcb, 0x64, 0x89, 0x09, 0x66, 0x41, 0x6d, 0x38, 0xd3, 0x9f, 0xcc, 0x50, 0x6d, 0xed, 0x6a, 0xcb, 0x29, 0x72, 0x32, 0x50, 0x41, 0xbd, 0x34, 0x8f, 0x61, 0x7e, 0x3d, 0xd3, 0x63, 0xcf, 0x52, 0x96, 0x5b, 0x0a, 0x23, 0xf8, 0x0a, 0x1a, 0xbf, 0x9a, 0xb1, 0xa6, 0x9c, 0x19, 0x7f, 0x87, 0xc1, 0xe9, 0x0f, 0xad, 0xd0, 0x49, 0x0b, 0x96, 0x19, 0x1a, 0x1d, 0x49, 0x8d, 0x8e, 0x93, 0xa5, 0x6d, 0x1e, 0x3a, 0xe2, 0xe2, 0x72, 0x80, 0x92, 0x3b, 0xa8, 0x06, 0xa6, 0x5e, 0xad, 0x35, 0xb6, 0xb2, 0xd9, 0xee, 0xed, 0x00, 0xb5, 0xa1, 0xe2, 0x0f, 0x06, 0xe1, 0xe7, 0xb4, 0x2d, 0x3e, 0x29, 0xba, 0xae, 0x1d, 0x3a, 0x59, 0x5d, 0xef, 0xeb, 0xd2, 0xb8, 0x14, 0xac, 0x52, 0x1c, 0x5a, 0xbd, 0xe8, 0x88, 0x48, 0xc7, 0xde, 0x49, 0xca, 0xe2, 0x0b, 0x36, 0x7f, 0xb4, 0xa9, 0xab, 0x46, 0xf1, 0x7f, 0x36, 0x0a, 0xbc, 0x12, 0x34, 0xb3, 0xae, 0x29, 0xf0, 0xd6, 0x0f, 0x03, 0xca, 0x90, 0x2f, 0xaa, 0x08, 0xe6, 0x4c, 0xca, 0xdc, 0x97, 0xc8, 0x9b, 0xc2, 0xd3, 0x4e, 0x04, 0x4f, 0x6b, 0x87, 0x0a, 0x72, 0xc3, 0x61, 0x50, 0x9e, 0xa0, 0x27, 0x9f, 0xbf, 0x0c, 0xcb, 0x08, 0x90, 0x00, 0x41, 0x41, 0xc7, 0xbb, 0xef, 0x99, 0x8e, 0x16, 0xbd, 0x18, 0x1d, 0x0e, 0x40, 0x81, 0x0c, 0x91, 0x91, 0x81, 0x31, 0x28, 0xf0, 0xdf, 0x80, 0xc9, 0x1a, 0xb6, 0x3d, 0xae, 0xe1, 0x01, 0xdf, 0xab, 0x3b, 0x9f, 0xc9, 0x4a, 0x0b, 0xcc, 0xc0, 0x5d, 0xaf, 0x6d, 0x59, 0xba, 0x4a, 0x94, 0x13, 0xcf, 0xd7, 0x3c, 0x5e, 0xbc, 0xb8, 0x57, 0x1f, 0xaa, 0xaa, 0xc8, 0x2b, 0xc1, 0xe7, 0x74, 0xa6, 0x02, 0x54, 0x4d, 0x88, 0xb1, 0xc4, 0x13, 0xe7, 0xa9, 0x25, 0x8b, 0xea, 0x67, 0xc4, 0x2f, 0xc9, 0x8c, 0x13, 0x50, 0xd9, 0xca, 0xd4, 0x13, 0x71, 0xd0, 0xfa, 0x31, 0x9b, 0x2f, 0x3e, 0x77, 0x56, 0x24, 0xce, 0x8b, 0x63, 0x12, 0xe1, 0x29, 0x0b, 0x25, 0xe7, 0xdc, 0x03, 0xbd, 0xf8, 0xc6, 0xbb, 0x7b, 0x2e, 0x07, 0x1a, 0xa0, 0x7a, 0xe3, 0x0b, 0x47, 0xa9, 0xd2, 0x52, 0x3e, 0x28, 0x85, 0x02, 0x3a, 0x58, 0xb1, 0xf5, 0x54, 0x4a, 0x21, 0x46, 0x92, 0xd1, 0x43, 0xaa, 0x26, 0xf8, 0x86, 0x85, 0x89, 0x6f, 0x52, 0xbd, 0xcd, 0x77, 0x25, 0x8a, 0xad, 0x61, 0xdc, 0x6e, 0x83, 0x27, 0x33, 0xb3, 0x50, 0xee, 0x6f, 0x29, 0x2f, 0x64, 0x52, 0x66, 0xe2, 0xbf, 0xf4, 0x6a, 0x1a, 0x15, 0x51, 0xcb, 0x36, 0xb6, 0x58, 0x70, 0x99, 0xc3, 0x52, 0x1d, 0xb6, 0xb5, 0x38, 0x66, 0xe6, 0xff, 0xf5, 0x25, 0x91, 0xc7, 0x3e, 0x54, 0xc9, 0x9b, 0x13, 0xba, 0x4b, 0xda, 0x39, 0xd2, 0xd2, 0x5b, 0xa3, 0x14, 0x85, 0x08, 0x78, 0x96, 0x14, 0x8e, 0x04, 0x7d, 0xe9, 0x2a, 0xf8, 0x74, 0x75, 0x5e, 0x85, 0x46, 0x07, 0x3f, 0x72, 0xc5, 0x43, 0x27, 0xde, 0x7a, 0xea, 0x68, 0x7d, 0xe8, 0x7a, 0x8f, 0xc3, 0x2d, 0x9d, 0x72, 0xb0, 0x52, 0xe5, 0x36, 0xfa, 0x87, 0x01, 0x34, 0x37, 0x12, 0x8a, 0x74, 0x86, 0x1f, 0x4a, 0x40, 0x2b, 0xd1, 0xfe, 0x22, 0x6f, 0x5c, 0xc8, 0x0a, 0x8c, 0x31, 0x43, 0x12, 0x72, 0x64, 0xbd, 0x6b, 0xe7, 0x17, 0x72, 0xe3, 0xfd, 0x7f, 0xf6, 0x81, 0x76, 0xa9, 0x43, 0xdd, 0x52, 0x5d, 0xbc, 0x3b, 0xf7, 0xa0, 0x94, 0xce, 0xd6, 0xc0, 0xdc, 0xb1, 0xa0, 0xde, 0x82, 0xe5, 0xa5, 0x27, 0x31, 0x03, 0xad, 0x64, 0x94, 0x77, 0x7c, 0xd3, 0xdf, 0x8a, 0x8e, 0x95, 0x20, 0xd9, 0x87, 0xad, 0x27, 0x44, 0xc4, 0x61, 0xb2, 0x32, 0x41, 0x0b, 0xa7, 0x30, 0x28, 0xd4, 0x5d, 0xe4, 0xdb, 0xd2, 0xad, 0xbc, 0x2d, 0x6c, 0x1d, 0xd6, 0xb1, 0xf9, 0xc2, 0x39, 0x91, 0x55, 0x02, 0xec, 0x9b, 0x60, 0xba, 0x07, 0xdb, 0x3f, 0x1a, 0x46, 0x6d, 0x02, 0xf7, 0xd8, 0x6e, 0x1f, 0x7a, 0x58, 0xa0, 0x26, 0xf0, 0x5f, 0xf1, 0x4c, 0x12, 0xc5, 0x6c, 0xf1, 0x85, 0x38, 0x77, 0x9c, 0x54, 0x6d, 0x8d, 0x2d, 0x27, 0x62, 0x0c, 0x75, 0x82, 0xef, 0xb3, 0xfd, 0x18, 0x91, 0x68, 0xef, 0xe1, 0xa8, 0x69, 0x92, 0xbf, 0x14, 0xc4, 0x09, 0x2c, 0x88, 0xee, 0x51, 0x87, 0xfb, 0xb7, 0x81, 0x2b, 0x4c, 0x69, 0xde, 0x88, 0x0c, 0xb7, 0xbe, 0x2e, 0xc2, 0xa6, 0xb1, 0xe6, 0xda, 0xd1, 0x3e, 0x4f, 0xb3, 0x55, 0xd0, 0xbb, 0xa9, 0xe3, 0x62, 0xfb, 0x48, 0xb3, 0x5e, 0x6d, 0x0a, 0xd1, 0xd7, 0x4e, 0x89, 0x01, 0xdf, 0xd3, 0x7d, 0x39, 0x3b, 0x02, 0xff, 0x79, 0x05, 0x65, 0x8a, 0xdf, 0xc8, 0x8d, 0x4b, 0x11, 0x69, 0x30, 0xa8, 0x8a, 0x76, 0x1a, 0xca, 0xf4, 0xa4, 0xf6, 0xbf, 0x53, 0x1a, 0xbb, 0x05, 0xfa, 0xa0, 0xb4, 0x1a, 0x85, 0x3e, 0x59, 0xfd, 0xf3, 0xaf, 0x79, 0xdb, 0x13, 0xcb, 0x20, 0x95, 0x86, 0x07, 0xde, 0xb7, 0x03, 0x6f, 0xdb, 0xc5, 0x63, 0x9a, 0x7f, 0xe3, 0xc5, 0x0d, 0x89, 0x09, 0xb0, 0x3a, 0x5b, 0x83, 0x37, 0x10, 0x66, 0xf1, 0xb1, 0x11, 0xfd, 0xd5, 0x15, 0x12, 0x88, 0x83, 0x34, 0xf1, 0xba, 0xdb, 0xc9, 0xd7, 0x2a, 0xda, 0x7f, 0x6e, 0x6d, 0xc5, 0xe6, 0x04, 0x20, 0x23, 0x88, 0x41, 0xef, 0x0d, 0xba, 0x0b, 0xc1, 0x7f, 0x62, 0xd3, 0xe9, 0x91, 0x9f, 0xc2, 0x1a, 0xbc, 0x7a, 0xd3, 0x8a, 0xea, 0xae, 0xfd, 0x3e, 0x71, 0xdb, 0xa0, 0x7f, 0x2d, 0x79, 0xee, 0x83, 0x69, 0xcd, 0xb4, 0x33, 0x0f, 0x83, 0xd0, 0xa7, 0x87, 0x76, 0x5a, 0x9c, 0xe4, 0xce, 0xe6, 0xec, 0xfb, 0x81, 0x3a, 0xa9, 0x31, 0x8c, 0x40, 0xe0, 0x20, 0x6c, 0x01, 0x03, 0x29, 0x05, 0xe1, 0x21, 0x67, 0xcd, 0x3f, 0x00, 0xa5, 0x36, 0x22, 0x33, 0x74, 0x7d, 0xed, 0x9d, 0xc9, 0xfa, 0xe2, 0xda, 0x16, 0x22, 0x5c, 0xa8, 0x44, 0xa6, 0x6a, 0x4b, 0x79, 0x42, 0xb7, 0xd6, 0x1d, 0x27, 0x13, 0xe2, 0x7d, 0x2e, 0x5b, 0x30, 0x9d, 0x0a, 0x1a, 0xcd, 0x37, 0x8b, 0x4c, 0x81, 0xc4, 0x21, 0x31, 0x20, 0xc9, 0xdb, 0xb1, 0xed, 0x90, 0x49, 0x7d, 0xe4, 0x65, 0xf5, 0x67, 0x11, 0x7d, 0x13, 0x5d, 0xa1, 0xb2, 0xf3, 0x6e, 0x28, 0x88, 0x02, 0x5e, 0xf4, 0xdc, 0x50, 0x08, 0x0e, 0xd9, 0xee, 0x14, 0x7e, 0x93, 0x8e, 0x6a, 0x44, 0x5c, 0xcf, 0x4d, 0xe5, 0xc6, 0xe1, 0xf1, 0xc3, 0x98, 0x2e, 0x32, 0x4c, 0x18, 0xaf, 0x4a, 0x1c, 0x37, 0x2c, 0x6e, 0x6c, 0x8e, 0xcf, 0x9f, 0xcf, 0xe5, 0x08, 0xf5, 0x42, 0xa5, 0x1c, 0x90, 0x32, 0x20, 0xe1, 0xb1, 0xe5, 0x60, 0x32, 0xd9, 0x53, 0xd7, 0x11, 0xbe, 0xb0, 0x33, 0x80, 0x27, 0x7a, 0x87, 0x47, 0x59, 0x11, 0x55, 0x50, 0xf0, 0xa5, 0x06, 0x83, 0xfa, 0x06, 0x85, 0x99, 0x00, 0x0e, 0x72, 0x2c, 0x2b, 0x14, 0xaa, 0xfe, 0x4d, 0xe2, 0x5a, 0x17, 0x22, 0xdb, 0xf4, 0x54, 0x0a, 0x7f, 0xae, 0xd3, 0x3a, 0xe1, 0xb9, 0xd9, 0x71, 0xbb, 0x1c, 0x52, 0x89, 0xac, 0x36, 0xe5, 0xcd, 0x41, 0x36, 0xff, 0x6b, 0xe6, 0xd2, 0xa3, 0x84, 0x8b, 0xbc, 0xb1, 0x8b, 0x48, 0xa3, 0x58, 0xa9, 0x90, 0x5f, 0xea, 0xd3, 0x31, 0x2d, 0x9a, 0x43, 0xbe, 0xa1, 0x78, 0x3f, 0xd4, 0x51, 0xfc, 0x3b, 0xd2, 0xa6, 0xc3, 0x8b, 0xe8, 0x3a, 0x8d, 0x24, 0x99, 0x84, 0x6d, 0x33, 0x3c, 0xc3, 0xd2, 0xaf, 0x19, 0xb7, 0xcd, 0x23, 0x5c, 0x55, 0x28, 0x2f, 0x06, 0x09, 0x4a, 0xf2, 0x1b, 0xc0, 0x94, 0x81, 0x82, 0xee, 0x8c, 0x30, 0x9e, 0x8a, 0x8a, 0x63, 0x14, 0xe4, 0x72, 0x77, 0x95, 0x81, 0x55, 0x9d, 0x36, 0x67, 0xbb, 0xee, 0xd5, 0x77, 0x93, 0x2e, 0xcd, 0x65, 0x18, 0x9a, 0x1c, 0x0b, 0x4c, 0xed, 0x2c, 0x57, 0x76, 0x08, 0x54, 0x39, 0x1c, 0xd5, 0xed, 0x5f, 0xf3, 0x96, 0xc8, 0x44, 0x29, 0xa8, 0x74, 0x26, 0xb8, 0x98, 0x8c, 0x53, 0xbf, 0x9b, 0xca, 0x27, 0xdc, 0xb7, 0xb3, 0xe5, 0xe3, 0x6f, 0x5e, 0x16, 0xe8, 0x71, 0x71, 0x15, 0xd5, 0x6d, 0x81, 0x14, 0x6f, 0x53, 0xa3, 0xd2, 0xc3, 0x0f, 0x4b, 0xaa, 0xc5, 0x1c, 0x80, 0xc9, 0xc4, 0x54, 0x3c, 0x80, 0xfd, 0x84, 0x16, 0xd3, 0x64, 0xbe, 0x81, 0x89, 0xae, 0xb0, 0xdd, 0x1c, 0x7e, 0xa6, 0x30, 0x98, 0x72, 0xe9, 0x66, 0x6e, 0x59, 0x76, 0x3b, 0x2b, 0x1f, 0xc3, 0x38, 0x83, 0xbb, 0x56, 0x71, 0x7f, 0xdb, 0x7d, 0xfb, 0x19, 0xa2, 0x6c, 0xbe, 0xfe, 0x14, 0xa0, 0x12, 0x34, 0x51, 0x54, 0xfc, 0x2b, 0x45, 0x65, 0x73, 0xff, 0xc5, 0x51, 0x64, 0x2a, 0xf2, 0x9e, 0x05, 0x30, 0x04, 0x13, 0xf1, 0x01, 0x25, 0x04, 0xd3, 0x1c, 0x09, 0xe8, 0xc8, 0x95, 0x40, 0x1c, 0xda, 0x4d, 0x86, 0x6f, 0xc9, 0x8b, 0xab, 0x36, 0xbe, 0x40, 0xf6, 0x59, 0x1a, 0xf6, 0x8c, 0xc1, 0x85, 0xb1, 0x4d, 0x55, 0x7d, 0xc8, 0x77, 0x2f, 0x26, 0x90, 0x26, 0xd6, 0x62, 0x96, 0x5a, 0xcc, 0xcd, 0x67, 0x72, 0x06, 0xd5, 0x76, 0x24, 0x91, 0x6d, 0xbf, 0x8b, 0x9a, 0xb3, 0x0c, 0xd2, 0xe6, 0x15, 0x8a, 0xcc, 0xfc, 0xc0, 0x89, 0x61, 0x90, 0xfa, 0xf8, 0xc1, 0x4b, 0x9c, 0x38, 0x72, 0xda, 0x7f, 0x76, 0x24, 0x6e, 0x67, 0x55, 0xbf, 0xe5, 0xc5, 0x29, 0xfa, 0x1c, 0xdc, 0xb1, 0xe3, 0x9c, 0x32, 0x64, 0xdb, 0x2e, 0x7e, 0x50, 0x6b, 0x11, 0x9d, 0x00, 0x8c, 0xad, 0x2e, 0x93, 0x24, 0xfb, 0x9b, 0xff, 0x7b, 0x33, 0x88, 0x1b, 0x78, 0xf2, 0x27, 0x75, 0xf1, 0x1a, 0xa1, 0x43, 0xd5, 0x03, 0x65, 0xc0, 0x81, 0x89, 0xa5, 0xa0, 0x7c, 0x5e, 0xd6, 0x04, 0xd7, 0x70, 0xbb, 0x4b, 0xbd, 0x9e, 0x58, 0x74, 0xaa, 0x87, 0x81, 0xa4, 0xbf, 0x41, 0x47, 0xee, 0xc9, 0x57, 0xcf, 0x94, 0xf6, 0x86, 0xaf, 0xcb, 0x7a, 0x33, 0xc1, 0x23, 0x32, 0x45, 0xcb, 0xd6, 0x2c, 0x91, 0x79, 0x50, 0x19, 0x0e, 0xf9, 0x29, 0xf6, 0x59, 0xf5, 0x65, 0x2e, 0x62, 0x5d, 0x6a, 0xc1, 0xf0, 0x2a, 0xa4, 0x70, 0xe9, 0xc6, 0x02, 0xa2, 0x8a, 0xcf, 0x10, 0x56, 0xbf, 0x53, 0x49, 0x20, 0xe5, 0x4d, 0xb5, 0x45, 0x64, 0x9e, 0xcf, 0x1a, 0x09, 0xbe, 0x8b, 0xdf, 0xc3, 0x11, 0x73, 0x16, 0x36, 0x96, 0xdc, 0x1c, 0x8d, 0x6e, 0x7b, 0x50, 0xca, 0x82, 0x6c, 0x56, 0xcd, 0x3c, 0x30, 0x4b, 0xce, 0x26, 0x71, 0x2c, 0xed, 0xf5, 0x45, 0x15, 0xff, 0x55, 0xa2, 0x89, 0xc5, 0x6b, 0xc4, 0x67, 0xa4, 0x44, 0xf8, 0x2e, 0x09, 0xb2, 0xb7, 0xe7, 0x93, 0x61, 0x54, 0x38, 0xf5, 0x4b, 0x3f, 0x18, 0x99, 0xa9, 0x51, 0x67, 0xa7, 0x4a, 0xef, 0x13, 0x19, 0x97, 0x07, 0x11, 0x8d, 0xb9, 0xb4, 0xfb, 0x84, 0xd3, 0x9a, 0x9c, 0x25, 0x03, 0x3d, 0x6d, 0x9b, 0x0c, 0x25, 0x84, 0x9c, 0xc3, 0x61, 0x96, 0x8b, 0xaf, 0xbd, 0xc7, 0x6a, 0x4a, 0x26, 0xd4, 0x4f, 0x40, 0xeb, 0xc0, 0x4e, 0x87, 0xd5, 0xd9, 0xb0, 0xac, 0x49, 0xb6, 0x3d, 0x56, 0x99, 0xe3, 0xbe, 0xae, 0xd4, 0xef, 0x4c, 0x47, 0x6d, 0xb1, 0x8d, 0xc1, 0x9c, 0xa1, 0x49, 0xb6, 0x96, 0x1d, 0xdf, 0x56, 0x3b, 0xaa, 0xf1, 0xd1, 0x15, 0xbc, 0x54, 0x17, 0xed, 0xe9, 0xb4, 0x5c, 0x45, 0x48, 0x17, 0xfd, 0xaf, 0xb4, 0x8d, 0x78, 0x01, 0x94, 0xd5, 0xa8, 0x94, 0x3e, 0xee, 0xf3, 0x3c, 0x71, 0x6e, 0xf4, 0x66, 0x3e, 0x23, 0x7a, 0x88, 0xb3, 0xcf, 0xf0, 0xbc, 0x43, 0x89, 0x1c, 0x5b, 0x4a, 0xc9, 0xf0, 0xca, 0xb2, 0x5f, 0xe0, 0xe6, 0xe8, 0xdd, 0x0e, 0xd1, 0xae, 0xdd, 0x6f, 0x77, 0x7a, 0xfd, 0xed, 0x83, 0x68, 0x4e, 0xc8, 0x93, 0xf7, 0xa1, 0xc5, 0x60, 0x10, 0x1a, 0xf9, 0x00, 0x7d, 0xcd, 0xf7, 0xfc, 0x9f, 0xae, 0xbd, 0x81, 0xb0, 0x42, 0xd4, 0xbb, 0x0d, 0x11, 0xae, 0xcf, 0xed, 0xcf, 0x1c, 0xa4, 0xa8, 0xea, 0x34, 0xc8, 0xfd, 0x99, 0xed, 0x75, 0x6f, 0x91, 0x42, 0x32, 0xf5, 0x3b, 0x5a, 0x49, 0xea, 0x12, 0xbc, 0x51, 0xd4, 0xbe, 0x1a, 0x1f, 0x6b, 0x62, 0x25, 0x27, 0x62, 0xf4, 0xbf, 0xbf, 0xb2, 0xc7, 0x10, 0xd6, 0x55, 0x0f, 0x05, 0xd3, 0x17, 0xe5, 0x90, 0x62, 0x5a, 0xd1, 0x3b, 0xc6, 0xd7, 0x36, 0xc3, 0x27, 0x7c, 0xb1, 0x30, 0x3c, 0x7b, 0x8f, 0x25, 0xbe, 0xb0, 0x69, 0x0d, 0x13, 0x61, 0x41, 0x1f, 0x00, 0x9c, 0x1b, 0xea, 0x24, 0xef, 0x44, 0xdf, 0xd1, 0xd3, 0xf4, 0xf4, 0x45, 0xdc, 0xbe, 0x75, 0x6b, 0x30, 0x58, 0x16, 0x99, 0xff, 0x46, 0x10, 0x0d, 0x4a, 0x80, 0xd8, 0xf1, 0xe6, 0x2b, 0xa6, 0x35, 0x45, 0x30, 0x69, 0x0b, 0x2e, 0xc0, 0x6c, 0xb8, 0x75, 0x31, 0x8a, 0x05, 0x60, 0x96, 0x33, 0x69, 0x1a, 0xa7, 0x1d, 0xbd, 0x5f, 0x77, 0x34, 0xf7, 0x00, 0xf6, 0xe3, 0xa8, 0xec, 0xe2, 0x73, 0xaa, 0xc4, 0x72, 0x3e, 0x32, 0xf9, 0xe0, 0xf7, 0x2d, 0xee, 0x62, 0xa3, 0xc0, 0xe6, 0xf4, 0xde, 0xae, 0xbc, 0xfc, 0x59, 0x0f, 0x53, 0x7e, 0xe1, 0x86, 0xe3, 0x59, 0xfd, 0xd2, 0x68, 0xab, 0x99, 0x5c, 0x66, 0xf7, 0x16, 0xd1, 0xec, 0xcb, 0x07, 0xee, 0x41, 0x13, 0x08, 0xbd, 0xba, 0x1c, 0x78, 0xbf, 0x6c, 0xf5, 0x77, 0xa3, 0xbd, 0x55, 0xaf, 0x26, 0x92, 0xa2, 0x3c, 0x90, 0x00, 0xcf, 0x99, 0x60, 0x81, 0xc4, 0xcf, 0xd1, 0xba, 0x9f, 0x62, 0xb7, 0x8b, 0x14, 0x49, 0x4f, 0xa7, 0x6c, 0x3c, 0xc8, 0x99, 0xac, 0x6a, 0x69, 0x36, 0x5e, 0x31, 0x6c, 0x58, 0xc3, 0xbf, 0x48, 0x47, 0xce, 0x5b, 0x1a, 0x0b, 0xb5, 0x0b, 0xf0, 0x11, 0x67, 0x85, 0x1b, 0x10, 0x33, 0x45, 0x39, 0xc1, 0x41, 0xef, 0xa6, 0xa4, 0x15, 0x03, 0xb6, 0xec, 0x09, 0x3d, 0x5f, 0x22, 0xa9, 0x70, 0x83, 0xa1, 0x73, 0xe6, 0xeb, 0xfb, 0xa3, 0x92, 0xf5, 0x21, 0xbd, 0x03, 0x19, 0x15, 0xb1, 0x73, 0xc2, 0xe6, 0x44, 0xb9, 0x30, 0x0e, 0x39, 0xce, 0xe7, 0x07, 0x49, 0x7b, 0x6d, 0x7b, 0x02, 0x74, 0xa7, 0xbd, 0x38, 0x35, 0xb3, 0x59, 0x3a, 0x10, 0x6b, 0xf4, 0xf2, 0xba, 0xd4, 0xb5, 0xbf, 0xe1, 0x1e, 0x00, 0xed, 0x33, 0x2f, 0xc7, 0xf3, 0x45, 0x46, 0xaf, 0xb9, 0xf2, 0xe2, 0x07, 0x4a, 0xf1, 0xce, 0xa6, 0x87, 0x2f, 0xeb, 0x58, 0x33, 0xc2, 0x53, 0xb2, 0xd2, 0x5e, 0x5d, 0x85, 0x95, 0xa6, 0xcc, 0x4e, 0x39, 0x63, 0x66, 0xa4, 0xb2, 0x7b, 0xbe, 0x81, 0x85, 0xe1, 0xaf, 0xb0, 0x62, 0x9f, 0x71, 0xe1, 0x7a, 0xd1, 0xa7, 0xb9, 0xb4, 0x8c, 0x10, 0xaf, 0x68, 0xd6, 0xb1, 0xc9, 0x83, 0x0a, 0xce, 0x75, 0x73, 0xb7, 0x18, 0x19, 0x91, 0xe4, 0x2b, 0x51, 0x2d, 0x7b, 0xa2, 0x6f, 0xfb, 0x06, 0x66, 0xc6, 0xaf, 0x9c, 0xbb, 0x7a, 0xc9, 0x31, 0x09, 0xec, 0x0b, 0x2c, 0x57, 0x53, 0xec, 0xd7, 0x83, 0x68, 0xb1, 0xd3, 0x3a, 0x57, 0xff, 0xe4, 0x57, 0x03, 0xa1, 0xe3, 0x55, 0x0a, 0xe2, 0x0c, 0xb9, 0x79, 0x86, 0x7b, 0xf6, 0xf8, 0x82, 0x0d, 0xb8, 0x44, 0xb6, 0x4b, 0x3d, 0x1e, 0x2b, 0xa4, 0xa8, 0xbf, 0xe8, 0x45, 0xc4, 0xdd, 0xcb, 0xee, 0x00, 0xfa, 0x2b, 0xa7, 0xe2, 0xd7, 0xa7, 0xef, 0x7e, 0x90, 0x80, 0x7f, 0x59, 0x2a, 0x99, 0xfd, 0x51, 0xe1, 0xed, 0x04, 0xa4, 0xfe, 0x3d, 0x27, 0x96, 0xe9, 0xb4, 0xed, 0xef, 0x70, 0x23, 0x60, 0x5e, 0x43, 0x2c, 0x7e, 0xb1, 0xfb, 0xa5, 0x1f, 0x5d, 0x30, 0xd2, 0x6a, 0x47, 0x16, 0x11, 0x38, 0x07, 0x3c, 0x01, 0x0c, 0x5e, 0x10, 0x13, 0x95, 0x55, 0x85, 0xea, 0x14, 0xf8, 0xda, 0x90, 0x11, 0xb4, 0x2a, 0x63, 0x89, 0x09, 0x13, 0x1c, 0x90, 0x4d, 0x22, 0x39, 0x80, 0xdf, 0xa8, 0xcd, 0x95, 0x73, 0x91, 0xaf, 0x61, 0xb1, 0xc1, 0xcb, 0x67, 0x0f, 0xde, 0xd3, 0xb8, 0xff, 0x77, 0x14, 0x0a, 0x2d, 0xb3, 0x5f, 0x8d, 0xc6, 0x44, 0x93, 0x4f, 0x86, 0x57, 0x6c, 0xa2, 0xa5, 0x05, 0x3d, 0x03, 0xd2, 0x4f, 0x85, 0x44, 0x4f, 0x51, 0x55, 0x25, 0xfd, 0xb8, 0x69, 0x1c, 0x72, 0x99, 0x0d, 0xb4, 0x25, 0x42, 0xd9, 0x13, 0x0c, 0x56, 0x50, 0x8d, 0x6f, 0x7e, 0xca, 0xa8, 0x20, 0xd1, 0xf1, 0x9f, 0xbb, 0xc2, 0x13, 0xfa, 0x2b, 0x46, 0x01, 0xf3, 0xe7, 0x2a, 0x25, 0x60, 0xf6, 0xb2, 0xb5, 0x9c, 0x82, 0x40, 0xc2, 0xdc, 0x3c, 0x54, 0x38, 0x7a, 0x7e, 0xa5, 0x3d, 0xd1, 0xf5, 0x65, 0x7c, 0x3e, 0x92, 0x18, 0xa4, 0xe7, 0x2b, 0x78, 0x94, 0xa5, 0x1f, 0x49, 0x61, 0x52, 0x43, 0xe4, 0x22, 0x2e, 0x81, 0xa7, 0x1d, 0x25, 0x8c, 0xf0, 0xbf, 0xec, 0xf0, 0xa0, 0xa3, 0x70, 0xd7, 0x92, 0x2f, 0xb1, 0x65, 0x75, 0xe4, 0x19, 0x25, 0xb9, 0x38, 0xde, 0xc2, 0x64, 0x64, 0x39, 0x44, 0x93, 0xc0, 0x8b, 0x63, 0xa2, 0xd7, 0x6b, 0x4e, 0x75, 0xf7, 0x8d, 0x3f, 0xa8, 0x47, 0x3a, 0xbd, 0x28, 0xc8, 0xf3, 0x84, 0x60, 0xa9, 0xd0, 0x75, 0x06, 0x3e, 0xad, 0x34, 0x56, 0xca, 0xdf, 0x8c, 0x18, 0x2d, 0x6f, 0xc6, 0xa5, 0x8b, 0x98, 0x0a, 0x57, 0x7e, 0x1c, 0x72, 0xb9, 0xfe, 0xc1, 0x64, 0x15, 0x90, 0x8e, 0x08, 0xe9, 0xc1, 0x57, 0x6e, 0x4f, 0x3c, 0xaa, 0xa0, 0x5c, 0xd4, 0x0a, 0xa3, 0x87, 0x22, 0xf7, 0x80, 0xe8, 0xd4, 0xeb, 0x8e, 0x2e, 0x0e, 0xf7, 0x0f, 0x56, 0x45, 0x58, 0x07, 0x1c, 0x58, 0xbc, 0xc8, 0xd8, 0xd1, 0xe3, 0x41, 0xea, 0x27, 0xf1, 0x53, 0xeb, 0x9a, 0xd4, 0x76, 0xdf, 0x0d, 0x70, 0xd9, 0x12, 0xf0, 0xb3, 0x61, 0xce, 0xf9, 0x00, 0xe4, 0x24, 0x1e, 0x7c, 0xd3, 0x9b, 0xe4, 0xa5, 0xe5, 0xf0, 0x5d, 0x02, 0x5b, 0x52, 0xdf, 0xd8, 0x12, 0xbd, 0xec, 0xd9, 0x67, 0x94, 0xb6, 0x65, 0x31, 0x3a, 0xbe, 0xf3, 0xba, 0x85, 0xc6, 0x8d, 0x5a, 0x00, 0x3e, 0xe7, 0xe3, 0x91, 0x60, 0x03, 0xf8, 0xe8, 0x78, 0x8e, 0x21, 0xfc, 0x5e, 0x3c, 0x56, 0x89, 0xd6, 0x27, 0x7a, 0xb9, 0xb9, 0xa0, 0x29, 0x7b, 0x93, 0x79, 0x16, 0x8d, 0xe3, 0x8e, 0x8f, 0x28, 0xb1, 0x10, 0xda, 0x34, 0xb9, 0xc9, 0xcd, 0x8e, 0x66, 0x57, 0x65, 0x77, 0x2d, 0x44, 0x16, 0x83, 0xa0, 0x74, 0x57, 0x25, 0x60, 0x38, 0x3a, 0xf1, 0x9f, 0x89, 0x2b, 0xd1, 0x16, 0xd4, 0x02, 0xa2, 0x75, 0x9a, 0x4e, 0xe4, 0x4c, 0xa9, 0x35, 0x56, 0xeb, 0xa4, 0xf4, 0xa3, 0x2c, 0x0d, 0xa5, 0xec, 0x58, 0x45, 0xe5, 0x98, 0xbb, 0x1d, 0xf5, 0x9b, 0xa6, 0x6a, 0x2a, 0x9e, 0x15, 0xd5, 0x09, 0x9e, 0x56, 0xfc, 0xae, 0x0c, 0x4d, 0xb0, 0x9e, 0x04, 0x1c, 0xb7, 0xd2, 0x3d, 0xe8, 0x8d, 0xe9, 0x47, 0x03, 0x12, 0x23, 0xd9, 0xab, 0x51, 0xf0, 0x42, 0xca, 0x23, 0x19, 0x85, 0xc0, 0x34, 0xd7, 0xe8, 0x0b, 0xf5, 0x2d, 0xe4, 0xcd, 0xdb, 0x6d, 0x8a, 0x67, 0x7f, 0xcd, 0xae, 0x58, 0x48, 0x55, 0xef, 0x35, 0xb6, 0xc0, 0x2f, 0x5c, 0xc3, 0xeb, 0xd3, 0xae, 0xf3, 0x38, 0x37, 0x47, 0x0c, 0xa4, 0x10, 0xb2, 0xc4, 0x80, 0xab, 0x93, 0x6c, 0x0a, 0x70, 0xac, 0x09, 0xdf, 0x34, 0xc7, 0x78, 0x85, 0x33, 0xae, 0xf2, 0x89, 0xa1, 0xf3, 0xea, 0xd5, 0x80, 0x50, 0x8c, 0x79, 0xe0, 0x92, 0xd9, 0x46, 0x14, 0xcb, 0x5a, 0x0d, 0xd4, 0xdb, 0x8b, 0xa7, 0x47, 0x03, 0xb6, 0x8c, 0xd1, 0x91, 0xe0, 0xd7, 0x3f, 0x73, 0xa9, 0x01, 0xa2, 0xe1, 0x6c, 0x86, 0xe1, 0xc5, 0xf5, 0x99, 0x74, 0x99, 0x87, 0x48, 0xd0, 0xeb, 0x9a, 0xe6, 0x44, 0xd4, 0x58, 0x6f, 0xb5, 0x2b, 0xa7, 0x5b, 0xaa, 0xcb, 0xde, 0xc3, 0x09, 0xb8, 0xf6, 0x52, 0xae, 0xf7, 0x54, 0xc4, 0x06, 0x2e, 0x78, 0xee, 0xdf, 0x94, 0x85, 0xa7, 0x50, 0x07, 0x66, 0xe9, 0x16, 0x85, 0x6b, 0xdd, 0x95, 0xc3, 0xd0, 0x5e, 0xbc, 0xb9, 0x3e, 0xc7, 0x47, 0x29, 0xfa, 0x39, 0xb2, 0xcb, 0x49, 0xdd, 0xb7, 0xcb, 0x77, 0xb4, 0x22, 0xcf, 0x3c, 0x8d, 0x8e, 0x1c, 0x6b, 0x72, 0xc3, 0xa1, 0x08, 0x9c, 0x45, 0x7b, 0x61, 0xcd, 0x61, 0x5f, 0xc4, 0xc4, 0xc9, 0xf9, 0x41, 0x99, 0x1e, 0x54, 0x5d, 0xa4, 0xce, 0x53, 0x3e, 0x38, 0x0e, 0xa7, 0xff, 0x0c, 0x49, 0x7b, 0x8d, 0x48, 0x26, 0xba, 0x47, 0xcd, 0x61, 0xf0, 0x5b, 0xff, 0x4f, 0x77, 0x73, 0xf8, 0x91, 0xa3, 0x28, 0x3a, 0x6c, 0xb9, 0xbb, 0xce, 0x8f, 0x2e, 0x03, 0xff, 0x10, 0x04, 0x3a, 0x8e, 0x4d, 0xd4, 0x86, 0x34, 0xea, 0x8e, 0x54, 0xbf, 0x81, 0xe2, 0xd2, 0x65, 0x74, 0x9b, 0x39, 0x01, 0x83, 0xd0, 0xce, 0x40, 0x0b, 0x95, 0x10, 0xae, 0xc2, 0x6b, 0xbb, 0x3d, 0xb8, 0xce, 0x1d, 0xde, 0xbd, 0x78, 0xed, 0x38, 0xd9, 0xcf, 0x37, 0x74, 0xf6, 0x7a, 0xf1, 0x36, 0xeb, 0xd6, 0x76, 0x48, 0xc3, 0x9d, 0x0d, 0x4d, 0xe7, 0x5c, 0x1d, 0x29, 0x69, 0x5d, 0xdf, 0xaa, 0xa5, 0x33, 0x11, 0x5c, 0x27, 0xb3, 0x41, 0xf8, 0x14, 0x88, 0x5d, 0x10, 0x3d, 0x76, 0x9e, 0x9d, 0x31, 0x83, 0x29, 0x8e, 0xfc, 0x57, 0xd8, 0x42, 0x6d, 0xba, 0x28, 0x89, 0xeb, 0xf8, 0x78, 0xd5, 0xe0, 0x14, 0x60, 0xec, 0x96, 0x1d, 0x25, 0x34, 0x8c, 0xa8, 0x9c, 0xc5, 0x38, 0xe3, 0xa8, 0xde, 0x80, 0x2b, 0x95, 0x99, 0x1a, 0x5f, 0x99, 0x10, 0xb6, 0x17, 0x67, 0x9c, 0x5d, 0x1e, 0x4b, 0x91, 0x1a, 0x74, 0x2e, 0x73, 0x3f, 0xd5, 0x7c, 0xc1, 0x2a, 0xaf, 0xb4, 0xa0, 0x18, 0xdc, 0xbd, 0x46, 0x17, 0x8d, 0xfa, 0x68, 0x54, 0x29, 0x27, 0xa7, 0xf2, 0x3f, 0x46, 0xcd, 0x73, 0x40, 0xee, 0xb9, 0xe5, 0xc1, 0x1a, 0xb2, 0xcb, 0xd5, 0xe5, 0x91, 0x53, 0x28, 0xea, 0x4b, 0xd9, 0x73, 0x54, 0x6e, 0xe4, 0x72, 0x96, 0xfb, 0x74, 0x45, 0xc4, 0xfc, 0x63, 0x12, 0xf7, 0x9c, 0x16, 0x68, 0x95, 0x39, 0x85, 0xff, 0xbe, 0xfb, 0x3b, 0x20, 0x6c, 0x0c, 0x20, 0xd3, 0x61, 0xfa, 0x77, 0x5a, 0x0d, 0x50, 0x38, 0xa4, 0x2c, 0x8c, 0x31, 0xef, 0x61, 0x3b, 0x89, 0x42, 0xee, 0xc0, 0xe3, 0xad, 0x99, 0xd8, 0xdd, 0xac, 0x96, 0x09, 0xdd, 0x1e, 0x36, 0x08, 0x76, 0x60, 0x83, 0xf4, 0xa3, 0x38, 0xe9, 0x4a, 0x9d, 0x0a, 0x40, 0x2f, 0xf1, 0xb6, 0x1c, 0x7b, 0x6c, 0xcb, 0xf0, 0xba, 0x79, 0x52, 0xc8, 0x2d, 0xe3, 0x3e, 0xa1, 0x82, 0x93, 0x03, 0xd3, 0x08, 0x56, 0x02, 0x8d, 0x1d, 0xfe, 0x88, 0x27, 0xcd, 0x4d, 0x33, 0x4a, 0x59, 0xb7, 0x89, 0xed, 0xd7, 0x8a, 0x9d, 0x69, 0xb8, 0xf8, 0x92, 0xf2, 0x32, 0x62, 0x2e, 0x08, 0x59, 0x28, 0x3e, 0xff, 0x9e, 0x2a, 0xfd, 0x92, 0xa4, 0x7e, 0x62, 0x17, 0xee, 0xa2, 0xa3, 0x4c, 0x94, 0xef, 0x62, 0x28, 0x3d, 0x30, 0xa4, 0xcf, 0x13, 0x27, 0xee, 0x4c, 0xc7, 0x0b, 0x72, 0x42, 0x50, 0xc6, 0x6e, 0x43, 0x0a, 0xf6, 0x9f, 0x2e, 0x3d, 0x6f, 0xb9, 0x26, 0xb2, 0x56, 0x99, 0xc4, 0x75, 0x33, 0x60, 0x18, 0xf7, 0x79, 0x47, 0x06, 0xdc, 0x62, 0xe2, 0xe1, 0x45, 0xd9, 0xa6, 0xaf, 0x62, 0x3e, 0x32, 0xfe, 0xf8, 0xc1, 0xb1, 0x1e, 0xb7, 0xee, 0x5f, 0xe2, 0x52, 0xd6, 0x80, 0x36, 0x93, 0x7a, 0x78, 0x63, 0x09, 0xdb, 0x71, 0x1e, 0x68, 0x85, 0x0c, 0xed, 0x87, 0x63, 0x1f, 0x79, 0x5b, 0x6a, 0x00, 0xa1, 0x61, 0xa7, 0xee, 0x56, 0x75, 0xeb, 0x57, 0xaf, 0x1b, 0x12, 0xae, 0x24, 0xdc, 0xa7, 0x87, 0xc6, 0x9d, 0x52, 0x3f, 0x6c, 0x93, 0x95, 0xc5, 0x61, 0x59, 0x4c, 0x1a, 0x67, 0x10, 0x23, 0xbc, 0x5a, 0x91, 0xfe, 0xe6, 0x38, 0xe9, 0xe6, 0x4a, 0x60, 0xee, 0xff, 0x1a, 0x94, 0x14, 0xd3, 0x32, 0x30, 0x16, 0xbe, 0x4f, 0x37, 0xca, 0x33, 0xdc, 0x0c, 0x03, 0xde, 0x5b, 0x01, 0x56, 0x61, 0xd8, 0x5a, 0x03, 0xd1, 0x58, 0x28, 0x44, 0xd1, 0x47, 0xe9, 0xef, 0x36, 0x15, 0xab, 0x0b, 0x5f, 0x02, 0xb4, 0x5f, 0x4a, 0x0d, 0x85, 0x86, 0x20, 0xe3, 0x27, 0xf7, 0x71, 0x2e, 0xf7, 0xb1, 0x59, 0x2e, 0x03, 0xa6, 0xe3, 0x17, 0x7b, 0x9b, 0x39, 0x2c, 0x8e, 0x25, 0x50, 0x03, 0xf7, 0x1e, 0xc4, 0x7f, 0x9e, 0x15, 0x49, 0xb1, 0x5a, 0xf1, 0xcc, 0x01, 0xe0, 0x54, 0xe1, 0xc1, 0xd5, 0xf9, 0xa7, 0xee, 0x30, 0x6c, 0xbd, 0xf8, 0x7b, 0x60, 0x73, 0xe8, 0xed, 0x67, 0x4e, 0xa7, 0xde, 0x4d, 0x60, 0x0a, 0x38, 0x1f, 0xd6, 0x9f, 0xec, 0x33, 0x86, 0x35, 0xb9, 0xaf, 0x8b, 0xb1, 0x28, 0x91, 0x0f, 0xc4, 0x26, 0xcd, 0xde, 0xf2, 0xc6, 0x17, 0x71, 0x3e, 0x74, 0x66, 0x47, 0xa6, 0x5c, 0xad, 0x32, 0x40, 0xa7, 0x3a, 0xff, 0x27, 0x05, 0x92, 0x5b, 0x3a, 0x0f, 0xc3, 0xf4, 0x33, 0xfb, 0x04, 0xb0, 0x0a, 0xde, 0x06, 0x82, 0x01, 0xff, 0x2e, 0x82, 0x04, 0xe0, 0xc8, 0x86, 0xe3, 0xaf, 0x49, 0x98, 0x50, 0x73, 0x8a, 0x8b, 0x98, 0xff, 0x0d, 0x10, 0x22, 0x14, 0xec, 0x7b, 0xb4, 0xc5, 0xdd, 0x85, 0x34, 0x84, 0x19, 0x50, 0xfb, 0x7f, 0x84, 0xc7, 0x92, 0x42, 0x94, 0x2f, 0x18, 0x43, 0x3e, 0xa5, 0xba, 0xd4, 0xbb, 0xe0, 0x3e, 0x01, 0xbb, 0x76, 0xe5, 0xd6, 0x45, 0xde, 0xdf, 0x43, 0x51, 0xee, 0x8f, 0x04, 0xf6, 0x3c, 0x41, 0x43, 0x2b, 0x5a, 0xb8, 0x6e, 0x49, 0xe7, 0xff, 0x5d, 0x73, 0x83, 0x57, 0x0f, 0x9f, 0x82, 0xdc, 0x03, 0x22, 0x33, 0x65, 0x9a, 0xdb, 0x03, 0xfa, 0x51, 0x69, 0xc0, 0x0a, 0x20, 0x10, 0xc8, 0xd0, 0xc4, 0x61, 0x48, 0xbd, 0x87, 0xbf, 0x2a, 0x19, 0x34, 0x77, 0x45, 0x0f, 0xe6, 0xc5, 0x8f, 0x33, 0xf3, 0x64, 0x82, 0xab, 0xb0, 0x61, 0xc0, 0x7d, 0xa8, 0x23, 0x7f, 0xb4, 0xdf, 0xd0, 0x33, 0x7f, 0x45, 0x8e, 0x5d, 0xbc, 0xcd, 0xdf, 0xac, 0x60, 0xb2, 0xec, 0x17, 0x3b, 0xcf, 0x77, 0x6d, 0xa2, 0xfd, 0x05, 0xe2, 0x98, 0xef, 0xe4, 0x6d, 0x92, 0xa8, 0x93, 0x38, 0x07, 0xa6, 0x76, 0x83, 0x82, 0xcf, 0x73, 0x18, 0xce, 0xd7, 0x68, 0xf4, 0x6d, 0xe6, 0x84, 0x4f, 0xbc, 0x59, 0xd2, 0x5b, 0xd2, 0x1c, 0xcc, 0x60, 0xad, 0x68, 0x79, 0x70, 0x74, 0x59, 0x06, 0xbf, 0xac, 0x43, 0x99, 0x62, 0xec, 0x76, 0x97, 0x11, 0x9a, 0x85, 0xd4, 0xed, 0xf6, 0x20, 0x2e, 0x3c, 0x92, 0x5d, 0x62, 0x22, 0x44, 0xbd, 0xb2, 0x3b, 0x64, 0x82, 0x63, 0xe1, 0x39, 0xc6, 0x69, 0x0b, 0x64, 0xc9, 0x70, 0xcb, 0x02, 0x89, 0xe5, 0x6d, 0xb1, 0x2d, 0x51, 0x2d, 0xdd, 0xe4, 0x49, 0x52, 0xbd, 0x9c, 0xa5, 0xec, 0xa2, 0xa4, 0x72, 0x39, 0x8e, 0xe2, 0xbf, 0xbc, 0x47, 0xbe, 0x8f, 0x86, 0x8a, 0xad, 0xe0, 0x46, 0x57, 0xb7, 0x80, 0xad, 0x8e, 0x44, 0x32, 0x02, 0x7f, 0x80, 0x70, 0xdd, 0xfe, 0x71, 0xd4, 0x27, 0x3e, 0x87, 0x46, 0x20, 0x44, 0x61, 0xc0, 0x51, 0x19, 0x54, 0xb9, 0x60, 0x56, 0x30, 0xe3, 0xfa, 0x03, 0x38, 0xd4, 0x07, 0xc3, 0x22, 0xf3, 0x58, 0x8e, 0x1d, 0x21, 0xda, 0x4f, 0x98, 0xf5, 0x79, 0xe3, 0xd7, 0x45, 0x48, 0x11, 0x8b, 0x34, 0xce, 0xcc, 0xea, 0xfc, 0x24, 0xfb, 0x11, 0xf4, 0xf5, 0xfa, 0x05, 0x24, 0xc7, 0x5d, 0x7e, 0x3a, 0x65, 0x45, 0xfa, 0x90, 0xe7, 0xbe, 0x02, 0x95, 0xbf, 0xcc, 0xe1, 0xd9, 0x87, 0x42, 0xff, 0x50, 0x87, 0x5f, 0x70, 0x14, 0xce, 0xbe, 0xb7, 0x77, 0xfb, 0xc3, 0xc4, 0x89, 0x4b, 0xda, 0x3b, 0x75, 0x37, 0xb6, 0x94, 0x14, 0xd7, 0x1f, 0xe4, 0xb1, 0xc0, 0x45, 0xb0, 0xcf, 0x79, 0x2f, 0x23, 0x7d, 0x81, 0xf9, 0x4f, 0x36, 0xe0, 0x46, 0xf0, 0x4e, 0xfb, 0xfa, 0x95, 0x38, 0xfe, 0xf7, 0xcf, 0x3f, 0x92, 0xc0, 0xaf, 0x56, 0x14, 0x31, 0xe2, 0x2a, 0x71, 0x62, 0x8e, 0x34, 0xc6, 0x08, 0x0f, 0xa4, 0x3a, 0x03, 0x1a, 0xfd, 0x42, 0xa8, 0xb9, 0x51, 0xe6, 0x8f, 0x35, 0x08, 0x26, 0x3d, 0xf5, 0x63, 0xf2, 0x18, 0x38, 0xa9, 0x21, 0x6c, 0xf0, 0x39, 0x22, 0x8d, 0x3e, 0xa9, 0xd4, 0x87, 0x66, 0xf6, 0xb7, 0x72, 0x6f, 0xab, 0xc8, 0x0a, 0x2a, 0x6c, 0x79, 0x5b, 0x02, 0x8a, 0x2c, 0xb5, 0x36, 0x77, 0x09, 0xb7, 0x61, 0xca, 0x89, 0x58, 0xc8, 0xbd, 0xa2, 0x21, 0x2b, 0xfe, 0x16, 0x0c, 0x24, 0x6d, 0xe1, 0x70, 0x78, 0x6a, 0xd5, 0x62, 0x7a, 0xfe, 0x5f, 0x63, 0x55, 0xdf, 0xd4, 0xd1, 0x32, 0x46, 0x83, 0x9c, 0xda, 0xb4, 0x6a, 0x71, 0xb8, 0xc6, 0xe6, 0xce, 0x00, 0xbd, 0x1a, 0x00, 0x77, 0x8a, 0x3c, 0x58, 0xcb, 0x17, 0x91, 0xe9, 0x08, 0x48, 0x11, 0x5e, 0xe3, 0x2a, 0xf7, 0xfb, 0x87, 0xd9, 0x8e, 0xe8, 0xf0, 0x0c, 0x13, 0xdb, 0x16, 0xb4, 0x6b, 0xae, 0xb2, 0xec, 0x28, 0x5e, 0x79, 0x8c, 0x8c, 0xbf, 0x3b, 0xe0, 0x75, 0x9c, 0xa7, 0x71, 0x83, 0x46, 0xd8, 0xff, 0x2d, 0x24, 0x10, 0xb8, 0x8a, 0x1e, 0x95, 0x3a, 0xf0, 0xdc, 0xe3, 0xf8, 0x0c, 0xa7, 0x83, 0x41, 0xed, 0x4e, 0xe3, 0xf5, 0x3e, 0x07, 0xb3, 0xbd, 0x8a, 0xdb, 0x73, 0x41, 0xf3, 0xb4, 0xf5, 0xfb, 0x18, 0x43, 0x77, 0x80, 0x30, 0x0b, 0x51, 0x0b, 0xe2, 0xf1, 0x0d, 0x10, 0x48, 0xab, 0x7d, 0x36, 0x0f, 0x98, 0xa2, 0x42, 0xef, 0xce, 0x0c, 0x8d, 0xe8, 0xa7, 0xfb, 0x38, 0xb4, 0x84, 0x6d, 0x41, 0xfe, 0xb1, 0x8a, 0x90, 0xf1, 0x48, 0xf8, 0x48, 0x46, 0x9a, 0x55, 0x37, 0xec, 0x3d, 0xea, 0x76, 0x43, 0xaf, 0x22, 0xbf, 0x5b, 0x2b, 0x7b, 0x1a, 0x7d, 0xce, 0xff, 0x89, 0xf7, 0xbc, 0x6f, 0x86, 0x4d, 0xae, 0x6c, 0x15, 0x5b, 0x03, 0xd5, 0xfc, 0x9c, 0x85, 0x0b, 0xd0, 0x28, 0xb4, 0xfc, 0x3c, 0xc0, 0x96, 0xaf, 0x4d, 0xb3, 0x7c, 0xea, 0xa7, 0x72, 0x54, 0x73, 0x42, 0x41, 0xaa, 0x6c, 0x24, 0x1f, 0xc0, 0x0d, 0xec, 0xa9, 0xb0, 0x3e, 0x9c, 0x59, 0x3b, 0x59, 0x96, 0x9b, 0x85, 0x05, 0x6c, 0xaf, 0xfe, 0xa4, 0x38, 0x2d, 0xc9, 0xad, 0x65, 0x81, 0x49, 0x40, 0xe9, 0xd0, 0x40, 0x0f, 0x15, 0xcb, 0x68, 0xcc, 0x88, 0x8f, 0xaf, 0x6b, 0x30, 0x2b, 0x29, 0x37, 0xcf, 0xc4, 0x4e, 0x42, 0xfb, 0xb2, 0x61, 0x91, 0x6e, 0xc3, 0x2b, 0xd5, 0x6d, 0x8d, 0x7e, 0x78, 0x3f, 0x81, 0xd4, 0xaf, 0x89, 0xaf, 0x2f, 0xe6, 0x7a, 0x31, 0x49, 0x99, 0xe5, 0x7e, 0x4c, 0x1a, 0x0e, 0xa2, 0x1a, 0x3e, 0xca, 0xec, 0x4d, 0xf7, 0x64, 0xd4, 0x45, 0xe4, 0x2f, 0xd5, 0xf4, 0xe1, 0x29, 0xe7, 0x74, 0x5d, 0x54, 0xb7, 0x3e, 0x33, 0x27, 0x79, 0xeb, 0x9e, 0x93, 0xe0, 0x7e, 0xfe, 0x9c, 0x84, 0xbf, 0x9b, 0x6a, 0xfc, 0xa4, 0xdd, 0x63, 0x84, 0xea, 0x99, 0x3f, 0x17, 0xd8, 0xb0, 0xf6, 0xdb, 0x16, 0x32, 0x57, 0xf0, 0x7d, 0xcc, 0x03, 0xd2, 0x07, 0xe1, 0x60, 0x01, 0xf1, 0xea, 0xe1, 0xd8, 0x0a, 0xb9, 0x12, 0xb4, 0xdc, 0xf5, 0x80, 0x0b, 0x89, 0x76, 0x5d, 0x83, 0xd1, 0xcb, 0xe8, 0x9c, 0xd5, 0xf3, 0x1e, 0x5c, 0x7e, 0x3c, 0xb0, 0xd2, 0xe3, 0x49, 0xb9, 0x14, 0xa5, 0x31, 0xb6, 0x14, 0x68, 0xdf, 0x75, 0x74, 0x9e, 0xd3, 0x49, 0xc6, 0x2e, 0x45, 0x96, 0xb6, 0xae, 0xdb, 0x36, 0x27, 0xdf, 0xbb, 0x4e, 0x3f, 0x14, 0xd1, 0x0e, 0x25, 0xd1, 0x6b, 0x07, 0x93, 0xc3, 0xc3, 0xf7, 0xe7, 0x7a, 0x6c, 0x59, 0xdb, 0xcd, 0xe6, 0xba, 0x01, 0x08, 0xc4, 0xc2, 0xf4, 0xce, 0xb0, 0x49, 0x37, 0xa3, 0xd5, 0x4e, 0xff, 0xe8, 0x51, 0x94, 0x6a, 0x32, 0x8d, 0xa0, 0x86, 0x1b, 0xdf, 0x0f, 0x57, 0x42, 0x64, 0xd2, 0xd7, 0x2b, 0x71, 0x03, 0xda, 0xb6, 0xe8, 0xcb, 0xc0, 0xe1, 0x8b, 0xa3, 0xd5, 0x31, 0x37, 0x72, 0x69, 0xec, 0xd7, 0xa5, 0xfb, 0x96, 0xab, 0x11, 0x7c, 0x8f, 0x9e, 0xce, 0x6d, 0x96, 0x2b, 0xe5, 0xec, 0x23, 0xaa, 0x0e, 0x51, 0x0a, 0x1b, 0xf9, 0xdc, 0x86, 0x80, 0xff, 0x47, 0x0c, 0x23, 0xfa, 0x29, 0x48, 0x8f, 0x22, 0xcb, 0x00, 0x15, 0xa9, 0x2a, 0xd2, 0x1f, 0x17, 0x56, 0x30, 0x7d, 0xa4, 0xf8, 0x4d, 0xec, 0x19, 0xf8, 0xe9, 0x48, 0xc4, 0x40, 0x14, 0x68, 0x61, 0xf9, 0x4b, 0xa8, 0x44, 0x94, 0x66, 0x37, 0xd9, 0xf2, 0x3f, 0xdb, 0x66, 0x2d, 0x5a, 0x70, 0x37, 0x60, 0xe6, 0x9b, 0x09, 0x40, 0x60, 0x11, 0x14, 0x40, 0x81, 0xb7, 0x2e, 0x29, 0x02, 0xab, 0x8d, 0x4e, 0x5b, 0xbe, 0x55, 0x1a, 0xfe, 0x6f, 0xdd, 0xb4, 0x0b, 0x98, 0xd4, 0x41, 0xa6, 0xb0, 0x50, 0x6b, 0x3a, 0x59, 0xb4, 0xcf, 0x7b, 0x14, 0x26, 0x1e, 0x0e, 0x53, 0xd7, 0x4b, 0x29, 0x81, 0x37, 0x68, 0xbb, 0x9d, 0x48, 0x8e, 0xa7, 0xf6, 0x7f, 0x26, 0x99, 0x3a, 0x93, 0xbe, 0x3b, 0x5f, 0xb7, 0xbc, 0xf6, 0x22, 0x22, 0x0c, 0x05, 0xdb, 0x6e, 0x09, 0x0e, 0x7d, 0x4b, 0x8c, 0x2e, 0xff, 0xcd, 0x4d, 0x5b, 0xfd, 0xee, 0x6a, 0xc6, 0x37, 0xea, 0xf7, 0xc0, 0x8b, 0x59, 0xed, 0xc1, 0xa4, 0x5a, 0x7f, 0xc3, 0x81, 0x29, 0x49, 0x7b, 0xf8, 0x35, 0x04, 0x54, 0x11, 0x3b, 0x19, 0x18, 0x76, 0x7f, 0xce, 0x06, 0xc2, 0x95, 0xe0, 0x2e, 0xa6, 0xe4, 0xc2, 0x57, 0xfc, 0x97, 0x6f, 0xb6, 0x87, 0xcf, 0x90, 0x25, 0xef, 0xb8, 0x1f, 0xc6, 0xdc, 0x8d, 0xcd, 0x21, 0x33, 0xa7, 0x7e, 0xa3, 0x9a, 0x43, 0x10, 0x38, 0xc5, 0x90, 0x28, 0xd6, 0x3e, 0x7a, 0x14, 0xce, 0x5e, 0x02, 0xd2, 0x7f, 0xe6, 0x13, 0x2f, 0xfb, 0x32, 0x8c, 0xd1, 0xec, 0xeb, 0xd9, 0x03, 0x22, 0x31, 0x8c, 0xa6, 0xcc, 0xc3, 0x12, 0x87, 0x12, 0x24, 0x6b, 0x73, 0x79, 0x15, 0xc7, 0x93, 0x04, 0xd5, 0x50, 0x37, 0x8b, 0xa9, 0xdf, 0xcc, 0x21, 0xb4, 0xba, 0xca, 0xd1, 0xde, 0x86, 0x4e, 0x1d, 0x20, 0xee, 0xa2, 0x1b, 0x5a, 0xc5, 0x2a, 0x7c, 0x63, 0xd2, 0xda, 0xba, 0xe3, 0xa7, 0xd5, 0x37, 0x5b, 0xef, 0x73, 0xc8, 0x18, 0x0d, 0x17, 0xef, 0x53, 0xbc, 0xcd, 0x32, 0xfd, 0xc1, 0xbc, 0xa7, 0xd6, 0xa8, 0xdc, 0xb8, 0x98, 0xa8, 0xf7, 0x6e, 0x56, 0x86, 0x2d, 0x26, 0x42, 0x46, 0x25, 0x16, 0x43, 0x36, 0xbf, 0xfc, 0x78, 0xdc, 0x7b, 0x35, 0xc9, 0xe2, 0x48, 0x35, 0xd8, 0x52, 0xc9, 0x75, 0xec, 0x4f, 0xac, 0x93, 0xb9, 0x1d, 0x6c, 0xde, 0xa1, 0x21, 0xda, 0x0f, 0x3c, 0x49, 0x78, 0x80, 0xec, 0xa1, 0xa3, 0x41, 0x22, 0xe7, 0x8a, 0xce, 0xbb, 0xb6, 0xef, 0x62, 0x82, 0xd9, 0x96, 0x66, 0xe1, 0x6f, 0xa0, 0x07, 0xc0, 0x1c, 0x61, 0xd4, 0x53, 0x23, 0x09, 0xd4, 0x34, 0xbe, 0x3a, 0xa9, 0x5f, 0x52, 0xa2, 0x7d, 0xbd, 0xc2, 0xcb, 0x71, 0xaa, 0xa6, 0xca, 0x1a, 0x9e, 0x74, 0xf4, 0x84, 0x02, 0xfc, 0x0f, 0xb0, 0x4f, 0x9d, 0x3c, 0x35, 0x82, 0x04, 0xe0, 0x88, 0x24, 0x93, 0x29, 0x96, 0x7a, 0xb8, 0xb7, 0xe9, 0xec, 0x87, 0xbe, 0x75, 0x61, 0x56, 0x80, 0xdd, 0x54, 0x80, 0xde, 0x40, 0xe2, 0x63, 0x62, 0x4b, 0x5a, 0x63, 0x07, 0x77, 0xba, 0x0b, 0x90, 0x77, 0xa8, 0xc6, 0x24, 0x8d, 0xd0, 0x82, 0xcd, 0xec, 0x11, 0xf8, 0xba, 0xd6, 0x6c, 0xf1, 0x1a, 0x90, 0xa7, 0xfd, 0xff, 0x61, 0xcd, 0x48, 0x93, 0x83, 0xec, 0x2e, 0x52, 0x3f, 0xcb, 0x0a, 0x06, 0xfe, 0x46, 0x5f, 0xe5, 0x88, 0xbb, 0xc7, 0x27, 0x16, 0xef, 0x92, 0xb4, 0x1e, 0x66, 0x67, 0x42, 0xe1, 0xd3, 0x15, 0xf1, 0x58, 0x8d, 0x8e, 0x42, 0xdb, 0x35, 0xea, 0xcd, 0x40, 0x59, 0x3a, 0xb3, 0x9a, 0xc9, 0x1e, 0x4f, 0x59, 0x20, 0x03, 0xdf, 0xed, 0x3e, 0xd7, 0xbb, 0x0f, 0x0b, 0xbb, 0xf0, 0xa2, 0x9f, 0xad, 0x8e, 0x64, 0x1c, 0x44, 0x9f, 0x13, 0x1e, 0xa7, 0xd3, 0x8c, 0x7a, 0xd6, 0xfd, 0x9f, 0xa2, 0xf0, 0x61, 0xfe, 0x29, 0xd8, 0x84, 0x56, 0x96, 0xda, 0xa9, 0x82, 0x15, 0xf6, 0x79, 0xf8, 0xe6, 0xd5, 0xdc, 0xe0, 0xfd, 0x77, 0x4b, 0x1a, 0x3c, 0x7e, 0x61, 0x3e, 0x1f, 0xf3, 0x05, 0xfc, 0xac, 0x34, 0x2b, 0xf0, 0x95, 0x47, 0x31, 0x63, 0xe9, 0x9f, 0x4b, 0x9d, 0xc2, 0x44, 0xd4, 0xc3, 0xbb, 0x65, 0xc3, 0x9f, 0xcf, 0x3e, 0xe3, 0x99, 0x89, 0x33, 0x61, 0x46, 0xdc, 0xb7, 0xba, 0x76, ]) export const testVectors = [ { testName: 'vector 1', whichSha: 'sha256', ikm: tv0Ikm, salt: tv0Salt, info: tv0Info, okmDesired: tv0OkmDesired, okmLen: 42, }, { testName: 'vector 2', whichSha: 'sha256', ikm: tv1Ikm, salt: tv1Salt, info: tv1Info, okmDesired: tv1OkmDesired, okmLen: 82, }, { testName: 'vector 3', whichSha: 'sha256', ikm: tv2Ikm, salt: undefined, info: undefined, okmDesired: tv2OkmDesired, okmLen: 42, }, { testName: 'vector 4', whichSha: 'sha384', ikm: tv3Ikm, salt: tv3Salt, info: tv3Info, okmDesired: tv3OkmDesired, okmLen: 42, }, { testName: 'vector 5', whichSha: 'sha384', ikm: tv4Ikm, salt: tv4Salt, info: tv4Info, okmDesired: tv4OkmDesired, okmLen: 82, }, { testName: 'vector 6', whichSha: 'sha384', ikm: tv5Ikm, salt: undefined, info: undefined, okmDesired: tv5OkmDesired, okmLen: 42, }, /* Test vector #6 is testing types in C which is not the same as JavaScript. */ // { .whichSha = AWS_CRYPTOSDK_NOSHA, .ikm = tv6Ikm, .ikm_len = 10 }, { testName: 'vector 8', whichSha: 'sha256', ikm: tv7Ikm, salt: tv7Salt, info: tv7Info, okmDesired: tv7OkmDesired, okmLen: 8129, }, ]
the_stack
import * as R from "ramda"; import { Client, Model, Rbac, Api } from "@core/types"; import { parseMultiFormat } from "@core/lib/parse"; import { getEnvironmentName, getEnvironmentsByEnvParentId, getSubEnvironmentsByParentEnvironmentId, graphTypes, } from "@core/lib/graph"; import chalk from "chalk"; import Table from "cli-table3"; import { envsNeedFetch, changesetsNeedFetch, getEnvWithMeta, getPendingUpdateDetails, getEnvWithMetaCellDisplay, } from "@core/lib/client"; import { spinnerWithText, stopSpinner } from "./spinner"; import { dispatch, initCore } from "./core"; import { Graph } from "@core/types/client/graph"; import { findCliUser, findUser } from "./args"; import { exit } from "./process"; import { getPrompt } from "./console_io"; import { argIsEnvironment, tryApplyDetectedAppOverride, } from "../app_detection"; import { BaseArgs } from "../types"; export const findEnvironment = ( graph: Graph.UserGraph, envParentId: string, environmentArg: string ): Model.Environment | undefined => { const environments = getEnvironmentsByEnvParentId(graph)[envParentId] ?? []; return environments.find((env) => { const envName = getEnvironmentName(graph, env.id) as string; const role = graph[env.environmentRoleId] as Rbac.EnvironmentRole; return ( envName.toLowerCase() === environmentArg.toLowerCase() || env.id === environmentArg || role.id === environmentArg ); }); }; export const getEnvironmentTree = ( graph: Client.Graph.UserGraph, envParentId: string, parentEnvironmentId?: string, currentBranchId?: string ) => { let baseEnvironments = ( getEnvironmentsByEnvParentId(graph)[envParentId] ?? [] ).filter(R.complement(R.prop("isSub"))); if (parentEnvironmentId) { baseEnvironments = [ baseEnvironments.find(R.propEq("id", parentEnvironmentId)), ].filter(Boolean) as Model.Environment[]; } return R.flatten( baseEnvironments.map((environment) => { let name = getEnvironmentName(graph, environment.id); const subEnvironments = getSubEnvironmentsByParentEnvironmentId(graph)[environment.id] ?? []; if (environment.id == currentBranchId) { name = chalk.green(chalk.bold(name + " (current branch)")); } return [ name, ...subEnvironments.map((subEnv) => { const s = "├──" + (subEnv as { subName: string }).subName; return subEnv.id == currentBranchId ? chalk.green(chalk.bold(s + " (current branch)")) : s; }), ]; }) ).join("\n"); }, getEnvironmentTreeJson = ( graph: Client.Graph.UserGraph, envParentId: string, parentEnvironmentId?: string, currentBranchId?: string ) => { const res: { id: string; name: string; branches: { id: string; name: string; }[]; currentBranch?: { id: string; name: string; }; }[] = []; let baseEnvironments = ( getEnvironmentsByEnvParentId(graph)[envParentId] ?? [] ).filter(R.complement(R.prop("isSub"))); if (parentEnvironmentId) { baseEnvironments = [ baseEnvironments.find(R.propEq("id", parentEnvironmentId)), ].filter(Boolean) as Model.Environment[]; } for (let environment of baseEnvironments) { const name = getEnvironmentName(graph, environment.id), subEnvironments = getSubEnvironmentsByParentEnvironmentId(graph)[environment.id] ?? []; const branches = subEnvironments.map((sub) => ({ id: sub.id, name: sub.subName, })); res.push({ id: environment.id, name, branches, currentBranch: branches.find(({ id }) => id == currentBranchId), }); } return res; }, parseKeyValuePairs = R.pipe( R.filter(Boolean) as (v: string[]) => string[], R.map(R.curry(parseMultiFormat)(R.__, ["env", "json"])) as ( v: string[] ) => Client.Env.RawEnv[], R.mergeAll ), pushDiffRows = ( state: Client.State, table: Table.Table, diffs: Client.Env.DiffsByKey ) => { const keys = R.sortBy(R.identity, Object.keys(diffs)); for (let k of keys) { table.push([ k, { content: "🚫 " + chalk.red( getEnvWithMetaCellDisplay(state.graph, diffs[k].fromValue) ), hAlign: "center", }, { content: chalk.bold(chalk.green("→ ")) + chalk.green( getEnvWithMetaCellDisplay(state.graph, diffs[k].toValue) ), hAlign: "center", }, ]); } }, getPending = ( state: Client.State, opts: { envParentIds?: Set<string>; environmentIds?: Set<string>; entryKeys?: Set<string>; afterReset?: boolean; } = {} ): [string, string, Record<string, Client.Env.DiffsByKey>] => { const { filteredUpdates, apps, appEnvironments, appPaths, blocks, blockPaths, blockEnvironments, diffsByEnvironmentId, pendingLocalIds, } = getPendingUpdateDetails(state, opts); if (filteredUpdates.length == 0) { return ["", "", {}]; } let summary = opts.afterReset ? "Updates " + chalk.bold("still pending") + " for" : "Updates pending for"; if (apps.size) { summary += chalk.bold(` ${apps.size} app${apps.size > 1 ? "s" : ""}`) + ` (${appEnvironments.size} environment${ appEnvironments.size > 1 ? "s" : "" }, ${appPaths.size} variable${appPaths.size > 1 ? "s" : ""})`; if (blocks.size) { summary += " and "; } } if (blocks.size) { summary += chalk.bold(`${blocks.size} block${blocks.size > 1 ? "s" : ""}`) + ` (${blockEnvironments.size} environment${ blockEnvironments.size > 1 ? "s" : "" }, ${blockPaths.size} variable${blockPaths.size > 1 ? "s" : ""})`; } summary += ":"; const diffTables: Table.Table[] = []; for (let envParentId of [...Array.from(apps), ...Array.from(blocks)]) { const envParent = state.graph[envParentId] as Model.EnvParent, table = new Table({ colWidths: [24, 32, 32], }); table.push([ { content: chalk.bold(envParent.name), colSpan: 3, }, ]); const baseEnvironments = ( getEnvironmentsByEnvParentId(state.graph)[envParentId] ?? [] ).filter(R.complement(R.prop("isSub"))); for (let environment of baseEnvironments) { const diffs = diffsByEnvironmentId[environment.id], name = getEnvironmentName(state.graph, environment.id).toLowerCase(); if (diffs) { table.push([ { content: chalk.bold(chalk.cyan(name)), colSpan: 3, }, ]); pushDiffRows(state, table, diffs); } const subEnvironments = getSubEnvironmentsByParentEnvironmentId(state.graph)[ environment.id ] ?? []; for (let subEnv of subEnvironments) { if (!subEnv.isSub) continue; const diffs = diffsByEnvironmentId[subEnv.id]; if (diffs) { table.push([ { content: chalk.bold( chalk.cyan(name) + " → " + chalk.cyan(subEnv.subName.toLowerCase()) ), colSpan: 3, }, ]); pushDiffRows(state, table, diffs); } } } for (let envId of pendingLocalIds) { const diffs = diffsByEnvironmentId[envId]; const name = getEnvironmentName(state.graph, envId); if (diffs) { table.push([ { content: `${chalk.bold(chalk.cyan(name))}`, colSpan: 3, }, ]); pushDiffRows(state, table, diffs); } } diffTables.push(table); } return [ summary, diffTables.map((t) => t.toString()).join("\n\n"), diffsByEnvironmentId || {}, ]; }, getShowEnvsTable = ( state: Client.State, envParentId: string, environmentIds: string[], entryKeys?: Set<string> ): [string, Record<string, Client.Env.EnvWithMeta>] => { const table = new Table({ colWidths: // Long keys/values will be truncated, unless passing a single environment. environmentIds.length === 1 ? [] : [30, ...R.repeat(34, environmentIds.length)], }); const envParent = state.graph[envParentId] as Model.EnvParent; const titleRow: Table.HorizontalTableRow = [chalk.bold(envParent.name)]; const envWithMetaByEnvironmentId: Record<string, Client.Env.EnvWithMeta> = {}, allKeys = new Set<string>(); for (let environmentId of environmentIds) { // TODO: better UX is warranted for `show` of branches, but would require refactors lower let maybeParentName = ""; let thisEnvName: string; const isOverrideEnv = environmentId.includes("|"); if (isOverrideEnv) { const overridenUserId = environmentId.split("|")[1]; const orgUser = findUser(state.graph, overridenUserId) || findCliUser(state.graph, overridenUserId); thisEnvName = orgUser ? orgUser.type === "cliUser" ? orgUser.name : orgUser.firstName + " " + orgUser.lastName : overridenUserId; } else { // override envs aren't quite normal environments thisEnvName = getEnvironmentName( state.graph, environmentId ).toLowerCase(); const thisEnv = findEnvironment( state.graph, envParentId, environmentId ); maybeParentName = thisEnv?.isSub ? getEnvironmentName( state.graph, thisEnv.parentEnvironmentId ).toLowerCase() + " > " : ""; } titleRow.push({ content: maybeParentName + chalk.bold(chalk.cyan(thisEnvName)), hAlign: "center", }); const envWithMeta = getEnvWithMeta(state, { envParentId, environmentId, }); envWithMetaByEnvironmentId[environmentId] = envWithMeta; for (let k in envWithMeta.variables) { if (entryKeys && !entryKeys.has(k)) { continue; } allKeys.add(k); } } table.push(titleRow); for (let k of R.sortBy(R.identity, Array.from(allKeys))) { table.push([ k, ...environmentIds.map((id) => ({ content: getEnvWithMetaCellDisplay( state.graph, envWithMetaByEnvironmentId[id].variables[k] ), hAlign: "center", })), ] as Table.Cell[]); } if (!allKeys.size) { table.push([ { colSpan: environmentIds.length + 1, content: "No config yet" }, ]); } return [table.toString(), envWithMetaByEnvironmentId]; }, getShowEnvs = ( state: Client.State, envParentId: string, environmentIds: string[], entryKeys?: Set<string> ): [string, Record<string, Client.Env.EnvWithMeta>] => { const outputs: string[] = []; let envs: Record<string, Client.Env.EnvWithMeta> = {}; // 3 columns let batchEnvironmentIds: string[] = []; for (let i = 0; i < environmentIds.length; i += 3) { batchEnvironmentIds = environmentIds.slice(i, i + 3); const [o, e] = getShowEnvsTable( state, envParentId, batchEnvironmentIds, entryKeys ); outputs.push(o); envs = { ...envs, ...e }; } return [outputs.join("\n\n"), envs]; }, selectPendingEnvironments = async (params: { state: Client.State; auth: Client.ClientUserAuth | Client.ClientCliAuth; argv: BaseArgs; envParentArg?: string; environmentArg?: string; overrideByUser?: string; entryKeys?: string[]; }): Promise<{ state: Client.State; auth: Client.ClientUserAuth | Client.ClientCliAuth; envParent: Model.EnvParent | undefined; user: Model.OrgUser | Model.CliUser | undefined; environment: Model.Environment | undefined; pendingOpts: Parameters<typeof getPending>[1] | object | undefined; pendingEnvironmentIds: string[] | undefined; }> => { const { argv, envParentArg, overrideByUser, entryKeys } = params; let { state, auth, environmentArg } = params; const prompt = getPrompt(); let envParent: Model.EnvParent | undefined; let environment: Model.Environment | undefined; let apps: Model.App[] = []; let blocks: Model.Block[] = []; let envParents: Model.EnvParent[] = []; let envParentsByName: Record<string, Model.EnvParent> = {}; let envParentsById: Record<string, Model.EnvParent> = {}; const setupSharedVars = () => { ({ apps, blocks } = graphTypes(state.graph)); envParents = [...apps, ...blocks]; envParentsByName = R.indexBy( R.pipe(R.prop("name"), R.toLower), envParents ); envParentsById = R.indexBy(R.pipe(R.prop("id"), R.toLower), envParents); }; setupSharedVars(); if (envParentArg) { envParent = envParentsByName[envParentArg.toLowerCase()] ?? envParentsById[envParentArg.toLowerCase()]; } // detection from ENVKEY if (!envParent) { if (tryApplyDetectedAppOverride(auth.userId, argv)) { ({ auth, state } = await initCore(argv, true)); setupSharedVars(); const appId = argv["detectedApp"]?.appId?.toLowerCase(); if (appId) { const envFirst = argIsEnvironment(state.graph, appId, envParentArg); const otherArgsValid = !envParentArg || envFirst; if (otherArgsValid) { envParent = state.graph[appId] as Model.App | undefined; if (envParent) { console.log("Detected app", chalk.bold(envParent.name), "\n"); if (envFirst && !environmentArg) { // shuffle right environmentArg = envParentArg; } } } } } } if (!envParent) { // determine if there's a default app // if app/block not found via arg or default, prompt for it const { parentName } = await prompt<{ parentName: string; }>({ type: "autocomplete", name: "parentName", message: "Choose an " + chalk.bold("app") + " or " + chalk.bold("block") + " (type to search):", initial: 0, required: true, choices: R.sort( R.ascend(R.prop("message")), envParents.map((envParent) => ({ name: envParent.name, message: chalk.bold(envParent.name), })) ), }); envParent = envParentsByName[parentName.toLowerCase()]; } if (!envParent) { return exit(1, chalk.red.bold("Invalid app-or-block.")); } if (overrideByUser) { const user = findUser(state.graph, overrideByUser) || findCliUser(state.graph, overrideByUser); if (!user) { return exit(1, chalk.red.bold("User not found.")); } const userCompositeOverrideId = [envParent.id, user.id].join("|"); return { auth, state, environment: undefined, pendingOpts: { envParentIds: new Set([envParent.id]), environmentIds: new Set([userCompositeOverrideId]), }, pendingEnvironmentIds: [userCompositeOverrideId], envParent, user, }; } const pendingEnvsChoices = ( getEnvironmentsByEnvParentId(state.graph)[envParent.id] ?? [] ) .filter((ae) => { const [, pending] = getPending(state, { envParentIds: new Set([envParent!.id]), environmentIds: new Set([ae.id]), }); return Boolean(pending); }) .map((ae) => { return { name: ae.id, message: chalk.bold( (state.graph[ae.environmentRoleId] as Rbac.EnvironmentRole).name + (ae.isSub ? ` > ${ae.subName}` : "") ), }; }); if (!pendingEnvsChoices.length) { let message = chalk.red( `No environments for ${chalk.bold( envParent.name )} have pending updates.` ); const [, allPending] = getPending(state); if (allPending) { message += "Other environments do have pending updates:\n" + allPending; } return exit(1, message); } const environmentName = (environmentArg ?? ( await prompt<{ environment: string }>({ type: "autocomplete", name: "environment", message: "Select environment:", initial: 0, required: true, choices: pendingEnvsChoices, }) ).environment) as string; environment = findEnvironment(state.graph, envParent.id, environmentName); if (!environment) { return exit( 1, chalk.red( `Environment ${chalk.bold( environmentName )} does not exist, or you don't have access.` ) ); } return { state, auth, user: undefined, pendingOpts: { envParentIds: new Set([envParent.id]), environmentIds: new Set([environment.id]), entryKeys: entryKeys && entryKeys.length > 0 ? new Set(entryKeys) : undefined, }, pendingEnvironmentIds: [environment.id], envParent, environment, }; }, fetchEnvsIfNeeded = async (state: Client.State, envParentIds: string[]) => { let needsFetch = false; const byEnvParentId: Api.Net.FetchEnvsParams["byEnvParentId"] = {}; for (let id of envParentIds) { if (envsNeedFetch(state, id)) { needsFetch = true; byEnvParentId[id] = { envs: true }; } } if (needsFetch) { spinnerWithText("Fetching and decrypting..."); const fetchRes = await dispatch({ type: Client.ActionType.FETCH_ENVS, payload: { byEnvParentId, }, }); stopSpinner(); // TODO: handle errors return fetchRes.state; } return state; }, fetchChangesetsIfNeeded = async ( state: Client.State, envParentIds: string[] ): Promise<Client.State> => { let needsFetch = false; const byEnvParentId: Api.Net.FetchEnvsParams["byEnvParentId"] = {}; for (let id of envParentIds) { if (changesetsNeedFetch(state, id)) { needsFetch = true; byEnvParentId[id] = { changesets: true }; } } if (needsFetch) { spinnerWithText("Fetching and decrypting..."); const fetchRes = await dispatch({ type: Client.ActionType.FETCH_ENVS, payload: { byEnvParentId, }, }); stopSpinner(); // TODO: handle errors return fetchRes.state; } return state; };
the_stack
import type {TextureFormat, DeviceFeature, Device} from '@luma.gl/api'; import {decodeTextureFormat} from '@luma.gl/api'; import GL from '@luma.gl/constants'; import {isWebGL2} from '../../context/context/webgl-checks'; // TEXTURE FEATURES // Define local device feature strings to optimize minification const texture_compression_bc: DeviceFeature = 'texture-compression-bc'; const texture_compression_astc: DeviceFeature = 'texture-compression-astc'; const texture_compression_etc2: DeviceFeature = 'texture-compression-etc2'; const texture_compression_etc1_webgl: DeviceFeature = 'texture-compression-etc1-webgl'; const texture_compression_pvrtc_webgl: DeviceFeature = 'texture-compression-pvrtc-webgl'; const texture_compression_atc_webgl: DeviceFeature = 'texture-compression-atc-webgl'; // Define local webgl extension strings to optimize minification const X_S3TC = 'WEBGL_compressed_texture_s3tc'; // BC1, BC2, BC3 const X_S3TC_SRGB = 'WEBGL_compressed_texture_s3tc_srgb'; // BC1, BC2, BC3 const X_RGTC = 'EXT_texture_compression_rgtc'; // BC4, BC5 const X_BPTC = 'EXT_texture_compression_bptc'; // BC6, BC7 const X_ETC2 = 'WEBGL_compressed_texture_etc'; // Renamed from 'WEBGL_compressed_texture_es3' const X_ASTC = 'WEBGL_compressed_texture_astc'; const X_ETC1 = 'WEBGL_compressed_texture_etc1'; const X_PVRTC = 'WEBGL_compressed_texture_pvrtc'; const X_ATC = 'WEBGL_compressed_texture_atc'; // Define local webgl extension strings to optimize minification const EXT_SRGB = 'EXT_sRGB'; // https://developer.mozilla.org/en-US/docs/Web/API/EXT_sRGB const EXT_TEXTURE_NORM16 = 'EXT_texture_norm16'; const EXT_FLOAT_WEBGL1 = 'WEBGL_color_buffer_float'; const EXT_FLOAT_RENDER_WEBGL2 = 'EXT_color_buffer_float'; const EXT_HALF_FLOAT_WEBGL1 = 'WEBGL_color_buffer_half_float'; // const DEPTH = 'WEBGL_depth_texture'; const checkExtension = (gl: WebGLRenderingContext, extension: string): boolean => gl.getExtension(extension); const checkExtensions = (gl: WebGLRenderingContext, extensions: string[]): boolean => extensions.every((extension) => gl.getExtension(extension)); // prettier-ignore const TEXTURE_FEATURE_CHECKS: Partial<Record<DeviceFeature, (gl: WebGLRenderingContext) => boolean> > = { 'texture-blend-float-webgl1': (gl) => isWebGL2(gl) ? true : checkExtension(gl, 'EXT_float_blend'), 'texture-formats-srgb-webgl1': (gl) => (isWebGL2(gl) ? true : checkExtension(gl, EXT_SRGB)), 'texture-formats-depth-webgl1': (gl) => isWebGL2(gl) ? true : checkExtension(gl, 'WEBGL_depth_texture'), 'texture-formats-float32-webgl1': (gl) => isWebGL2(gl) ? true : checkExtension(gl, 'OES_texture_float'), 'texture-formats-float16-webgl1': (gl) => isWebGL2(gl) ? true : checkExtension(gl, 'OES_texture_half_float'), 'texture-formats-norm16-webgl': (gl) => isWebGL2(gl) ? checkExtension(gl, EXT_TEXTURE_NORM16) : false, 'texture-filter-linear-float32-webgl': (gl) => checkExtension(gl, 'OES_texture_float_linear'), 'texture-filter-linear-float16-webgl': (gl) => checkExtension(gl, 'OES_texture_half_float_linear'), 'texture-filter-anisotropic-webgl': (gl) => checkExtension(gl, 'EXT_texture_filter_anisotropic'), 'texture-renderable-float32-webgl': (gl) => checkExtension(gl, 'EXT_color_buffer_float'), // [false, 'EXT_color_buffer_float'], 'texture-renderable-float16-webgl': (gl) => checkExtension(gl, 'EXT_color_buffer_half_float'), 'texture-compression-bc': (gl) => checkExtensions(gl, [X_S3TC, X_S3TC_SRGB, X_RGTC, X_BPTC]), 'texture-compression-bc5-webgl': (gl) => checkExtensions(gl, [X_RGTC]), // 'texture-compression-bc7-webgl': gl => checkExtensions(gl, [X_BPTC]), // 'texture-compression-bc3-srgb-webgl': gl => checkExtensions(gl, [X_S3TC_SRGB]), // 'texture-compression-bc3-webgl': gl => checkExtensions(gl, [X_S3TC]), 'texture-compression-etc2': (gl) => checkExtensions(gl, [X_ETC2]), 'texture-compression-astc': (gl) => checkExtensions(gl, [X_ASTC]), 'texture-compression-etc1-webgl': (gl) => checkExtensions(gl, [X_ETC1]), 'texture-compression-pvrtc-webgl': (gl) => checkExtensions(gl, [X_PVRTC]), 'texture-compression-atc-webgl': (gl) => checkExtensions(gl, [X_ATC]) }; export function checkTextureFeature(gl: WebGLRenderingContext, feature: DeviceFeature): boolean { return TEXTURE_FEATURE_CHECKS[feature]?.(gl); } const checkTextureFeatures = (gl: WebGLRenderingContext, features: DeviceFeature[]): boolean => features.every((feature) => checkTextureFeature(gl, feature)); /** Return a list of texture feature strings (for Device.features). Mainly compressed texture support */ export function getTextureFeatures(gl: WebGLRenderingContext): DeviceFeature[] { const textureFeatures = Object.keys(TEXTURE_FEATURE_CHECKS) as DeviceFeature[]; return textureFeatures.filter((feature) => checkTextureFeature(gl, feature)); } // TEXTURE FORMATS /** Map a format to webgl and constants */ type Format = { gl?: GL; /** If a different unsized format is needed in WebGL1 */ gl1?: GL; gl1ext?: string; gl2ext?: string; // format requires WebGL2, when using a WebGL 1 context, color renderbuffer formats are limited b?: number; // (bytes per pixel), for memory usage calculations. /** channels */ c?: number; bpp?: number; /** packed */ p?: number; x?: string; // compressed f?: DeviceFeature; // for compressed texture formats render?: DeviceFeature; // renderable if extension is present filter?: DeviceFeature; wgpu?: false; // If not supported on WebGPU types?: number[]; dataFormat?: GL; attachment?: GL.DEPTH_ATTACHMENT | GL.STENCIL_ATTACHMENT | GL.DEPTH_STENCIL_ATTACHMENT; }; // TABLES /** Legal combinations for internalFormat, format and type * // [GL.DEPTH_COMPONENT]: {types: [GL.UNSIGNED_SHORT, GL.UNSIGNED_INT, GL.UNSIGNED_INT_24_8], gl1ext: DEPTH}, // [GL.DEPTH_STENCIL]: {gl1ext: DEPTH}, // Sized texture format // R [GL.R8]: {dataFormat: GL.RED, types: [GL.UNSIGNED_BYTE], gl2: true}, [GL.R16F]: {dataFormat: GL.RED, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true}, [GL.R8UI]: {dataFormat: GL.RED_INTEGER, types: [GL.UNSIGNED_BYTE], gl2: true}, // // RG [GL.RG8]: {dataFormat: GL.RG, types: [GL.UNSIGNED_BYTE], gl2: true}, [GL.RG16F]: {dataFormat: GL.RG, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true}, [GL.RG8UI]: {dataFormat: GL.RG_INTEGER, types: [GL.UNSIGNED_BYTE], gl2: true}, // // RGB [GL.RGB8]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE], gl2: true}, [GL.SRGB8]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE], gl2: true, gl1ext: EXT_SRGB}, [GL.RGB16F]: {dataFormat: GL.RGB, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true, gl1ext: EXT_HALF_FLOAT_WEBGL1}, [GL.RGB8UI]: {dataFormat: GL.RGB_INTEGER, types: [GL.UNSIGNED_BYTE], gl2: true}, // // RGBA [GL.RGB565]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_5_6_5], gl2: true}, [GL.R11F_G11F_B10F]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_INT_10F_11F_11F_REV, GL.HALF_FLOAT, GL.FLOAT], gl2: true}, [GL.RGB9_E5]: {dataFormat: GL.RGB, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true, gl1ext: EXT_HALF_FLOAT_WEBGL1}, [GL.RGBA8]: {dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE], gl2: true}, [GL.SRGB8_ALPHA8]: {dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE], gl2: true, gl1ext: EXT_SRGB}, [GL.RGB5_A1]: {dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_5_5_5_1], gl2: true}, [GL.RGBA4]: {dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_4_4_4_4], gl2: true}, [GL.RGBA16F]: {dataFormat: GL.RGBA, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true, gl1ext: EXT_HALF_FLOAT_WEBGL1}, [GL.RGBA8UI]: {dataFormat: GL.RGBA_INTEGER, types: [GL.UNSIGNED_BYTE], gl2: true} */ /** Texture format data */ // prettier-ignore export const TEXTURE_FORMATS: Record<TextureFormat, Format> = { // Unsized formats that leave the precision up to the driver. // TODO - Fix bpp constants // 'r8unorm-unsized': {gl: GL.LUMINANCE, b: 4, c: 2, bpp: 4}, 'rgb8unorm-unsized': {gl: GL.RGB, gl1: GL.RGB, b: 4, c: 2, bpp: 4, dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_5_6_5]}, 'rgba8unorm-unsized': {gl: GL.RGBA, gl1: GL.RGBA, b: 4, c: 2, bpp: 4, dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_4_4_4_4, GL.UNSIGNED_SHORT_5_5_5_1]}, // 'rgb8unorm-srgb-unsized': {gl: GL.SRGB_EXT, b: 4, c: 2, bpp: 4, gl1Ext: SRGB}, // 'rgba8unorm-srgb-unsized': {gl: GL.SRGB_ALPHA_EXT, b: 4, c: 2, bpp: 4, gl1Ext: SRGB}, // 8-bit formats 'r8unorm': {gl: GL.R8, b: 1, c: 1}, 'r8snorm': {gl: GL.R8_SNORM, b: 1, c: 1}, 'r8uint': {gl: GL.R8UI, b: 1, c: 1}, 'r8sint': {gl: GL.R8I, b: 1, c: 1}, // 16-bit formats 'rg8unorm': {gl: GL.RG8, b: 2, c: 2}, 'rg8snorm': {gl: GL.RG8_SNORM, b: 2, c: 2}, 'rg8uint': {gl: GL.RG8UI, b: 2, c: 2}, 'rg8sint': {gl: GL.RG8I, b: 2, c: 2}, 'r16uint': {gl: GL.R16UI, b: 2, c: 1}, 'r16sint': {gl: GL.R16I, b: 2, c: 1}, 'r16float': {gl: GL.R16F, b: 2, c: 1, render: 'texture-renderable-float16-webgl', filter: 'texture-filter-linear-float16-webgl'}, 'r16unorm-webgl': {gl: GL.R16_EXT, b:2, c:1, f: 'texture-formats-norm16-webgl'}, 'r16snorm-webgl': {gl: GL.R16_SNORM_EXT, b:2, c:1, f: 'texture-formats-norm16-webgl'}, // Packed 16-bit formats 'rgba4unorm-webgl': {gl: GL.RGBA4, b: 2, c: 4, wgpu: false}, 'rgb565unorm-webgl': {gl: GL.RGB565, b: 2, c: 4, wgpu: false}, 'rgb5a1unorm-webgl': {gl: GL.RGB5_A1, b: 2, c: 4, wgpu: false}, // 24-bit formats 'rbg8unorm-webgl': {gl: GL.RGB8, b: 3, c: 3, wgpu: false}, 'rbg8snorm-webgl': {gl: GL.RGB8_SNORM, b: 3, c: 3, wgpu: false}, // 32-bit formats 'rgba8unorm': {gl: GL.RGBA8, gl1: GL.RGBA, b: 4, c: 2, bpp: 4}, 'rgba8unorm-srgb': {gl: GL.SRGB8_ALPHA8, gl1: GL.SRGB_ALPHA_EXT, b: 4, c: 4, gl1ext: EXT_SRGB, bpp: 4}, 'rgba8snorm': {gl: GL.RGBA8_SNORM, b: 4, c: 4}, 'rgba8uint': {gl: GL.RGBA8UI, b: 4, c: 4, bpp: 4}, 'rgba8sint': {gl: GL.RGBA8I, b: 4, c: 4, bpp: 4}, // reverse colors, webgpu only 'bgra8unorm': {b: 4, c: 4}, 'bgra8unorm-srgb': {b: 4, c: 4}, 'rg16uint': {gl: GL.RG16UI, b: 4, c: 1, bpp: 4}, 'rg16sint': {gl: GL.RG16I, b: 4, c: 2, bpp: 4}, // When using a WebGL 2 context and the EXT_color_buffer_float WebGL2 extension 'rg16float': {gl: GL.RG16F, bpp: 4, b: 4, c: 2, render: 'texture-renderable-float16-webgl', filter: 'texture-filter-linear-float16-webgl'}, 'rg16unorm-webgl': {gl: GL.RG16_EXT, b:2, c:2, f: 'texture-formats-norm16-webgl'}, 'rg16snorm-webgl': {gl: GL.RG16_SNORM_EXT, b:2, c:2, f: 'texture-formats-norm16-webgl'}, 'r32uint': {gl: GL.R32UI, b: 4, c: 1, bpp: 4}, 'r32sint': {gl: GL.R32I, b: 4, c: 1, bpp: 4}, 'r32float': {gl: GL.R32F, bpp: 4, b: 4, c: 1, render: 'texture-renderable-float32-webgl', filter: 'texture-filter-linear-float32-webgl'}, // Packed 32-bit formats 'rgb9e5ufloat': {gl: GL.RGB9_E5, b: 4, c: 3, p: 1, render: 'texture-renderable-float16-webgl', filter: 'texture-filter-linear-float16-webgl'}, 'rg11b10ufloat': {gl: GL.R11F_G11F_B10F, b: 4, c: 3, p: 1,render: 'texture-renderable-float32-webgl'}, 'rgb10a2unorm': {gl: GL.RGB10_A2, b: 4, c: 4, p: 1}, // webgl2 only 'rgb10a2unorm-webgl': {b: 4, c: 4, gl: GL.RGB10_A2UI, p: 1, wgpu: false, bpp: 4}, // 48-bit formats 'rgb16unorm-webgl': {gl: GL.RGB16_EXT, b:2, c:3, f: 'texture-formats-norm16-webgl'}, 'rgb16snorm-webgl': {gl: GL.RGB16_SNORM_EXT, b:2, c:3, f: 'texture-formats-norm16-webgl'}, // 64-bit formats 'rg32uint': {gl: GL.RG32UI, b: 8, c: 2}, 'rg32sint': {gl: GL.RG32I, b: 8, c: 2}, 'rg32float': {gl: GL.RG32F, b: 8, c: 2, render: 'texture-renderable-float32-webgl', filter: 'texture-filter-linear-float32-webgl'}, 'rgba16uint': {gl: GL.RGBA16UI, b: 8, c: 4}, 'rgba16sint': {gl: GL.RGBA16I, b: 8, c: 4}, 'rgba16float': {gl: GL.RGBA16F, gl1: GL.RGBA, b: 8, c: 4, render: 'texture-renderable-float16-webgl', filter: 'texture-filter-linear-float16-webgl'}, 'rgba16unorm-webgl': {gl: GL.RGBA16_EXT, b:2, c:4, f: 'texture-formats-norm16-webgl'}, 'rgba16snorm-webgl': {gl: GL.RGBA16_SNORM_EXT, b:2, c:4, f: 'texture-formats-norm16-webgl'}, // 96-bit formats (deprecated!) 'rgb32float-webgl': {gl: GL.RGB32F, gl1: GL.RGB, render: 'texture-renderable-float32-webgl', filter: 'texture-filter-linear-float32-webgl', gl2ext: EXT_FLOAT_RENDER_WEBGL2, gl1ext: EXT_FLOAT_WEBGL1, // WebGL1 render buffers are supported with GL.RGB32F dataFormat: GL.RGB, types: [GL.FLOAT]}, // 128-bit formats 'rgba32uint': {gl: GL.RGBA32UI, b: 16, c: 4}, 'rgba32sint': {gl: GL.RGBA32I, b: 16, c: 4}, 'rgba32float': {gl: GL.RGBA32F, gl1: GL.RGBA, b: 16, c: 4, render: 'texture-renderable-float32-webgl', filter: 'texture-filter-linear-float32-webgl'}, // Depth and stencil formats 'stencil8': {gl: GL.STENCIL_INDEX8, b: 1, c: 1, attachment: GL.STENCIL_ATTACHMENT}, // 8 stencil bits 'depth16unorm': {gl: GL.DEPTH_COMPONENT16, gl1: GL.DEPTH_COMPONENT16, b: 2, c: 1, attachment: GL.DEPTH_ATTACHMENT}, // 16 depth bits 'depth24plus': {gl: GL.DEPTH_COMPONENT24, b: 3, c: 1, attachment: GL.DEPTH_ATTACHMENT}, 'depth32float': {gl: GL.DEPTH_COMPONENT32F, b: 4, c: 1, attachment: GL.DEPTH_ATTACHMENT}, 'depth24plus-stencil8': {b: 4, gl: GL.UNSIGNED_INT_24_8, gl1: GL.DEPTH_STENCIL, c: 2, p: 1, attachment: GL.DEPTH_STENCIL_ATTACHMENT}, // "depth24unorm-stencil8" feature 'depth24unorm-stencil8': {gl: GL.DEPTH24_STENCIL8, b: 4, c: 2, p: 1, attachment: GL.DEPTH_STENCIL_ATTACHMENT}, // "depth32float-stencil8" feature "depth32float-stencil8": {gl: GL.DEPTH32F_STENCIL8, b: 5, c: 2, p: 1, attachment: GL.DEPTH_STENCIL_ATTACHMENT}, // BC compressed formats: check device.features.has("texture-compression-bc"); 'bc1-rgb-unorm-webgl': {gl: GL.COMPRESSED_RGB_S3TC_DXT1_EXT, x: X_S3TC, f: texture_compression_bc}, 'bc1-rgb-unorm-srgb-webgl': {gl: GL.COMPRESSED_SRGB_S3TC_DXT1_EXT, x: X_S3TC_SRGB, f: texture_compression_bc}, 'bc1-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT1_EXT, x: X_S3TC, f: texture_compression_bc}, 'bc1-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_S3TC_DXT1_EXT, x: X_S3TC_SRGB, f: texture_compression_bc}, 'bc2-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT3_EXT, x: X_S3TC, f: texture_compression_bc}, 'bc2-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, x: X_S3TC_SRGB, f: texture_compression_bc}, 'bc3-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT5_EXT, x: X_S3TC, f: texture_compression_bc}, 'bc3-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, x: X_S3TC_SRGB, f: texture_compression_bc}, 'bc4-r-unorm': {gl: GL.COMPRESSED_RED_RGTC1_EXT, x: X_RGTC, f: texture_compression_bc}, 'bc4-r-snorm': {gl: GL.COMPRESSED_SIGNED_RED_RGTC1_EXT, x: X_RGTC, f: texture_compression_bc}, 'bc5-rg-unorm': {gl: GL.COMPRESSED_RED_GREEN_RGTC2_EXT, x: X_RGTC, f: texture_compression_bc}, 'bc5-rg-snorm': {gl: GL.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT, x: X_RGTC, f: texture_compression_bc}, 'bc6h-rgb-ufloat': {gl: GL.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT, x: X_BPTC, f: texture_compression_bc}, 'bc6h-rgb-float': {gl: GL.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT, x: X_BPTC, f: texture_compression_bc}, 'bc7-rgba-unorm': {gl: GL.COMPRESSED_RGBA_BPTC_UNORM_EXT, x: X_BPTC, f: texture_compression_bc}, 'bc7-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT, x: X_BPTC, f: texture_compression_bc}, // WEBGL_compressed_texture_etc: device.features.has("texture-compression-etc2") // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression 'etc2-rgb8unorm': {gl: GL.COMPRESSED_RGB8_ETC2, f: texture_compression_etc2}, 'etc2-rgb8unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ETC2, f: texture_compression_etc2}, 'etc2-rgb8a1unorm': {gl: GL.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, f: texture_compression_etc2}, 'etc2-rgb8a1unorm-srgb': {gl: GL.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, f: texture_compression_etc2}, 'etc2-rgba8unorm': {gl: GL.COMPRESSED_RGBA8_ETC2_EAC, f: texture_compression_etc2}, 'etc2-rgba8unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, f: texture_compression_etc2}, 'eac-r11unorm': {gl: GL.COMPRESSED_R11_EAC, f: texture_compression_etc2}, 'eac-r11snorm': {gl: GL.COMPRESSED_SIGNED_R11_EAC, f: texture_compression_etc2}, 'eac-rg11unorm': {gl: GL.COMPRESSED_RG11_EAC, f: texture_compression_etc2}, 'eac-rg11snorm': {gl: GL.COMPRESSED_SIGNED_RG11_EAC, f: texture_compression_etc2}, // X_ASTC compressed formats: device.features.has("texture-compression-astc") 'astc-4x4-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_4x4_KHR, f: texture_compression_astc}, 'astc-4x4-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, f: texture_compression_astc}, 'astc-5x4-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_5x4_KHR, f: texture_compression_astc}, 'astc-5x4-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR, f: texture_compression_astc}, 'astc-5x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_5x5_KHR, f: texture_compression_astc}, 'astc-5x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR, f: texture_compression_astc}, 'astc-6x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_6x5_KHR, f: texture_compression_astc}, 'astc-6x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR, f: texture_compression_astc}, 'astc-6x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_6x6_KHR, f: texture_compression_astc}, 'astc-6x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, f: texture_compression_astc}, 'astc-8x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x5_KHR, f: texture_compression_astc}, 'astc-8x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR, f: texture_compression_astc}, 'astc-8x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x6_KHR, f: texture_compression_astc}, 'astc-8x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR, f: texture_compression_astc}, 'astc-8x8-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x8_KHR, f: texture_compression_astc}, 'astc-8x8-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR, f: texture_compression_astc}, 'astc-10x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x10_KHR, f: texture_compression_astc}, 'astc-10x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, f: texture_compression_astc}, 'astc-10x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x6_KHR, f: texture_compression_astc}, 'astc-10x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR, f: texture_compression_astc}, 'astc-10x8-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x8_KHR, f: texture_compression_astc}, 'astc-10x8-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR, f: texture_compression_astc}, 'astc-10x10-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x10_KHR, f: texture_compression_astc}, 'astc-10x10-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, f: texture_compression_astc}, 'astc-12x10-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_12x10_KHR, f: texture_compression_astc}, 'astc-12x10-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR, f: texture_compression_astc}, 'astc-12x12-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_12x12_KHR, f: texture_compression_astc}, 'astc-12x12-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, f: texture_compression_astc}, // WEBGL_compressed_texture_pvrtc 'pvrtc-rgb4unorm-webgl': {gl: GL.COMPRESSED_RGB_PVRTC_4BPPV1_IMG, f: texture_compression_pvrtc_webgl}, 'pvrtc-rgba4unorm-webgl': {gl: GL.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, f: texture_compression_pvrtc_webgl}, 'pvrtc-rbg2unorm-webgl': {gl: GL.COMPRESSED_RGB_PVRTC_2BPPV1_IMG, f: texture_compression_pvrtc_webgl}, 'pvrtc-rgba2unorm-webgl': {gl: GL.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, f: texture_compression_pvrtc_webgl}, // WEBGL_compressed_texture_etc1 'etc1-rbg-unorm-webgl': {gl: GL.COMPRESSED_RGB_ETC1_WEBGL, f: texture_compression_etc1_webgl}, // WEBGL_compressed_texture_atc 'atc-rgb-unorm-webgl': {gl: GL.COMPRESSED_RGB_ATC_WEBGL, f: texture_compression_atc_webgl}, 'atc-rgba-unorm-webgl': {gl: GL.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL, f: texture_compression_atc_webgl}, 'atc-rgbai-unorm-webgl': {gl: GL.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL, f: texture_compression_atc_webgl} }; // FUNCTIONS function getTextureFormat(format: TextureFormat | GL): TextureFormat { if (typeof format === 'string') { return format; } const entry = Object.entries(TEXTURE_FORMATS).find(([, entry]) => (entry.gl === format || entry.gl1 === format)); if (!entry) { throw new Error(`Unknown texture format ${format}`); } return entry[0] as TextureFormat; } /** Checks if a texture format is supported */ export function isTextureFormatSupported( gl: WebGLRenderingContext, formatOrGL: TextureFormat | GL ): boolean { const format = getTextureFormat(formatOrGL); const info = TEXTURE_FORMATS[format]; if (!info) { return false; } // Check that we have a GL constant if (isWebGL2(gl) ? info.gl === undefined : info.gl1 === undefined) { return false; } // Check extensions const extension = info.x || (isWebGL2(gl) ? info.gl2ext || info.gl1ext : info.gl1ext); if (extension) { return Boolean(gl.getExtension(extension)); } // if (info.gl1 === undefined && info.gl2 === undefined) { // // No info - always supported // } return true; } /** Checks if a texture format is supported */ export function getTextureFormatSupport( gl: WebGLRenderingContext, formatOrGL: TextureFormat | GL ): { supported: boolean; filterable?: boolean; renderable?: boolean; blendable?: boolean; storable?: boolean; } { const format = getTextureFormat(formatOrGL); const info = TEXTURE_FORMATS[format]; if (!info) { return {supported: false}; } let decoded; try { decoded = decodeTextureFormat(format); } catch {} // Support Check that we have a GL constant let supported = isWebGL2(gl) ? info.gl === undefined : info.gl1 === undefined; supported = supported && checkTextureFeatures(gl, [info.f]); // Filtering const filterable = info.filter ? checkTextureFeatures(gl, [info.filter]) : decoded && !decoded.signed; const renderable = info.filter ? checkTextureFeatures(gl, [info.render]) : decoded && !decoded.signed; return { supported, renderable: supported && checkTextureFeatures(gl, [info.render]), filterable: supported && checkTextureFeatures(gl, [info.filter]), blendable: false, // tod, storable: false }; } /** Checks whether linear filtering (interpolated sampling) is available for floating point textures */ export function isTextureFormatFilterable( gl: WebGLRenderingContext, formatOrGL: TextureFormat | GL ): boolean { const format = getTextureFormat(formatOrGL); if (!isTextureFormatSupported(gl, format)) { return false; } try { const decoded = decodeTextureFormat(format); if (decoded.signed) { return false; } } catch { return false; } if (format.endsWith('32float')) { return Boolean(gl.getExtension('OES_texture_float_linear')); } if (format.endsWith('16float')) { return Boolean(gl.getExtension('OES_texture_half_float_linear')); } // if (typeof format === 'string') { // if (format === 'rgba32float') { // return gl.device.features.has('texture-renderable-rgba32float-webgl'); // } // if (format.endsWith('32float')) { // return gl.device.features.has('texture-renderable-float32-webgl'); // } // if (format.endsWith('16float')) { // return gl.device.features.has('texture-renderable-float16-webgl'); // } // } return true; } export function isTextureFormatRenderable( gl: WebGLRenderingContext, formatOrGL: TextureFormat | GL ): boolean { const format = getTextureFormat(formatOrGL); if (!isTextureFormatSupported(gl, format)) { return false; } if (typeof format === 'number') { return false; // isTextureFormatFilterableWebGL(gl, format); } // TODO depends on device... return true; } /** * Converts WebGPU string style texture formats to GL constants * Pass through GL constants */ export function getWebGLTextureFormat(gl: WebGLRenderingContext, formatOrGL: TextureFormat | GL): GL | undefined { const format = getTextureFormat(formatOrGL); const formatInfo = TEXTURE_FORMATS[format]; const webglFormat = isWebGL2(gl) ? formatInfo?.gl : formatInfo?.gl1; // Remap or pass through if (typeof format === 'number') { return webglFormat || format; } if (webglFormat === undefined) { throw new Error(`Unsupported texture format ${format}`); } return webglFormat; } export function getWebGLTextureParameters(gl: WebGLRenderingContext, formatOrGL: TextureFormat | GL) { const format = getTextureFormat(formatOrGL); const webglFormat = getWebGLTextureFormat(gl, format); const decoded = decodeTextureFormat(format); return { format: webglFormat, dataFormat: getWebGLPixelDataFormat( decoded.format, decoded.integer, decoded.normalized, webglFormat ), type: getWebGLDataType(decoded.dataType), // @ts-expect-error compressed: decoded.compressed }; } export function getWebGLDepthStencilAttachment( formatOrGL: TextureFormat | GL ): GL.DEPTH_ATTACHMENT | GL.STENCIL_ATTACHMENT | GL.DEPTH_STENCIL_ATTACHMENT { const format = getTextureFormat(formatOrGL); if (typeof format === 'number') { // TODO throw new Error('unsupported depth stencil format') } const info = TEXTURE_FORMATS[format]; const attachment = info.attachment; if (!attachment) { throw new Error('not a depth stencil format'); } return attachment; } /** * function to test if Float 32 bit format texture can be bound as color attachment * @todo Generalize to check arbitrary formats? */ export function _checkFloat32ColorAttachment( gl: WebGLRenderingContext, internalFormat = gl.RGBA, srcFormat = GL.RGBA, srcType = GL.UNSIGNED_BYTE ) { let texture: WebGLTexture; let framebuffer: WebGLFramebuffer; try { texture = gl.createTexture(); gl.bindTexture(GL.TEXTURE_2D, texture); const level = 0; const width = 1; const height = 1; const border = 0; const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue gl.texImage2D( gl.TEXTURE_2D, level, internalFormat, width, height, border, srcFormat, srcType, pixel ); framebuffer = gl.createFramebuffer(); gl.bindFramebuffer(GL.FRAMEBUFFER, framebuffer); gl.framebufferTexture2D(GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, texture, 0); const status = gl.checkFramebufferStatus(GL.FRAMEBUFFER) === GL.FRAMEBUFFER_COMPLETE; gl.bindTexture(GL.TEXTURE_2D, null); return status; } finally { gl.deleteTexture(texture); gl.deleteFramebuffer(framebuffer); } } /** @deprecated should be removed */ const DATA_FORMAT_CHANNELS = { [GL.RED]: 1, [GL.RED_INTEGER]: 1, [GL.RG]: 2, [GL.RG_INTEGER]: 2, [GL.RGB]: 3, [GL.RGB_INTEGER]: 3, [GL.RGBA]: 4, [GL.RGBA_INTEGER]: 4, [GL.DEPTH_COMPONENT]: 1, [GL.DEPTH_STENCIL]: 1, [GL.ALPHA]: 1, [GL.LUMINANCE]: 1, [GL.LUMINANCE_ALPHA]: 2 }; /** @deprecated should be removed */ const TYPE_SIZES = { [GL.FLOAT]: 4, [GL.UNSIGNED_INT]: 4, [GL.INT]: 4, [GL.UNSIGNED_SHORT]: 2, [GL.SHORT]: 2, [GL.HALF_FLOAT]: 2, [GL.BYTE]: 1, [GL.UNSIGNED_BYTE]: 1 }; /** TODO - VERY roundabout legacy way of calculating bytes per pixel */ export function getTextureFormatBytesPerPixel(gl: WebGLRenderingContext, formatOrGL: TextureFormat | GL): number { const format = getTextureFormat(formatOrGL); const params = getWebGLTextureParameters(gl, format); // NOTE(Tarek): Default to RGBA bytes const channels = DATA_FORMAT_CHANNELS[params.dataFormat] || 4; const channelSize = TYPE_SIZES[params.type] || 1; return channels * channelSize; } // DATA TYPE HELPERS function getWebGLPixelDataFormat( dataFormat: string, integer: boolean, normalized: boolean, format: GL ): GL { // WebGL1 formats use same internalFormat if (format === GL.RGBA || format === GL.RGB) { return format; } // prettier-ignore switch (dataFormat) { case 'r': return integer && !normalized ? GL.RED_INTEGER : GL.RED; case 'rg': return integer && !normalized ? GL.RG_INTEGER : GL.RG; case 'rgb': return integer && !normalized ? GL.RGB_INTEGER : GL.RGB; case 'rgba': return integer && !normalized ? GL.RGBA_INTEGER : GL.RGBA; default: return GL.RGBA; } } export function getWebGLDataType(dataType: string): GL { // prettier-ignore switch (dataType) { case 'uint8': return GL.UNSIGNED_BYTE; case 'sint8': return GL.BYTE; case 'uint16': return GL.UNSIGNED_SHORT; case 'sint16': return GL.SHORT; case 'uint32': return GL.UNSIGNED_INT; case 'sint32': return GL.INT; case 'float16': return GL.HALF_FLOAT; case 'float32': return GL.FLOAT; default: return GL.UNSIGNED_BYTE; } }
the_stack
import { track } from '../Interface'; // MP4 boxes generator for ISO BMFF (ISO Base Media File Format, defined in ISO/IEC 14496-12) class MP4 { static types: Record<string, Array<number>> static HDLR_TYPES: Record<string, Uint8Array> static STTS: Uint8Array static STSC: Uint8Array static STCO: Uint8Array static STSZ: Uint8Array static VMHD: Uint8Array static SMHD: Uint8Array static STSD: Uint8Array static FTYP: Uint8Array static DINF: Uint8Array static STSD_PREFIX: Uint8Array static HDLR_VIDEO: Uint8Array static HDLR_AUDIO: Uint8Array static DREF: Uint8Array static init() { MP4.types = { avc1: [], avcC: [], btrt: [], dinf: [], dref: [], esds: [], ftyp: [], hdlr: [], mdat: [], mdhd: [], mdia: [], mfhd: [], minf: [], moof: [], moov: [], mp4a: [], mvex: [], mvhd: [], sdtp: [], stbl: [], stco: [], stsc: [], stsd: [], stsz: [], stts: [], tfdt: [], tfhd: [], traf: [], trak: [], trun: [], trex: [], tkhd: [], vmhd: [], smhd: [], '.mp3': [] }; Object.keys(MP4.types).forEach((type) => { MP4.types[type] = [ type.charCodeAt(0), type.charCodeAt(1), type.charCodeAt(2), type.charCodeAt(3) ]; }); MP4.FTYP = new Uint8Array([ 0x69, 0x73, 0x6f, 0x6d, // major_brand: isom 0x0, 0x0, 0x0, 0x1, // minor_version: 0x01 0x69, 0x73, 0x6f, 0x6d, // isom 0x61, 0x76, 0x63, 0x31 // avc1 ]); MP4.STSD_PREFIX = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x01 // entry_count ]); MP4.STTS = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x00 // entry_count ]); MP4.STCO = MP4.STTS; MP4.STSC = MP4.STTS; MP4.STSZ = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x00, // sample_size 0x00, 0x00, 0x00, 0x00 // sample_count ]); MP4.HDLR_VIDEO = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide' 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: VideoHandler ]); MP4.HDLR_AUDIO = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun' 0x00, 0x00, 0x00, 0x00, // reserved: 3 * 4 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: SoundHandler ]); MP4.DREF = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x01, // entry_count 0x00, 0x00, 0x00, 0x0c, // entry_size 0x75, 0x72, 0x6c, 0x20, // type 'url ' 0x00, 0x00, 0x00, 0x01 // version(0) + flags ]); // Sound media header MP4.SMHD = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x00 // balance(2) + reserved(2) ]); // video media header MP4.VMHD = new Uint8Array([ 0x00, 0x00, 0x00, 0x01, // version(0) + flags 0x00, 0x00, // graphicsmode: 2 bytes 0x00, 0x00, 0x00, 0x00, // opcolor: 3 * 2 bytes 0x00, 0x00 ]); } // Generate a box static box(type: Array<number>, ...args: Array<Uint8Array>) { let size = 8; let result = null; const datas = [...args]; const arrayCount = datas.length; for(let i = 0; i < arrayCount; i++) { size += datas[i].byteLength; } result = new Uint8Array(size); result[0] = (size >>> 24) & 0xff; // size result[1] = (size >>> 16) & 0xff; result[2] = (size >>> 8) & 0xff; result[3] = size & 0xff; result.set(type, 4); // type let offset = 8; for(let i = 0; i < arrayCount; i++) { // data body result.set(datas[i], offset); offset += datas[i].byteLength; } return result; } // emit ftyp & moov static generateInitSegment(meta: track) { const ftyp = MP4.box(MP4.types.ftyp, MP4.FTYP); const moov = MP4.moov(meta); const result = new Uint8Array(ftyp.byteLength + moov.byteLength); result.set(ftyp, 0); result.set(moov, ftyp.byteLength); return result; } // Movie metadata box static moov(meta: track) { const mvhd = MP4.mvhd(meta.timescale, meta.duration); const trak = MP4.trak(meta); const mvex = MP4.mvex(meta); return MP4.box(MP4.types.moov, mvhd, trak, mvex); } // Movie header box static mvhd(timescale: number, duration: number = 0) { return MP4.box( MP4.types.mvhd, new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x00, // creation_time 0x00, 0x00, 0x00, 0x00, // modification_time (timescale >>> 24) & 0xff, // timescale: 4 bytes (timescale >>> 16) & 0xff, (timescale >>> 8) & 0xff, timescale & 0xff, (duration >>> 24) & 0xff, // duration: 4 bytes (duration >>> 16) & 0xff, (duration >>> 8) & 0xff, duration & 0xff, 0x00, 0x01, 0x00, 0x00, // Preferred rate: 1.0 0x01, 0x00, 0x00, 0x00, // PreferredVolume(1.0, 2bytes) + reserved(2bytes) 0x00, 0x00, 0x00, 0x00, // reserved: 4 + 4 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix---- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // ----end composition matrix---- 0x00, 0x00, 0x00, 0x00, // ----begin pre_defined 6 * 4 bytes---- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ----end pre_defined 6 * 4 bytes---- 0xff, 0xff, 0xff, 0xff // next_track_ID ]) ); } // Track box static trak(meta: track) { return MP4.box(MP4.types.trak, MP4.tkhd(meta), MP4.mdia(meta)); } // Track header box static tkhd(meta: track) { const trackId = meta.id; const duration = meta.duration || 0; const width = meta.presentWidth; const height = meta.presentHeight; return MP4.box( MP4.types.tkhd, new Uint8Array([ 0x00, 0x00, 0x00, 0x07, // version(0) + flags 0x00, 0x00, 0x00, 0x00, // creation_time 0x00, 0x00, 0x00, 0x00, // modification_time (trackId >>> 24) & 0xff, // track_ID: 4 bytes (trackId >>> 16) & 0xff, (trackId >>> 8) & 0xff, trackId & 0xff, 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes (duration >>> 24) & 0xff, // duration: 4 bytes (duration >>> 16) & 0xff, (duration >>> 8) & 0xff, duration & 0xff, 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // layer(2bytes) + alternate_group(2bytes) 0x00, 0x00, 0x00, 0x00, // volume(2bytes) + reserved(2bytes) 0x00, 0x01, 0x00, 0x00, // ----begin composition matrix---- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // ----end composition matrix---- (width >>> 8) & 0xff, // width and height width & 0xff, 0x00, 0x00, (height >>> 8) & 0xff, height & 0xff, 0x00, 0x00 ]) ); } // Media Box static mdia(meta: track) { return MP4.box(MP4.types.mdia, MP4.mdhd(meta), MP4.hdlr(meta), MP4.minf(meta)); } // Media header box static mdhd(meta: track) { const { timescale } = meta; const duration = meta.duration || 0; return MP4.box( MP4.types.mdhd, new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags 0x00, 0x00, 0x00, 0x00, // creation_time 0x00, 0x00, 0x00, 0x00, // modification_time (timescale >>> 24) & 0xff, // timescale: 4 bytes (timescale >>> 16) & 0xff, (timescale >>> 8) & 0xff, timescale & 0xff, (duration >>> 24) & 0xff, // duration: 4 bytes (duration >>> 16) & 0xff, (duration >>> 8) & 0xff, duration & 0xff, 0x55, 0xc4, // language: und (undetermined) 0x00, 0x00 // pre_defined = 0 ]) ); } // Media handler reference box static hdlr(meta: track) { let data = null; if(meta.type === 'audio') { data = MP4.HDLR_AUDIO; } else { data = MP4.HDLR_VIDEO; } return MP4.box(MP4.types.hdlr, data); } // Media infomation box static minf(meta: track) { let xmhd = null; if(meta.type === 'audio') { xmhd = MP4.box(MP4.types.smhd, MP4.SMHD); } else { xmhd = MP4.box(MP4.types.vmhd, MP4.VMHD); } return MP4.box(MP4.types.minf, xmhd, MP4.dinf(), MP4.stbl(meta)); } // Data infomation box static dinf() { const result = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, MP4.DREF)); return result; } // Sample table box static stbl(meta: track) { const result = MP4.box( MP4.types.stbl, // type: stbl MP4.stsd(meta), // Sample Description Table MP4.box(MP4.types.stts, MP4.STTS), // Time-To-Sample MP4.box(MP4.types.stsc, MP4.STSC), // Sample-To-Chunk MP4.box(MP4.types.stsz, MP4.STSZ), // Sample size MP4.box(MP4.types.stco, MP4.STCO) // Chunk offset ); return result; } // Sample description box static stsd(meta: track) { if(meta.type === 'audio') { if(meta.codec === 'mp3') { return MP4.box(MP4.types.stsd, MP4.STSD_PREFIX, MP4.mp3(meta)); } // else: aac -> mp4a return MP4.box(MP4.types.stsd, MP4.STSD_PREFIX, MP4.mp4a(meta)); } return MP4.box(MP4.types.stsd, MP4.STSD_PREFIX, MP4.avc1(meta)); } static mp3(meta: track) { const { channelCount } = meta; const sampleRate = meta.audioSampleRate; const data = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // reserved(4) 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2) 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2) 0x00, 0x10, // sampleSize(2) 0x00, 0x00, 0x00, 0x00, // reserved(4) (sampleRate >>> 8) & 0xff, // Audio sample rate sampleRate & 0xff, 0x00, 0x00 ]); return MP4.box(MP4.types['.mp3'], data); } static mp4a(meta: track) { const { channelCount } = meta; const sampleRate = meta.audioSampleRate; const data = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // reserved(4) 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2) 0x00, 0x00, 0x00, 0x00, // reserved: 2 * 4 bytes 0x00, 0x00, 0x00, 0x00, 0x00, channelCount, // channelCount(2) 0x00, 0x10, // sampleSize(2) 0x00, 0x00, 0x00, 0x00, // reserved(4) (sampleRate >>> 8) & 0xff, // Audio sample rate sampleRate & 0xff, 0x00, 0x00 ]); return MP4.box(MP4.types.mp4a, data, MP4.esds(meta)); } static esds(meta: track) { const config = meta.config || []; const configSize = config.length; const data = new Uint8Array( [ 0x00, 0x00, 0x00, 0x00, // version 0 + flags 0x03, // descriptor_type 0x17 + configSize, // length3 0x00, 0x01, // es_id 0x00, // stream_priority 0x04, // descriptor_type 0x0f + configSize, // length 0x40, // codec: mpeg4_audio 0x15, // stream_type: Audio 0x00, 0x00, 0x00, // buffer_size 0x00, 0x00, 0x00, 0x00, // maxBitrate 0x00, 0x00, 0x00, 0x00, // avgBitrate 0x05 // descriptor_type ] .concat([configSize]) .concat(config) .concat([ 0x06, 0x01, 0x02 // GASpecificConfig ]) ); return MP4.box(MP4.types.esds, data); } static avc1(meta: track) { const { avcc } = meta; const width = meta.codecWidth; const height = meta.codecHeight; const data = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // reserved(4) 0x00, 0x00, 0x00, 0x01, // reserved(2) + data_reference_index(2) 0x00, 0x00, 0x00, 0x00, // pre_defined(2) + reserved(2) 0x00, 0x00, 0x00, 0x00, // pre_defined: 3 * 4 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (width >>> 8) & 0xff, // width: 2 bytes width & 0xff, (height >>> 8) & 0xff, // height: 2 bytes height & 0xff, 0x00, 0x48, 0x00, 0x00, // horizresolution: 4 bytes 0x00, 0x48, 0x00, 0x00, // vertresolution: 4 bytes 0x00, 0x00, 0x00, 0x00, // reserved: 4 bytes 0x00, 0x01, // frame_count 0x0a, // strlen 0x78, 0x71, 0x71, 0x2f, // compressorname: 32 bytes 0x66, 0x6c, 0x76, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, // depth 0xff, 0xff // pre_defined = -1 ]); return MP4.box(MP4.types.avc1, data, MP4.box(MP4.types.avcC, avcc)); } // Movie Extends box static mvex(meta: track) { return MP4.box(MP4.types.mvex, MP4.trex(meta)); } // Track Extends box static trex(meta: track) { const trackId = meta.id; const data = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) + flags (trackId >>> 24) & 0xff, // track_ID (trackId >>> 16) & 0xff, (trackId >>> 8) & 0xff, trackId & 0xff, 0x00, 0x00, 0x00, 0x01, // default_sample_description_index 0x00, 0x00, 0x00, 0x00, // default_sample_duration 0x00, 0x00, 0x00, 0x00, // default_sample_size 0x00, 0x01, 0x00, 0x01 // default_sample_flags ]); return MP4.box(MP4.types.trex, data); } // Movie fragment box static moof(track: track, baseMediaDecodeTime: number) { return MP4.box( MP4.types.moof, MP4.mfhd(track.sequenceNumber), MP4.traf(track, baseMediaDecodeTime) ); } static mfhd(sequenceNumber: number) { const data = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, (sequenceNumber >>> 24) & 0xff, // sequence_number: int32 (sequenceNumber >>> 16) & 0xff, (sequenceNumber >>> 8) & 0xff, sequenceNumber & 0xff ]); return MP4.box(MP4.types.mfhd, data); } // Track fragment box static traf(track: track, baseMediaDecodeTime: number) { const trackId = track.id; // Track fragment header box const tfhd = MP4.box( MP4.types.tfhd, new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) & flags (trackId >>> 24) & 0xff, // track_ID (trackId >>> 16) & 0xff, (trackId >>> 8) & 0xff, trackId & 0xff ]) ); // Track Fragment Decode Time const tfdt = MP4.box( MP4.types.tfdt, new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // version(0) & flags (baseMediaDecodeTime >>> 24) & 0xff, // baseMediaDecodeTime: int32 (baseMediaDecodeTime >>> 16) & 0xff, (baseMediaDecodeTime >>> 8) & 0xff, baseMediaDecodeTime & 0xff ]) ); const sdtp = MP4.sdtp(track); const trun = MP4.trun(track, sdtp.byteLength + 16 + 16 + 8 + 16 + 8 + 8); return MP4.box(MP4.types.traf, tfhd, tfdt, trun, sdtp); } // Sample Dependency Type box static sdtp(track: track) { const samples = track.samples || []; const sampleCount = samples.length; const data = new Uint8Array(4 + sampleCount); // 0~4 bytes: version(0) & flags for(let i = 0; i < sampleCount; i++) { const { flags } = samples[i]; data[i + 4] = (flags.isLeading << 6) // is_leading: 2 (bit) | (flags.dependsOn << 4) // sample_depends_on | (flags.isDependedOn << 2) // sample_is_depended_on | flags.hasRedundancy; // sample_has_redundancy } return MP4.box(MP4.types.sdtp, data); } // Track fragment run box static trun(track: track, offset: number) { const samples = track.samples || []; const sampleCount = samples.length; const dataSize = 12 + 16 * sampleCount; const data = new Uint8Array(dataSize); offset += 8 + dataSize; data.set( [ 0x00, 0x00, 0x0f, 0x01, // version(0) & flags (sampleCount >>> 24) & 0xff, // sample_count (sampleCount >>> 16) & 0xff, (sampleCount >>> 8) & 0xff, sampleCount & 0xff, (offset >>> 24) & 0xff, // data_offset (offset >>> 16) & 0xff, (offset >>> 8) & 0xff, offset & 0xff ], 0 ); for(let i = 0; i < sampleCount; i++) { const { duration } = samples[i]; const { size } = samples[i]; const { flags } = samples[i]; const { cts } = samples[i]; data.set( [ (duration >>> 24) & 0xff, // sample_duration (duration >>> 16) & 0xff, (duration >>> 8) & 0xff, duration & 0xff, (size >>> 24) & 0xff, // sample_size (size >>> 16) & 0xff, (size >>> 8) & 0xff, size & 0xff, (flags.isLeading << 2) | flags.dependsOn, // sample_flags (flags.isDependedOn << 6) | (flags.hasRedundancy << 4) | flags.isNonSync, 0x00, 0x00, // sample_degradation_priority (cts >>> 24) & 0xff, // sample_composition_time_offset (cts >>> 16) & 0xff, (cts >>> 8) & 0xff, cts & 0xff ], 12 + 16 * i ); } return MP4.box(MP4.types.trun, data); } static mdat(data: any) { return MP4.box(MP4.types.mdat, data); } } MP4.init(); export default MP4;
the_stack
import { GameConfiguration, Module, PathUtil, Scene, XorshiftRandomGenerator } from ".."; import { customMatchers, Game } from "./helpers"; expect.extend(customMatchers); describe("test Module", () => { function resolveGameConfigurationPath(gameConfiguration: any, pathConverter: any): any { function objectMap(obj: any, f: any): any { const o: any = {}; Object.keys(obj).forEach(k => { o[k] = f(k, obj[k]); }); return o; } return objectMap(gameConfiguration, (k: any, v: any): any => { switch (k) { case "assets": return objectMap(v, (_k: any, asset: any) => { return objectMap(asset, (k: any, v: any) => (k === "path" ? pathConverter(v) : v)); }); case "main": return pathConverter(v); default: return v; } }); } const gameConfiguration: GameConfiguration = { width: 320, height: 320, fps: 30, main: "/script/foo.js", assets: { aGlobalAssetFoo: { type: "script", global: true, path: "/script/foo.js", virtualPath: "script/foo.js" }, aNonGlobalAssetBar: { type: "script", path: "/script/bar.js", virtualPath: "script/bar.js" }, // dummy modules dummymod: { type: "script", global: true, path: "/script/dummypath.js", virtualPath: "script/dummypath.js" }, cascaded: { type: "script", global: true, path: "/cascaded/script.js", virtualPath: "script/cascaded.js" }, moduleid: { type: "script", global: true, path: "/path/to/the/module.js", virtualPath: "path/to/the/module.js" }, // basic "node_modules/noPackageJson/index.js": { type: "script", path: "/node_modules/noPackageJson/index.js", virtualPath: "node_modules/noPackageJson/index.js", global: true }, "node_modules/noDefaultIndex/root.js": { type: "script", path: "/node_modules/noDefaultIndex/root.js", virtualPath: "node_modules/noDefaultIndex/root.js", global: true }, "node_modules/noDefaultIndex/package.json": { type: "text", path: "/node_modules/noDefaultIndex/package.json", virtualPath: "node_modules/noDefaultIndex/package.json", global: true }, "node_modules/wrongPackageJsonMain/package.json": { type: "text", path: "/node_modules/wrongPackageJsonMain/package.json", virtualPath: "node_modules/wrongPackageJsonMain/package.json", global: true }, "node_modules/wrongPackageJsonMain/index.js": { type: "script", path: "/node_modules/wrongPackageJsonMain/index.js", virtualPath: "node_modules/wrongPackageJsonMain/index.js", global: true }, "node_modules/wrongPackageJsonMain/aJsonFile.json": { type: "text", path: "/node_modules/wrongPackageJsonMain/aJsonFile.json", virtualPath: "node_modules/wrongPackageJsonMain/aJsonFile.json", global: true }, // directory structure "script/useA.js": { type: "script", path: "/script/useA.js", virtualPath: "script/useA.js", global: true }, "node_modules/moduleUsesA/index.js": { type: "script", path: "/node_modules/moduleUsesA/index.js", virtualPath: "node_modules/moduleUsesA/index.js", global: true }, "node_modules/moduleUsesA/node_modules/libraryA/index.js": { type: "script", path: "/node_modules/moduleUsesA/node_modules/libraryA/index.js", virtualPath: "node_modules/moduleUsesA/node_modules/libraryA/index.js", global: true }, "node_modules/moduleUsesA/node_modules/libraryA/lib/foo/foo.js": { type: "script", path: "/node_modules/moduleUsesA/node_modules/libraryA/lib/foo/foo.js", virtualPath: "node_modules/moduleUsesA/node_modules/libraryA/lib/foo/foo.js", global: true }, "node_modules/libraryA/index.js": { type: "script", path: "/node_modules/libraryA/index.js", virtualPath: "node_modules/libraryA/index.js", global: true }, // cyclic "node_modules/cyclic1/index.js": { type: "script", path: "/node_modules/cyclic1/index.js", virtualPath: "node_modules/cyclic1/index.js", global: true }, "node_modules/cyclic1/node_modules/cyclic2/index.js": { type: "script", path: "/node_modules/cyclic1/node_modules/cyclic2/index.js", virtualPath: "node_modules/cyclic1/node_modules/cyclic2/index.js", global: true }, "node_modules/cyclic1/node_modules/cyclic3/index.js": { type: "script", path: "/node_modules/cyclic1/node_modules/cyclic3/index.js", virtualPath: "node_modules/cyclic1/node_modules/cyclic3/index.js", global: true }, // virtual path altering directory "script/realpath.js": { type: "script", path: "/script/realpath.js", virtualPath: "script/some/deep/vpath.js", global: true }, // cache "script/cache1.js": { type: "script", path: "/script/cache1.js", virtualPath: "script/cache1.js", global: true }, "script/cache2.js": { type: "script", path: "/script/cache2.js", virtualPath: "script/cache2.js", global: true }, "node_modules/randomnumber/index.js": { type: "script", path: "/node_modules/randomnumber/index.js", virtualPath: "node_modules/randomnumber/index.js", global: true }, "node_modules/noPackageJsonModule/hoge.js": { type: "script", path: "/node_modules/noPackageJsonModule/real_hoge.js", virtualPath: "node_modules/noPackageJsonModule/hoge.js", global: true }, "node_modules/noPackageJsonModule/fuga.js": { type: "script", path: "/node_modules/noPackageJsonModule/real_fuga.js", virtualPath: "node_modules/noPackageJsonModule/fuga.js", global: true }, // require.resolve "script/resolve1.js": { type: "script", path: "/script/resolve1.js", virtualPath: "script/resolve1.js", global: true }, "script/resolve2.js": { type: "script", path: "/script/resolve2.js", virtualPath: "script/resolve2.js", global: true }, "node_modules/externalResolvedModule/index.js": { type: "script", path: "/node_modules/externalResolvedModule/index.js", virtualPath: "node_modules/externalResolvedModule/index.js", global: true }, dummydata: { type: "text", path: "/text/dummydata.txt", virtualPath: "text/dummydata.txt" } }, moduleMainScripts: { noPackageJsonModule: "node_modules/noPackageJsonModule/hoge.js", externalResolvedModule: "node_modules/externalResolvedModule/index.js" } }; const scriptContents: { [path: string]: string } = { // basic "/script/foo.js": "module.exports = { me: 'script-foo', thisModule: module }", "/script/bar.js": "module.exports = { me: 'script-bar', thisModule: module }", "/script/dummypath.js": "module.exports = { me: 'script-dummymod', thisModule: module }", "/cascaded/script.js": "module.exports = { me: 'script-cascaded', thisModule: module }", "/node_modules/noPackageJson/index.js": "module.exports = { me: 'noPackageJson-index', thisModule: module };", "/node_modules/noDefaultIndex/root.js": "exports.me = 'noDefaultIndex-root'; exports.thisModule = module; ", "/node_modules/noDefaultIndex/package.json": '{ "main": "root.js" }', "/node_modules/wrongPackageJsonMain/package.json": '{ "main": "__not_exists__.js" }', "/node_modules/wrongPackageJsonMain/index.js": "module.exports = { me: 'wrongPackageJsonMain-index', thisModule: module };", "/node_modules/wrongPackageJsonMain/aJsonFile.json": "{ 'aJsonFile': 'aValue' }", "/node_modules/noPackageJsonModule/real_hoge.js": "module.exports = { me: 'noPackageJsonModule', thisModule: module }", "/node_modules/noPackageJsonModule/real_fuga.js": "module.exports = { me: 'dummy'}", // directory structure "/script/useA.js": [ "const modUsesA = require('moduleUsesA');", "const libA = require('libraryA');", "module.exports = { 'me': 'script-useA', thisModule: module, libraryA: libA, moduleUsesA: modUsesA }; " ].join("\n"), "/node_modules/moduleUsesA/index.js": [ "const libA = require('libraryA');", "module.exports = { 'me': 'moduleUsesA-index', thisModule: module, libraryA: libA };" ].join("\n"), "/node_modules/moduleUsesA/node_modules/libraryA/index.js": [ "const foo = require('./lib/foo/foo');", "module.exports = { 'me': 'moduleUsesALibraryA-index', thisModule: module, foo: foo };" ].join("\n"), "/node_modules/moduleUsesA/node_modules/libraryA/lib/foo/foo.js": "module.exports = { me: 'moduleUsesALibraryA-lib-foo-foo', thisModule: module };", "/node_modules/libraryA/index.js": "module.exports = { me: 'libraryA-index', thisModule: module };", // cyclic "/node_modules/cyclic1/index.js": [ "module.exports = 'notyet';", "const c2 = require('cyclic2');", "const c3 = require('cyclic3');", "module.exports = {", " me: 'cyclic1',", " thisModule: module,", " c2: c2,", " c2loaded: c2.thisModule.loaded,", " c3: c3,", " c3loaded: c3.thisModule.loaded,", "};" ].join("\n"), "/node_modules/cyclic1/node_modules/cyclic2/index.js": [ "const c3 = require('cyclic3');", "module.exports = { me: 'cyclic2', thisModule: module, c3: c3, c3loaded: c3.thisModule.loaded };" ].join("\n"), "/node_modules/cyclic1/node_modules/cyclic3/index.js": [ "const c1 = require('cyclic1');", "module.exports = { me: 'cyclic3', thisModule: module, c1: c1 };" ].join("\n"), // virtual path altering directory "script/some/deep/realpath.js": "module.exports = { me: 'realpath', thisModule: module}", // cache "/script/cache1.js": "module.exports = { v1: require('randomnumber'), v2: require('randomnumber'), cache2: require('./cache2.js') };", "/script/cache2.js": "module.exports = { v1: require('randomnumber'), v2: require('randomnumber') };", "/node_modules/randomnumber/index.js": "module.exports = g.game.random.generate();", // require.resolve "/script/resolve1.js": [ "module.exports = [", " require.resolve('./resolve2'),", // relative file path (.js) " require.resolve('../text/dummydata.txt'),", // relative file path " require.resolve('libraryA'),", // external module " require('externalResolvedModule').resolvedPathAsDirectory,", // as a directory path in the external module " require('externalResolvedModule').resolvedPathAsFile,", // as a file path in the external module " require('externalResolvedModule').resolvedPathAsExtModule,", // as a external module in the external module "];" ].join("\n"), "/script/resolve2.js": "module.exports = {};", "/node_modules/externalResolvedModule/index.js": [ "module.exports = {", " resolvedPathAsDirectory: require.resolve('./'),", " resolvedPathAsFile: require.resolve('./index.js'),", " resolvedPathAsExtModule: require.resolve('libraryA'),", "};" ].join("\n"), "/text/dummydata.txt": "dummydata" }; it("初期化", done => { const path = "/path/to/the/module.js"; const dirname = "/path/to/the"; const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; game.resourceFactory.scriptContents = scriptContents; game._onLoad.add(() => { const module = new Module({ id: "moduleid", path, virtualPath: path, requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule), runtimeValueBase: game._runtimeValueBase }); expect(module.id).toBe("moduleid"); expect(module.filename).toBe(path); expect(module.exports instanceof Object).toBe(true); expect(module.parent).toBe(null); expect(module.loaded).toBe(false); expect(module.children).toEqual([]); expect(module.paths).toEqual(["/path/to/the/node_modules", "/path/to/node_modules", "/path/node_modules", "/node_modules"]); expect(module.require instanceof Function).toBe(true); expect(() => { module.require.resolve("../not/exists"); }).toThrowError("AssertionError"); expect(module._dirname).toBe(dirname); expect(module._runtimeValue.game).toBe(game); expect(module._runtimeValue.filename).toBe(path); expect(module._runtimeValue.dirname).toBe(dirname); expect(module._runtimeValue.module).toBe(module); done(); }); game._startLoadingGlobalAssets(); }); it("g._require()", done => { const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; game.resourceFactory.scriptContents = scriptContents; game._onLoad.add(() => { const mod = manager._require("noPackageJson"); expect(mod.me).toBe("noPackageJson-index"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/node_modules/noPackageJson/index.js"); done(); }); game._startLoadingGlobalAssets(); }); it("require - basic", done => { const game = new Game(gameConfiguration, "./"); const manager = game._moduleManager; const path = "/script/dummypath.js"; game.resourceFactory.scriptContents = scriptContents; game._onLoad.add(() => { const module = new Module({ id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], runtimeValueBase: game._runtimeValueBase, requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); let mod = module.require("./foo"); expect(mod.me).toBe("script-foo"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/script/foo.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); mod = module.require("noPackageJson"); expect(mod.me).toBe("noPackageJson-index"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/node_modules/noPackageJson/index.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); mod = module.require("noDefaultIndex"); expect(mod.me).toBe("noDefaultIndex-root"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/node_modules/noDefaultIndex/root.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); mod = module.require("wrongPackageJsonMain"); expect(mod.me).toBe("wrongPackageJsonMain-index"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/node_modules/wrongPackageJsonMain/index.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); mod = module.require("aGlobalAssetFoo"); expect(mod.me).toBe("script-foo"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/script/foo.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); mod = module.require("noPackageJsonModule"); expect(mod.me).toBe("noPackageJsonModule"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/node_modules/noPackageJsonModule/real_hoge.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); expect(() => { module.require("aNonGlobalAssetBar"); }).toThrowError("AssertionError"); const scene = new Scene({ game: game, assetIds: ["aNonGlobalAssetBar"] }); scene.onLoad.add(() => { let mod = module.require("aNonGlobalAssetBar"); expect(mod.me).toBe("script-bar"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/script/bar.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); mod = module.require("./bar"); expect(mod.me).toBe("script-bar"); game.popScene(); game._flushPostTickTasks(); expect(() => { module.require("aNonGlobalAssetBar"); }).toThrowError("AssertionError"); done(); }); game.pushScene(scene); game._flushPostTickTasks(); }); game._startLoadingGlobalAssets(); }); it("require - basic/URL", done => { const assetBase = "http://some.where"; const scripts: { [path: string]: string } = {}; Object.keys(scriptContents).forEach(k => { scripts[assetBase + k] = scriptContents[k]; }); const conf = resolveGameConfigurationPath(gameConfiguration, (p: any) => { return PathUtil.resolvePath(assetBase, p); }); const game = new Game(conf, assetBase + "/"); const manager = game._moduleManager; const path = assetBase + "/script/dummypath.js"; game.resourceFactory.scriptContents = scripts; game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); let mod = module.require("./foo"); expect(mod.me).toBe("script-foo"); expect(mod.thisModule.filename).toBe(assetBase + "/script/foo.js"); mod = module.require("noPackageJson"); expect(mod.me).toBe("noPackageJson-index"); expect(mod.thisModule.filename).toBe(assetBase + "/node_modules/noPackageJson/index.js"); mod = module.require("noDefaultIndex"); expect(mod.me).toBe("noDefaultIndex-root"); expect(mod.thisModule.filename).toBe(assetBase + "/node_modules/noDefaultIndex/root.js"); mod = module.require("wrongPackageJsonMain"); expect(mod.me).toBe("wrongPackageJsonMain-index"); expect(mod.thisModule.filename).toBe(assetBase + "/node_modules/wrongPackageJsonMain/index.js"); mod = module.require("aGlobalAssetFoo"); expect(mod.me).toBe("script-foo"); expect(mod.thisModule.filename).toBe(assetBase + "/script/foo.js"); expect(() => { module.require("aNonGlobalAssetBar"); }).toThrowError("AssertionError"); const scene = new Scene({ game: game, assetIds: ["aNonGlobalAssetBar"] }); scene.onLoad.add(() => { let mod = module.require("aNonGlobalAssetBar"); expect(mod.me).toBe("script-bar"); expect(mod.thisModule.filename).toBe(assetBase + "/script/bar.js"); mod = module.require("./bar"); expect(mod.me).toBe("script-bar"); game.popScene(); game._flushPostTickTasks(); expect(() => { module.require("aNonGlobalAssetBar"); }).toThrowError("AssertionError"); done(); }); game.pushScene(scene); game._flushPostTickTasks(); }); game._startLoadingGlobalAssets(); }); it("require - basic/relative", done => { const assetBase = "."; const scripts: any = {}; Object.keys(scriptContents).forEach(k => { scripts[assetBase + k] = scriptContents[k]; }); const conf = resolveGameConfigurationPath(gameConfiguration, (p: any) => { return assetBase + p; }); const game = new Game(conf, assetBase + "/"); const manager = game._moduleManager; const path = assetBase + "/script/dummypath.js"; game.resourceFactory.scriptContents = scripts; game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); let mod = module.require("./foo"); expect(mod.me).toBe("script-foo"); expect(mod.thisModule.filename).toBe(assetBase + "/script/foo.js"); mod = module.require("noPackageJson"); expect(mod.me).toBe("noPackageJson-index"); expect(mod.thisModule.filename).toBe(assetBase + "/node_modules/noPackageJson/index.js"); mod = module.require("noDefaultIndex"); expect(mod.me).toBe("noDefaultIndex-root"); expect(mod.thisModule.filename).toBe(assetBase + "/node_modules/noDefaultIndex/root.js"); mod = module.require("wrongPackageJsonMain"); expect(mod.me).toBe("wrongPackageJsonMain-index"); expect(mod.thisModule.filename).toBe(assetBase + "/node_modules/wrongPackageJsonMain/index.js"); mod = module.require("aGlobalAssetFoo"); expect(mod.me).toBe("script-foo"); expect(mod.thisModule.filename).toBe(assetBase + "/script/foo.js"); expect(() => { module.require("aNonGlobalAssetBar"); }).toThrowError("AssertionError"); const scene = new Scene({ game: game, assetIds: ["aNonGlobalAssetBar"] }); scene.onLoad.add(() => { let mod = module.require("aNonGlobalAssetBar"); expect(mod.me).toBe("script-bar"); expect(mod.thisModule.filename).toBe(assetBase + "/script/bar.js"); mod = module.require("./bar"); expect(mod.me).toBe("script-bar"); game.popScene(); game._flushPostTickTasks(); expect(() => { module.require("aNonGlobalAssetBar"); }).toThrowError("AssertionError"); done(); }); game.pushScene(scene); game._flushPostTickTasks(); }); game._startLoadingGlobalAssets(); }); it("require - directory structure", done => { const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; const path = "/script/dummypath.js"; game.resourceFactory.scriptContents = scriptContents; game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); const useA = module.require("./useA.js"); expect(useA.me).toBe("script-useA"); expect(useA.thisModule instanceof Module).toBe(true); expect(useA.thisModule.filename).toBe("/script/useA.js"); expect(useA.thisModule.parent).toBe(module); expect(useA.thisModule.children.length).toBe(2); expect(useA.thisModule.children[0] instanceof Module).toBe(true); expect(useA.thisModule.children[0].exports).toBe(useA.moduleUsesA); expect(useA.thisModule.children[1] instanceof Module).toBe(true); expect(useA.thisModule.children[1].exports).toBe(useA.libraryA); expect(useA.thisModule.loaded).toBe(true); const moduleUsesA = useA.moduleUsesA; expect(moduleUsesA.me).toBe("moduleUsesA-index"); expect(moduleUsesA.thisModule.parent).toBe(useA.thisModule); expect(moduleUsesA.thisModule.children.length).toBe(1); expect(moduleUsesA.thisModule.children[0] instanceof Module).toBe(true); expect(moduleUsesA.thisModule.children[0].exports).toBe(moduleUsesA.libraryA); expect(moduleUsesA.thisModule.loaded).toBe(true); const moduleUsesALibraryA = moduleUsesA.libraryA; expect(moduleUsesALibraryA.me).toBe("moduleUsesALibraryA-index"); expect(moduleUsesALibraryA.thisModule.parent).toBe(moduleUsesA.thisModule); expect(moduleUsesALibraryA.thisModule.children.length).toBe(1); expect(moduleUsesALibraryA.thisModule.children[0] instanceof Module).toBe(true); expect(moduleUsesALibraryA.thisModule.children[0].exports).toBe(moduleUsesALibraryA.foo); expect(moduleUsesALibraryA.thisModule.loaded).toBe(true); const moduleUsesALibraryAFoo = moduleUsesALibraryA.foo; expect(moduleUsesALibraryAFoo.me).toBe("moduleUsesALibraryA-lib-foo-foo"); expect(moduleUsesALibraryAFoo.thisModule.parent).toBe(moduleUsesALibraryA.thisModule); expect(moduleUsesALibraryAFoo.thisModule.children.length).toBe(0); expect(moduleUsesALibraryAFoo.thisModule.loaded).toBe(true); const libraryA = useA.libraryA; expect(libraryA.me).toBe("libraryA-index"); expect(libraryA.thisModule.parent).toBe(useA.thisModule); expect(libraryA.thisModule.children.length).toBe(0); expect(libraryA.thisModule.loaded).toBe(true); expect(moduleUsesALibraryA).not.toBe(libraryA); done(); }); game._startLoadingGlobalAssets(); }); it("require - directory structure/URL", done => { const assetBase = "http://some.where"; const scripts: any = {}; Object.keys(scriptContents).forEach((k: any) => { scripts[assetBase + k] = scriptContents[k]; }); const conf = resolveGameConfigurationPath(gameConfiguration, (p: any) => { return PathUtil.resolvePath(assetBase, p); }); const game = new Game(conf, assetBase + "/"); const manager = game._moduleManager; const path = assetBase + "/script/dummypath.js"; game.resourceFactory.scriptContents = scripts; game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); const useA = module.require("./useA.js"); expect(useA.me).toBe("script-useA"); expect(useA.thisModule.filename).toBe(assetBase + "/script/useA.js"); expect(useA.thisModule.children[0].exports).toBe(useA.moduleUsesA); expect(useA.thisModule.children[1].exports).toBe(useA.libraryA); const moduleUsesA = useA.moduleUsesA; expect(moduleUsesA.me).toBe("moduleUsesA-index"); expect(moduleUsesA.thisModule.children[0].exports).toBe(moduleUsesA.libraryA); const moduleUsesALibraryA = moduleUsesA.libraryA; expect(moduleUsesALibraryA.me).toBe("moduleUsesALibraryA-index"); expect(moduleUsesALibraryA.thisModule.children[0].exports).toBe(moduleUsesALibraryA.foo); const moduleUsesALibraryAFoo = moduleUsesALibraryA.foo; expect(moduleUsesALibraryAFoo.me).toBe("moduleUsesALibraryA-lib-foo-foo"); expect(moduleUsesALibraryAFoo.thisModule.children.length).toBe(0); const libraryA = useA.libraryA; expect(libraryA.me).toBe("libraryA-index"); expect(libraryA.thisModule.children.length).toBe(0); expect(moduleUsesALibraryA).not.toBe(libraryA); done(); }); game._startLoadingGlobalAssets(); }); it("require - cyclic", done => { const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; const path = "/script/dummypath.js"; game.resourceFactory.scriptContents = scriptContents; game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); const c1 = module.require("cyclic1"); expect(c1.me).toBe("cyclic1"); expect(c1.thisModule instanceof Module).toBe(true); expect(c1.thisModule.children.length).toBe(1); expect(c1.thisModule.children[0].exports).toBe(c1.c2); expect(c1.c2loaded).toBe(true); expect(c1.c3loaded).toBe(true); const c2 = c1.c2; expect(c2.me).toBe("cyclic2"); expect(c2.thisModule instanceof Module).toBe(true); expect(c2.thisModule.parent).toBe(c1.thisModule); expect(c2.thisModule.children.length).toBe(1); expect(c2.thisModule.children[0].exports).toBe(c1.c3); expect(c2.c3loaded).toBe(true); const c3 = c2.c3; expect(c3.me).toBe("cyclic3"); expect(c3.thisModule instanceof Module).toBe(true); expect(c3.thisModule.parent).toBe(c2.thisModule); expect(c3.thisModule.children.length).toBe(0); expect(c3.c1).toBe("notyet"); done(); }); game._startLoadingGlobalAssets(); }); it("require - virtual path altering directory", done => { const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; const path = "/script/realpath.js"; game.resourceFactory.scriptContents = scriptContents; game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); const mod = module.require("../../foo"); // virtualPath: /script/some/deep/vpath.js からのrequire() expect(mod.me).toBe("script-foo"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/script/foo.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); done(); }); game._startLoadingGlobalAssets(); }); it("require - cache", done => { const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; const path = "/script/dummypath.js"; game.resourceFactory.scriptContents = scriptContents; game.random = new XorshiftRandomGenerator(1); game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); const cache1 = module.require("./cache1"); expect(cache1.v1).toBe(cache1.v2); expect(cache1.v1).toBe(cache1.cache2.v1); expect(cache1.v1).toBe(cache1.cache2.v2); done(); }); game._startLoadingGlobalAssets(); }); it("require - to cascaded module", done => { const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; const path = "/script/dummypath.js"; game.resourceFactory.scriptContents = scriptContents; game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); const mod = module.require("./cascaded"); expect(mod.me).toBe("script-cascaded"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/cascaded/script.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); done(); }); game._startLoadingGlobalAssets(); }); it("require - from cascaded module", done => { const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; const path = "/cascaded/script.js"; game.resourceFactory.scriptContents = scriptContents; game._onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); const mod = module.require("./dummypath"); expect(mod.me).toBe("script-dummymod"); expect(mod.thisModule instanceof Module).toBe(true); expect(mod.thisModule.filename).toBe("/script/dummypath.js"); expect(mod.thisModule.parent).toBe(module); expect(mod.thisModule.children).toEqual([]); expect(mod.thisModule.loaded).toBe(true); done(); }); game._startLoadingGlobalAssets(); }); it("_resolvePath", done => { const game = new Game(gameConfiguration, "/"); const manager = game._moduleManager; const path = "/script/dummypath.js"; game.resourceFactory.scriptContents = scriptContents; game._onLoad.addOnce(() => { const scene = new Scene({ game: game, assetIds: ["dummydata"] }); scene.onLoad.add(() => { const module = new Module({ runtimeValueBase: game._runtimeValueBase, id: "dummymod", path, virtualPath: game._assetManager._liveAssetPathTable[path], requireFunc: (path: string, currentModule?: Module) => manager._require(path, currentModule), resolveFunc: (path: string, currentModule?: Module) => manager._resolvePath(path, currentModule) }); const mod = module.require("./resolve1"); expect(mod).toEqual([ "/script/resolve2.js", "/text/dummydata.txt", "/node_modules/libraryA/index.js", "/node_modules/externalResolvedModule/index.js", "/node_modules/externalResolvedModule/index.js", "/node_modules/libraryA/index.js" ]); done(); }); game.pushScene(scene); game._flushPostTickTasks(); }); game._startLoadingGlobalAssets(); }); it("_findAssetByPathAsFile", () => { const game = new Game({ width: 320, height: 320, main: "", assets: {} }); const manager = game._moduleManager; const liveAssetPathTable = { "foo/bar.js": game.resourceFactory.createScriptAsset("bar", "/foo/bar.js"), "zoo.js": game.resourceFactory.createScriptAsset("zoo", "/zoo.js") }; expect(manager._findAssetByPathAsFile("foo/bar.js", liveAssetPathTable)).toBe(liveAssetPathTable["foo/bar.js"]); expect(manager._findAssetByPathAsFile("foo/bar", liveAssetPathTable)).toBe(liveAssetPathTable["foo/bar.js"]); expect(manager._findAssetByPathAsFile("zoo", liveAssetPathTable)).toBe(liveAssetPathTable["zoo.js"]); expect(manager._findAssetByPathAsFile("zoo/roo.js", liveAssetPathTable)).toBe(undefined); }); it("_findAssetByPathDirectory", done => { const game = new Game({ width: 320, height: 320, main: "", assets: {} }); const pkgJsonAsset = game.resourceFactory.createTextAsset("foopackagejson", "foo/package.json"); const liveAssetPathTable = { "foo/root.js": game.resourceFactory.createScriptAsset("root", "/foo/root.js"), "foo/package.json": pkgJsonAsset, "foo/index.js": game.resourceFactory.createScriptAsset("fooindex", "/foo/index.js"), "bar/index.js": game.resourceFactory.createScriptAsset("barindex", "/bar/index.js"), "zoo/roo/notMain.js": game.resourceFactory.createScriptAsset("zooRooNotMain", "/zoo/roo/notMain.js") }; const manager = game._moduleManager; game.resourceFactory.scriptContents = { "foo/package.json": '{ "main": "root.js" }' }; pkgJsonAsset._load({ _onAssetError: e => { throw e; }, _onAssetLoad: () => { try { expect(manager._findAssetByPathAsDirectory("foo", liveAssetPathTable)).toBe(liveAssetPathTable["foo/root.js"]); expect(manager._findAssetByPathAsDirectory("bar", liveAssetPathTable)).toBe(liveAssetPathTable["bar/index.js"]); expect(manager._findAssetByPathAsDirectory("zoo/roo", liveAssetPathTable)).toBe(undefined); expect(manager._findAssetByPathAsDirectory("tee", liveAssetPathTable)).toBe(undefined); } finally { done(); } } }); }); });
the_stack
interface Rect { top: number; left: number; bottom: number; right: number; width: number; height: number; } interface AnimationState { rect: Rect; target: HTMLElement; } function userAgent(pattern: RegExp): any { if (typeof window !== 'undefined' && window.navigator) { return !!(/*@__PURE__*/ navigator.userAgent.match(pattern)); } } const IE11OrLess = userAgent( /(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i ); // const Edge = userAgent(/Edge/i); // const FireFox = userAgent(/firefox/i); // const Safari = // userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i); // const IOS = userAgent(/iP(ad|od|hone)/i); // const ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i); const AnimationDurtation = 150; const AnimationEasing = 'cubic-bezier(1, 0, 0, 1)'; export class AnimationManager { animating: boolean = false; animationCallbackId: any; states: Array<AnimationState> = []; capture(el: HTMLElement) { // 清空,重复调用,旧的不管了 this.states = []; let children: Array<HTMLElement> = [].slice.call(el.children); children.forEach(child => { // 如果是 ghost if (child.classList.contains('is-ghost')) { return; } const rect = getRect(child)!; // 通常是隐藏节点 if (!rect.width) { return; } let fromRect = {...rect}; const state: AnimationState = { target: child, rect }; // 还在动画中 if ((child as any).thisAnimationDuration) { let childMatrix = matrix(child); if (childMatrix) { fromRect.top -= childMatrix.f; fromRect.left -= childMatrix.e; } } (child as any).fromRect = fromRect; this.states.push(state); }); } animateAll(callback?: () => void) { this.animating = false; let animationTime = 0; this.states.forEach(state => { let time = 0, target = state.target, fromRect = (target as any).fromRect, toRect = { ...getRect(target)! }, prevFromRect = (target as any).prevFromRect, prevToRect = (target as any).prevToRect, animatingRect = state.rect, targetMatrix = matrix(target); if (targetMatrix) { // Compensate for current animation toRect.top -= targetMatrix.f; toRect.left -= targetMatrix.e; } (target as any).toRect = toRect; if ((target as any).thisAnimationDuration) { // Could also check if animatingRect is between fromRect and toRect if ( isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) && // Make sure animatingRect is on line between toRect & fromRect (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left) ) { // If returning to same place as started from animation and on same axis time = calculateRealTime(animatingRect, prevFromRect, prevToRect); } } // if fromRect != toRect: animate if (!isRectEqual(toRect, fromRect)) { (target as any).prevFromRect = fromRect; (target as any).prevToRect = toRect; if (!time) { time = AnimationDurtation; } this.animate(target, animatingRect, toRect, time); } if (time) { this.animating = true; animationTime = Math.max(animationTime, time); clearTimeout((target as any).animationResetTimer); (target as any).animationResetTimer = setTimeout(function () { (target as any).animationTime = 0; (target as any).prevFromRect = null; (target as any).fromRect = null; (target as any).prevToRect = null; (target as any).thisAnimationDuration = null; }, time); (target as any).thisAnimationDuration = time; } }); clearTimeout(this.animationCallbackId); if (!this.animating) { if (typeof callback === 'function') callback(); } else { this.animationCallbackId = setTimeout(() => { this.animating = false; if (typeof callback === 'function') callback(); }, animationTime); } this.states = []; } animate( target: HTMLElement, currentRect: Rect, toRect: Rect, duration: number ) { if (duration) { let affectDisplay = false; css(target, 'transition', ''); css(target, 'transform', ''); let translateX = currentRect.left - toRect.left, translateY = currentRect.top - toRect.top; (target as any).animatingX = !!translateX; (target as any).animatingY = !!translateY; css( target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)' ); if (css(target, 'display') === 'inline') { affectDisplay = true; css(target, 'display', 'inline-block'); } target.offsetWidth; // repaint css( target, 'transition', 'transform ' + duration + 'ms' + (AnimationEasing ? ' ' + AnimationEasing : '') ); css(target, 'transform', 'translate3d(0,0,0)'); typeof (target as any).animated === 'number' && clearTimeout((target as any).animated); (target as any).animated = setTimeout(function () { css(target, 'transition', ''); css(target, 'transform', ''); affectDisplay && css(target, 'display', ''); (target as any).animated = false; (target as any).animatingX = false; (target as any).animatingY = false; }, duration); } } } function matrix(el: HTMLElement) { let appliedTransforms = ''; if (typeof el === 'string') { appliedTransforms = el; } else { let transform = css(el, 'transform'); if (transform && transform !== 'none') { appliedTransforms = transform + ' ' + appliedTransforms; } } const matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || (window as any).CSSMatrix || (window as any).MSCSSMatrix; /*jshint -W056 */ return matrixFn && new matrixFn(appliedTransforms); } function css(el: HTMLElement, prop: string, val?: any) { let style = el && el.style; if (style) { if (val === void 0) { if (document.defaultView && document.defaultView.getComputedStyle) { val = document.defaultView.getComputedStyle(el, ''); } else if ((el as any).currentStyle) { val = (el as any).currentStyle; } return prop === void 0 ? val : val[prop]; } else { if (!(prop in style) && prop.indexOf('webkit') === -1) { prop = '-webkit-' + prop; } (style as any)[prop] = val + (typeof val === 'string' ? '' : 'px'); } } } function isRectEqual(rect1: Rect, rect2: Rect) { return ( Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width) ); } function calculateRealTime(animatingRect: Rect, fromRect: Rect, toRect: Rect) { return ( (Math.sqrt( Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2) ) / Math.sqrt( Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2) )) * AnimationDurtation ); } function getWindowScrollingElement() { let scrollingElement = document.scrollingElement; if (scrollingElement) { return scrollingElement; } else { return document.documentElement; } } function getRect( el: HTMLElement, relativeToContainingBlock?: boolean, relativeToNonStaticParent?: boolean, undoScale?: boolean, container?: HTMLElement ) { if (!el.getBoundingClientRect && (el as any) !== window) return; let elRect, top, left, bottom, right, height, width; if ((el as any) !== window && el !== getWindowScrollingElement()) { elRect = el.getBoundingClientRect(); top = elRect.top; left = elRect.left; bottom = elRect.bottom; right = elRect.right; height = elRect.height; width = elRect.width; } else { top = 0; left = 0; bottom = window.innerHeight; right = window.innerWidth; height = window.innerHeight; width = window.innerWidth; } if ( (relativeToContainingBlock || relativeToNonStaticParent) && (el as any) !== window ) { // Adjust for translate() container = container || (el.parentNode as HTMLElement); // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312) // Not needed on <= IE11 if (!IE11OrLess) { do { if ( container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || (relativeToNonStaticParent && css(container, 'position') !== 'static')) ) { let containerRect = container.getBoundingClientRect(); // Set relative to edges of padding box of container top -= containerRect.top + parseInt(css(container, 'border-top-width')); left -= containerRect.left + parseInt(css(container, 'border-left-width')); bottom = top + (elRect as any).height; right = left + (elRect as any).width; break; } /* jshint boss:true */ } while ((container = container.parentNode as HTMLElement)); } } if (undoScale && (el as any) !== window) { // Adjust for scale() let elMatrix = matrix(container || el), scaleX = elMatrix && elMatrix.a, scaleY = elMatrix && elMatrix.d; if (elMatrix) { top /= scaleY; left /= scaleX; width /= scaleX; height /= scaleY; bottom = top + height; right = left + width; } } return { top: top, left: left, bottom: bottom, right: right, width: width, height: height }; } export default new AnimationManager();
the_stack
import {Constructor, valueof, Number2} from '../../../types/GlobalTypes'; import {WebGLRenderTarget} from 'three/src/renderers/WebGLRenderTarget'; import {ShaderMaterial} from 'three/src/materials/ShaderMaterial'; import {Scene} from 'three/src/scenes/Scene'; import { FloatType, HalfFloatType, RGBAFormat, NearestFilter, LinearFilter, ClampToEdgeWrapping, } from 'three/src/constants'; import {PlaneBufferGeometry} from 'three/src/geometries/PlaneGeometry'; import {Mesh} from 'three/src/objects/Mesh'; import {Camera} from 'three/src/cameras/Camera'; import {TypedCopNode} from './_Base'; // import {CoreGraphNode} from '../../../core/graph/CoreGraphNode'; import {GlobalsGeometryHandler} from '../gl/code/globals/Geometry'; import {GlNodeChildrenMap} from '../../poly/registers/nodes/Gl'; import {BaseGlNodeType} from '../gl/_Base'; import {GlNodeFinder} from '../gl/code/utils/NodeFinder'; import {NodeContext} from '../../poly/NodeContext'; import {IUniform} from 'three/src/renderers/shaders/UniformsLib'; export interface IUniforms { [uniform: string]: IUniform; } const VERTEX_SHADER = ` void main() { gl_Position = vec4( position, 1.0 ); } `; const RESOLUTION_DEFAULT: Number2 = [256, 256]; import {NodeParamsConfig, ParamConfig} from '../utils/params/ParamsConfig'; import {DataTextureController, DataTextureControllerBufferType} from './utils/DataTextureController'; import {CopRendererController} from './utils/RendererController'; import {AssemblerName} from '../../poly/registers/assemblers/_BaseRegister'; import {Poly} from '../../Poly'; import {TexturePersistedConfig} from '../gl/code/assemblers/textures/PersistedConfig'; import {IUniformsWithTime} from '../../scene/utils/UniformsController'; import {ParamsInitData} from '../utils/io/IOController'; import {isBooleanTrue} from '../../../core/BooleanValue'; import {CoreUserAgent} from '../../../core/UserAgent'; class BuilderCopParamsConfig extends NodeParamsConfig { /** @param texture resolution */ resolution = ParamConfig.VECTOR2(RESOLUTION_DEFAULT); /** @param defines if the shader is rendered via the same camera used to render the scene */ useCameraRenderer = ParamConfig.BOOLEAN(0); } const ParamsConfig = new BuilderCopParamsConfig(); export class BuilderCopNode extends TypedCopNode<BuilderCopParamsConfig> { paramsConfig = ParamsConfig; static type() { return 'builder'; } readonly persisted_config: TexturePersistedConfig = new TexturePersistedConfig(this); protected _assembler_controller = this._create_assembler_controller(); public usedAssembler(): Readonly<AssemblerName.GL_TEXTURE> { return AssemblerName.GL_TEXTURE; } protected _create_assembler_controller() { const assembler_controller = Poly.assemblersRegister.assembler(this, this.usedAssembler()); if (assembler_controller) { const globals_handler = new GlobalsGeometryHandler(); assembler_controller.set_assembler_globals_handler(globals_handler); return assembler_controller; } } get assemblerController() { return this._assembler_controller; } private _texture_mesh: Mesh = new Mesh(new PlaneBufferGeometry(2, 2)); private _fragment_shader: string | undefined; private _uniforms: IUniforms | undefined; public readonly texture_material: ShaderMaterial = new ShaderMaterial({ uniforms: {}, vertexShader: VERTEX_SHADER, fragmentShader: '', }); private _texture_scene: Scene = new Scene(); private _texture_camera: Camera = new Camera(); private _render_target: WebGLRenderTarget | undefined; private _data_texture_controller: DataTextureController | undefined; private _renderer_controller: CopRendererController | undefined; protected _children_controller_context = NodeContext.GL; initializeNode() { this._texture_mesh.material = this.texture_material; this._texture_mesh.scale.multiplyScalar(0.25); this._texture_scene.add(this._texture_mesh); this._texture_camera.position.z = 1; // this ensures the builder recooks when its children are changed // and not just when a material that use it requests it this.addPostDirtyHook('_cook_main_without_inputs_when_dirty', () => { setTimeout(this._cook_main_without_inputs_when_dirty_bound, 0); }); // this.dirtyController.addPostDirtyHook( // '_reset_if_resolution_changed', // this._reset_if_resolution_changed.bind(this) // ); // this.params.onParamsCreated('reset', () => { // this._reset(); // }); } createNode<S extends keyof GlNodeChildrenMap>( node_class: S, params_init_value_overrides?: ParamsInitData ): GlNodeChildrenMap[S]; createNode<K extends valueof<GlNodeChildrenMap>>( node_class: Constructor<K>, params_init_value_overrides?: ParamsInitData ): K; createNode<K extends valueof<GlNodeChildrenMap>>( node_class: Constructor<K>, params_init_value_overrides?: ParamsInitData ): K { return super.createNode(node_class, params_init_value_overrides) as K; } children() { return super.children() as BaseGlNodeType[]; } nodesByType<K extends keyof GlNodeChildrenMap>(type: K): GlNodeChildrenMap[K][] { return super.nodesByType(type) as GlNodeChildrenMap[K][]; } childrenAllowed() { if (this.assemblerController) { return super.childrenAllowed(); } this.scene().markAsReadOnly(this); return false; } private _cook_main_without_inputs_when_dirty_bound = this._cook_main_without_inputs_when_dirty.bind(this); private async _cook_main_without_inputs_when_dirty() { await this.cookController.cookMainWithoutInputs(); } // private _reset_if_resolution_changed(trigger?: CoreGraphNode) { // if (trigger && trigger.graphNodeId() == this.p.resolution.graphNodeId()) { // this._reset(); // } // } async cook() { this.compileIfRequired(); this.renderOnTarget(); } shaders_by_name() { return { fragment: this._fragment_shader, }; } compileIfRequired() { if (this.assemblerController?.compileRequired()) { this.compile(); } } private compile() { const assemblerController = this.assemblerController; if (!assemblerController) { return; } const output_nodes: BaseGlNodeType[] = GlNodeFinder.findOutputNodes(this); if (output_nodes.length > 1) { this.states.error.set('only one output node allowed'); return; } const output_node = output_nodes[0]; if (output_node) { //const param_nodes = GlNodeFinder.find_param_generating_nodes(this); const root_nodes = output_nodes; //.concat(param_nodes); assemblerController.assembler.set_root_nodes(root_nodes); // main compilation assemblerController.assembler.update_fragment_shader(); // receives fragment and uniforms const fragment_shader = assemblerController.assembler.fragment_shader(); const uniforms = assemblerController.assembler.uniforms(); if (fragment_shader && uniforms) { this._fragment_shader = fragment_shader; this._uniforms = uniforms; } BuilderCopNode.handle_dependencies(this, assemblerController.assembler.uniformsTimeDependent()); } if (this._fragment_shader && this._uniforms) { this.texture_material.fragmentShader = this._fragment_shader; this.texture_material.uniforms = this._uniforms; this.texture_material.needsUpdate = true; this.texture_material.uniforms.resolution = { value: this.pv.resolution, }; } assemblerController.post_compile(); } static handle_dependencies(node: BuilderCopNode, time_dependent: boolean, uniforms?: IUniformsWithTime) { // That's actually useless, since this doesn't make the texture recook const scene = node.scene(); const id = node.graphNodeId(); const id_s = `${id}`; if (time_dependent) { // TODO: remove this once the scene knows how to re-render // the render target if it is .uniformsTimeDependent() node.states.timeDependent.forceTimeDependent(); if (uniforms) { scene.uniformsController.addTimeDependentUniformOwner(id_s, uniforms); } } else { node.states.timeDependent.unforceTimeDependent(); scene.uniformsController.removeTimeDependentUniformOwner(id_s); } } // // // RENDER + RENDER TARGET // // async renderOnTarget() { this.createRenderTargetIfRequired(); if (!this._render_target) { return; } this._renderer_controller = this._renderer_controller || new CopRendererController(this); const renderer = await this._renderer_controller.renderer(); const prev_target = renderer.getRenderTarget(); renderer.setRenderTarget(this._render_target); renderer.clear(); renderer.render(this._texture_scene, this._texture_camera); renderer.setRenderTarget(prev_target); if (this._render_target.texture) { if (isBooleanTrue(this.pv.useCameraRenderer)) { this.setTexture(this._render_target.texture); } else { // const w = this.pv.resolution.x; // const h = this.pv.resolution.y; // this._data_texture = this._data_texture || this._create_data_texture(w, h); // renderer.readRenderTargetPixels(this._render_target, 0, 0, w, h, this._data_texture.image.data); // this._data_texture.needsUpdate = true; this._data_texture_controller = this._data_texture_controller || new DataTextureController(DataTextureControllerBufferType.Float32Array); const data_texture = this._data_texture_controller.from_render_target(renderer, this._render_target); this.setTexture(data_texture); } } else { this.cookController.endCook(); } } renderTarget() { return (this._render_target = this._render_target || this._createRenderTarget(this.pv.resolution.x, this.pv.resolution.y)); } private createRenderTargetIfRequired() { if (!this._render_target || !this._renderTargetResolutionValid()) { this._render_target = this._createRenderTarget(this.pv.resolution.x, this.pv.resolution.y); this._data_texture_controller?.reset(); } } private _renderTargetResolutionValid() { if (this._render_target) { const image = this._render_target.texture.image; if (image.width != this.pv.resolution.x || image.height != this.pv.resolution.y) { return false; } else { return true; } } else { return false; } } private _createRenderTarget(width: number, height: number) { if (this._render_target) { const image = this._render_target.texture.image; if (image.width == width && image.height == height) { return this._render_target; } } const wrapS = ClampToEdgeWrapping; const wrapT = ClampToEdgeWrapping; const minFilter = LinearFilter; const magFilter = NearestFilter; var renderTarget = new WebGLRenderTarget(width, height, { wrapS: wrapS, wrapT: wrapT, minFilter: minFilter, magFilter: magFilter, format: RGBAFormat, type: CoreUserAgent.isiOS() ? HalfFloatType : FloatType, stencilBuffer: false, depthBuffer: false, }); Poly.warn('created render target', this.path(), width, height); return renderTarget; } }
the_stack
/// <reference path="../typings/tsd.d.ts" /> import assert = require("assert"); import util = require("util"); import stream = require("stream"); import StringMap = require("../lib/StringMap"); export interface SourceLocation { fileName: string; line: number; column: number; } export function setSourceLocation (loc: SourceLocation, fileName: string, line: number, column: number): void { loc.fileName = fileName; loc.line = line; loc.column = column; } export function hasSourceLocation (loc: SourceLocation): boolean { return loc.fileName !== null; } export class MemValue { constructor(public id: number) {} } export class LValue extends MemValue { } export class SystemReg extends LValue { constructor (id: number, public name: string) {super(id);} toString (): string { return this.name; } } export class Regex { constructor (public pattern: string, public flags: string) {} toString(): string { return `Regex(/${this.pattern}/${this.flags})`; } } /** for null and undefined */ export class SpecialConstantClass { constructor (public name: string) {} toString(): string { return `#${this.name}`; } } export type RValue = MemValue | string | boolean | number | SpecialConstantClass; export class Param extends MemValue { index: number; name: string; variable: Var; constructor(id: number, index: number, name: string, variable: Var) { super(id); this.index = index; this.name = name; this.variable = variable; variable.formalParam = this; } toString() { return `Param(${this.index}/*${this.name}*/)`; } } export class ArgSlot extends MemValue { local: Local = null; constructor (id: number, public index: number) { super(id); } toString() { if (this.local) return this.local.toString(); else return `Arg(${this.index})`; } } export class Var extends LValue { envLevel: number; //< environment nesting level name: string; formalParam: Param = null; // associated formal parameter escapes: boolean = false; constant: boolean = false; accessed: boolean = true; funcRef: FunctionBuilder = null; consRef: FunctionBuilder = null; local: Local = null; // The corresponding local to use if it doesn't escape param: Param = null; // The corresponding param to use if it is constant and doesn't escape envIndex: number = -1; //< index in its environment block, if it escapes constructor(id: number, envLevel: number, name: string) { super(id); this.envLevel = envLevel; this.name = name || ""; } toString() { if (this.local) return this.local.toString(); else if (this.param) return this.param.toString(); else return `Var(env@${this.envLevel}[${this.envIndex}]/*${this.name}*/)`; } } export class Local extends LValue { isTemp: boolean = false; // for users of the module. Has no meaning internally index: number; constructor(id: number, index: number) { super(id); this.index = index; } toString() { return `Local(${this.index})`; } } export var nullValue = new SpecialConstantClass("null"); export var undefinedValue = new SpecialConstantClass("undefined"); export var nullReg = new SystemReg(0, "#nullReg"); export var frameReg = new SystemReg(-1, "#frameReg"); export var argcReg = new SystemReg(-2, "#argcReg"); export var argvReg = new SystemReg(-3, "#argvReg"); export var lastThrownValueReg = new SystemReg(-4, "#lastThrownValue"); export function unwrapImmediate (v: RValue): any { if (v === nullValue) return null; else if (v === undefinedValue) return void 0; else return v; } export function wrapImmediate (v: any): RValue { if (v === void 0) return undefinedValue; else if (v === null) return nullValue; else return v; } export function isImmediate (v: RValue): boolean { switch (typeof v) { case "string": case "boolean": case "number": return true; case "object": return <any>v instanceof SpecialConstantClass; } return false; } export function isString (v: RValue): boolean { return typeof v === "string"; } export function isLValue (v: RValue): LValue { if (<any>v instanceof LValue) return <LValue>v; else return null; } export function isVar (v: RValue): Var { if (<any>v instanceof Var) return <Var>v; else return null; } export function isTempLocal (v: RValue): Local { if (<any>v instanceof Local) { var l = <Local>v; if (l.isTemp) return l; } return null; } // Note: in theory all comparisons can be simulated using only '<' and '=='. // a < b = LESS(a,b) // a > b = LESS(b,a) // a >= b = !LESS(a,b) // a <= b = !LESS(b,a) // a != b = !(a == b) // However things fall apart first when floating point is involved (because comparions between // NaN-s always return false) and second because JavaScript requires left-to-right evaluation and // converting to a primitive value for comparison could cause a function call. export const enum OpCode { // Special CLOSURE, CREATE, CREATE_ARGUMENTS, LOAD_SC, END_TRY, ASM, // Binary STRICT_EQ, STRICT_NE, LOOSE_EQ, LOOSE_NE, LT, LE, GT, GE, IN, INSTANCEOF, SHL_N, SHR_N, ASR_N, ADD, ADD_N, SUB_N, MUL_N, DIV_N, MOD_N, OR_N, XOR_N, AND_N, ASSERT_OBJECT, ASSERT_FUNC, DELETE, // Unary NEG_N, LOG_NOT, BIN_NOT_N, TYPEOF, VOID, TO_NUMBER, TO_STRING, TO_OBJECT, // Assignment ASSIGN, // Property access GET, PUT, // Call CALL, CALLIND, CALLCONS, // Unconditional jumps RET, THROW, GOTO, // Conditional jumps BEGIN_TRY, SWITCH, IF_TRUE, IF_IS_OBJECT, IF_STRICT_EQ, IF_STRICT_NE, IF_LOOSE_EQ, IF_LOOSE_NE, IF_LT, IF_LE, IF_GT, IF_GE, IF_IN, IF_INSTANCEOF, _BINOP_FIRST = STRICT_EQ, _BINOP_LAST = DELETE, _UNOP_FIRST = NEG_N, _UNOP_LAST = TO_OBJECT, _IF_FIRST = IF_TRUE, _IF_LAST = IF_INSTANCEOF, _BINCOND_FIRST = IF_STRICT_EQ, _BINCOND_LAST = IF_INSTANCEOF, _JUMP_FIRST = RET, _JUMP_LAST = IF_INSTANCEOF, } var g_opcodeName: string[] = [ // Special "CLOSURE", "CREATE", "CREATE_ARGUMENTS", "LOAD_SC", "END_TRY", "ASM", // Binary "STRICT_EQ", "STRICT_NE", "LOOSE_EQ", "LOOSE_NE", "LT", "LE", "GT", "GE", "IN", "INSTANCEOF", "SHL_N", "SHR_N", "ASR_N", "ADD", "ADD_N", "SUB_N", "MUL_N", "DIV_N", "MOD_N", "OR_N", "XOR_N", "AND_N", "ASSERT_OBJECT", "ASSERT_FUNC", "DELETE", // Unary "NEG_N", "LOG_NOT", "BIN_NOT_N", "TYPEOF", "VOID", "TO_NUMBER", "TO_STRING", "TO_OBJECT", // Assignment "ASSIGN", // Property access "GET", "PUT", // Call "CALL", "CALLIND", "CALLCONS", // Unconditional jumps "RET", "THROW", "GOTO", // Conditional jumps "BEGIN_TRY", "SWITCH", "IF_TRUE", "IF_IS_OBJECT", "IF_STRICT_EQ", "IF_STRICT_NE", "IF_LOOSE_EQ", "IF_LOOSE_NE", "IF_LT", "IF_LE", "IF_GT", "IF_GE", "IF_IN", "IF_INSTANCEOF", ]; export const enum SysConst { RUNTIME_VAR, ARGUMENTS_LEN, } var g_sysConstName : string[] = [ "RUNTIME_VAR", "ARGUMENTS_LEN", ]; // Note: surprisingly, 'ADD' is not commutative because 'string+x' is not the same as 'x+string' // Ain't dynamic typing great? var g_binOpCommutative: boolean[] = [ true, //STRICT_EQ, true, //STRICT_NE, true, //LOOSE_EQ, true, //LOOSE_NE, false, //LT, false, //LE, false, //GT, false, //GE, false, //SHL, false, //SHR, false, //ASR, false, //ADD, true, //ADD_N, false, //SUB_N true, //MUL, false, //DIV, false, //MOD, true, //OR, true, //XOR, true, //AND, false, //IN, false, //INSTANCEOF ]; export function isCommutative (op: OpCode): boolean { assert(op >= OpCode._BINOP_FIRST && op <= OpCode._BINOP_LAST); return g_binOpCommutative[op - OpCode._BINOP_FIRST]; } export function isBinop (op: OpCode): boolean { return op >= OpCode._BINOP_FIRST && op <= OpCode._BINOP_LAST; } export function isJump (op: OpCode): boolean { return op >= OpCode._JUMP_FIRST && op <= OpCode._JUMP_LAST; } export function isBinopConditional (op: OpCode): boolean { return op >= OpCode._BINOP_FIRST && op <= OpCode._BINOP_FIRST + OpCode._BINCOND_LAST - OpCode._BINCOND_FIRST; } export function binopToBincond (op: OpCode): OpCode { assert(isBinopConditional(op)); return op + OpCode._BINCOND_FIRST - OpCode._BINOP_FIRST; } export function rv2s (v: RValue): string { if (v === null) return ""; else if (typeof v === "string") return "\"" + v + "\""; // FIXME: escaping, etc else return String(v); // FIXME: regex, other types, etc } export function oc2s (op: OpCode): string { return g_opcodeName[op]; } export class Instruction { constructor (public op: OpCode) {} } export class ClosureOp extends Instruction { constructor (public dest: LValue, public funcRef: FunctionBuilder) { super(OpCode.CLOSURE); } toString (): string { return `${rv2s(this.dest)} = ${oc2s(this.op)}(${this.funcRef})`; } } export class LoadSCOp extends Instruction { constructor (public dest: LValue, public sc: SysConst, public arg?: string) { super(OpCode.LOAD_SC); } toString (): string { if (!this.arg) return `${rv2s(this.dest)} = ${oc2s(this.op)}(${g_sysConstName[this.sc]})`; else return `${rv2s(this.dest)} = ${oc2s(this.op)}(${g_sysConstName[this.sc]}, ${this.arg})`; } } export class BinOp extends Instruction { constructor (op: OpCode, public dest: LValue, public src1: RValue, public src2: RValue) { super(op); } toString (): string { if (this.src2 !== null) return `${rv2s(this.dest)} = ${oc2s(this.op)}(${rv2s(this.src1)}, ${rv2s(this.src2)})`; else return `${rv2s(this.dest)} = ${oc2s(this.op)}(${rv2s(this.src1)})`; } } export class UnOp extends BinOp { constructor (op: OpCode, dest: LValue, src: RValue) { super(op, dest, src, null); } } export class AssignOp extends UnOp { constructor (dest: LValue, src: RValue) { super(OpCode.ASSIGN, dest, src); } toString (): string { return `${rv2s(this.dest)} = ${rv2s(this.src1)}`; } } export class PutOp extends Instruction { constructor (public obj: RValue, public propName: RValue, public src: RValue) { super(OpCode.PUT); } toString (): string { return `${oc2s(this.op)}(${rv2s(this.obj)}, ${rv2s(this.propName)}, ${rv2s(this.src)})`; } } export class CallOp extends Instruction { public fileName: string = null; public line: number = 0; public column: number = 0; constructor( op: OpCode, public dest: LValue, public fref: FunctionBuilder, public closure: RValue, public args: ArgSlot[] ) { super(op); } toString (): string { if (this.fref) return `${rv2s(this.dest)} = ${oc2s(this.op)}(${this.fref}, ${this.closure}, [${this.args}])`; else return `${rv2s(this.dest)} = ${oc2s(this.op)}(${this.closure}, [${this.args}])`; } } export class JumpInstruction extends Instruction { constructor (op: OpCode, public label1: Label, public label2: Label) { super(op); } } export class RetOp extends JumpInstruction { constructor (label1: Label, public src: RValue) { super(OpCode.RET, label1, null); } toString (): string { return `${oc2s(this.op)} ${this.label1}, ${rv2s(this.src)}`; } } export class ThrowOp extends JumpInstruction { constructor (public src: RValue) { super(OpCode.THROW, null, null); } toString (): string { return `${oc2s(this.op)} ${rv2s(this.src)}`; } } export class GotoOp extends JumpInstruction { constructor (target: Label) { super(OpCode.GOTO, target, null); } toString(): string { return `${oc2s(this.op)} ${this.label1}`; } } export class BeginTryOp extends JumpInstruction { constructor (public tryId: number, onNormal: Label, onException: Label) { super(OpCode.BEGIN_TRY, onNormal, onException); } toString (): string { return `${oc2s(this.op)}(${this.tryId}) then ${this.label1} exc ${this.label2}`; } } export class EndTryOp extends Instruction { constructor (public tryId: number) { super(OpCode.END_TRY); } toString (): string { return `${oc2s(this.op)}(${this.tryId})`; } } export class SwitchOp extends JumpInstruction { constructor (public selector: RValue, defaultLab: Label, public values: number[], public targets: Label[]) { super(OpCode.SWITCH, null, defaultLab); } toString (): string { var res: string = `${oc2s(this.op)} ${rv2s(this.selector)}`; if (this.label2) res += `,default:${this.label2}`; return res + ",[" + this.values.toString() + "],[" + this.targets.toString() +"]"; } } export class IfOp extends JumpInstruction { constructor (op: OpCode, public src1: RValue, public src2: RValue, onTrue: Label, onFalse: Label) { super(op, onTrue, onFalse); } toString (): string { if (this.src2 !== null) return `${oc2s(this.op)}(${rv2s(this.src1)}, ${rv2s(this.src2)}) ${this.label1} else ${this.label2}`; else return `${oc2s(this.op)}(${rv2s(this.src1)}) ${this.label1} else ${this.label2}`; } } export type AsmPattern = Array<string|number>; export class AsmOp extends Instruction { constructor (public dest: LValue, public bindings: RValue[], public pat: AsmPattern) { super(OpCode.ASM); } toString (): string { return `${rv2s(this.dest)} = ${oc2s(this.op)}([${this.bindings}], [${this.pat}])`; } } export class Label { bb: BasicBlock = null; constructor(public id: number) {} toString() { return `B${this.bb.id}`; } } export class BasicBlock { id: number; body: Instruction[] = []; labels: Label[] = []; succ: Label[] = []; constructor (id: number) { this.id = id; } insertAt (at: number, inst: Instruction): void { this.body.splice(at, 0, inst); } push (inst: Instruction): void { // If the BasicBlock hasn't been "closed" with a jump, just add to the end, // otherwise insert before the jump if (!this.succ.length) this.body.push(inst); else this.body.splice(this.body.length-1, 0, inst) } jump (inst: JumpInstruction): void { assert(!this.succ.length); this.body.push(inst); if (inst.label1) this.succ.push(inst.label1); if (inst.label2) this.succ.push(inst.label2); if (inst.op === OpCode.SWITCH) { var switchOp = <SwitchOp>inst; for ( var i = 0, e = switchOp.targets.length; i < e; ++i ) this.succ.push(switchOp.targets[i]); } } placeLabel (lab: Label): void { assert(!this.body.length); assert(!lab.bb); lab.bb = this; this.labels.push(lab); } } /** * * @param op * @param v1 * @param v2 * @returns RValue folded value or null if the operands cannot be folded at compile time */ export function foldBinary (op: OpCode, v1: RValue, v2: RValue): RValue { if (!isImmediate(v1) || !isImmediate(v2)) return null; var a1: any = unwrapImmediate(v1); var a2: any = unwrapImmediate(v2); var r: any; switch (op) { case OpCode.STRICT_EQ: r = a1 === a2; break; case OpCode.STRICT_NE: r = a1 !== a2; break; case OpCode.LOOSE_EQ: r = a1 == a2; break; case OpCode.LOOSE_NE: r = a1 != a2; break; case OpCode.LT: r = a1 < a2; break; case OpCode.LE: r = a1 <= a2; break; case OpCode.SHL_N: r = a1 << a2; break; case OpCode.SHR_N: r = a1 >> a2; break; case OpCode.ASR_N: r = a1 >>> a2; break; case OpCode.ADD: case OpCode.ADD_N: r = a1 + a2; break; case OpCode.SUB_N: r = a1 - a2; break; case OpCode.MUL_N: r = a1 * a2; break; case OpCode.DIV_N: r = a1 / a2; break; case OpCode.MOD_N: r = a1 % a2; break; case OpCode.OR_N: r = a1 | a2; break; case OpCode.XOR_N: r = a1 ^ a2; break; case OpCode.AND_N: r = a1 & a2; break; case OpCode.IN: return null; case OpCode.INSTANCEOF: return null; case OpCode.ASSERT_OBJECT: return null; case OpCode.ASSERT_FUNC: return null; case OpCode.DELETE: r = false; break; default: return null; } return wrapImmediate(r); } export function isImmediateTrue (v: RValue): boolean { assert(isImmediate(v)); return !!unwrapImmediate(v); } export function isImmediateInteger (v: RValue): boolean { var tmp = unwrapImmediate(v); return typeof tmp === "number" && (tmp | 0) === tmp; } export function isValidArrayIndex (s: string): boolean { var n = Number(s) >>> 0; // convert to uint32 return n !== 4294967295 && String(n) === s; } /** * * @param op * @param v * @returns RValue folded value or null if the operand cannot be folded at compile time */ export function foldUnary (op: OpCode, v: RValue): RValue { if (!isImmediate(v)) return null; var a: any = unwrapImmediate(v); var r: any; switch (op) { case OpCode.NEG_N: r = -a; break; case OpCode.LOG_NOT: r = !a; break; case OpCode.BIN_NOT_N: r = ~a; break; case OpCode.TYPEOF: r = typeof a; break; case OpCode.VOID: r = void 0; break; case OpCode.TO_NUMBER: r = Number(a); break; case OpCode.TO_STRING: r = String(a); break; case OpCode.TO_OBJECT: return null; default: return null; } return wrapImmediate(r); } function bfs (entry: BasicBlock, exit: BasicBlock, callback: (bb: BasicBlock)=>void): void { var visited: boolean[] = []; var queue: BasicBlock[] = []; function enque (bb: BasicBlock): void { if (!visited[bb.id]) { visited[bb.id] = true; queue.push(bb); } } function visit (bb: BasicBlock): void { callback(bb); for (var i = 0, e = bb.succ.length; i < e; ++i) enque(bb.succ[i].bb ); } // Mark the exit node as visited to guarantee we will visit it last visited[exit.id] = true; visited[entry.id] = true; visit(entry); while (queue.length) visit(queue.shift()); // Finally generate the exit node visit(exit); } function dfs (entry: BasicBlock, exit: BasicBlock, callback: (bb: BasicBlock)=>void): void { var visited: boolean[] = []; var stack: BasicBlock[] = []; function push (bb: BasicBlock): void { if (!visited[bb.id]) { visited[bb.id] = true; stack.push(bb); } } function visit (bb: BasicBlock): void { callback(bb); //NOTE: in our current naive algorithm, this visit order produces "slightly" better results //for (var i = 0, e = bb.succ.length; i < e; ++i) for (var i = bb.succ.length - 1; i >= 0; --i) push(bb.succ[i].bb ); } // Mark the exit node as visited to guarantee we will visit it last visited[exit.id] = true; visited[entry.id] = true; visit(entry); var bb: BasicBlock; while ((bb = stack.pop()) !== void 0) visit(bb); // Finally generate the exit node visit(exit); } function buildBlockList (entry: BasicBlock, exit: BasicBlock): BasicBlock[] { var blockList: BasicBlock[] = []; dfs(entry, exit, (bb: BasicBlock) => blockList.push(bb)); return blockList; } function mangleName (name: string): string { var res: string = ""; var lastIndex = 0; for ( var i = 0, len = name.length; i < len; ++i ) { var ch = name[i]; if (!(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch === '_')) { if (lastIndex < i) res += name.slice(lastIndex, i); res += '_'; lastIndex = i + 1; } } if (lastIndex === 0) return name; if (lastIndex < i) res += name.slice(lastIndex, i); return res; } export class FunctionBuilder { public id: number; public module: ModuleBuilder; public parentBuilder: FunctionBuilder; public closureVar: Var; //< variable in the parent where this closure is kept public name: string; public mangledName: string; // Name suitable for code generation public runtimeVar: string = null; public isBuiltIn = false; public fileName: string = null; public line: number = 0; public column: number = 0; // The nesting level of this function's environment private envLevel: number; private params: Param[] = []; private locals: Local[] = []; private vars: Var[] = []; private envSize: number = 0; //< the size of the escaping environment block private paramSlotsCount: number = 0; //< number of slots to copy params into private paramSlots: Local[] = null; private argSlotsCount: number = 0; //< number of slots we need to reserve for calling private argSlots: ArgSlot[] = []; private tryRecordCount: number = 0; private lowestEnvAccessed: number = -1; private nextParamIndex = 0; private nextLocalId = 1; private nextLabelId = 0; private nextBBId = 0; private closed = false; private curBB: BasicBlock = null; private entryBB: BasicBlock = null; private exitBB: BasicBlock = null; private exitLabel: Label = null; public closures: FunctionBuilder[] = []; constructor(id: number, module: ModuleBuilder, parentBuilder: FunctionBuilder, closureVar: Var, name: string) { this.id = id; this.module = module; this.parentBuilder = parentBuilder; this.closureVar = closureVar; this.name = name; this.mangledName = "fn" + id; if (name) this.mangledName += "_" + mangleName(name); this.envLevel = parentBuilder ? parentBuilder.envLevel + 1 : 0; this.nextLocalId = parentBuilder ? parentBuilder.nextLocalId+1 : 1; this.entryBB = this.getBB(); this.exitLabel = this.newLabel(); } public getEnvLevel (): number { return this.envLevel; } public getEnvSize (): number { return this.envSize; } public getLocalsLength (): number { return this.locals.length; } public getParamsLength (): number { return this.params.length; } public getParamSlotsCount (): number { return this.paramSlotsCount; } public getTryRecordCount (): number { return this.tryRecordCount; } public getBlockListLength (): number { return this.blockList.length; } public getBlock (n: number): BasicBlock { return this.blockList[n]; } public getLowestEnvAccessed (): number { return this.lowestEnvAccessed; } toString() { return `Function(${this.id}/*${this.mangledName}*/)`; } newClosure (name: string): FunctionBuilder { var fref = new FunctionBuilder(this.module.newFunctionId(), this.module, this, this.newVar(name), name); this.closures.push(fref); return fref; } newBuiltinClosure (name: string, mangledName: string, runtimeVar: string): FunctionBuilder { var fref = this.newClosure(name); fref.mangledName = mangledName; fref.runtimeVar = runtimeVar; fref.isBuiltIn = true; return fref; } newParam(name: string): Param { var param = new Param(this.nextLocalId++, this.nextParamIndex++, name, this.newVar(name)); this.params.push(param); return param; } private getArgSlot(index: number): ArgSlot { if (index < this.argSlots.length) return this.argSlots[index]; assert(index === this.argSlots.length); var argSlot = new ArgSlot(this.nextLocalId++, this.argSlotsCount++); this.argSlots.push(argSlot); return argSlot; } newVar(name: string): Var { var v = new Var(this.nextLocalId++, this.envLevel, name); this.vars.push(v); return v; } newLocal(): Local { var loc = new Local(this.nextLocalId++, this.locals.length); this.locals.push(loc); return loc; } newLabel(): Label { var lab = new Label(this.nextLabelId++); return lab; } setVarAttributes ( v: Var, escapes: boolean, accessed: boolean, constant: boolean, funcRef: FunctionBuilder, consRef: FunctionBuilder ): void { v.escapes = escapes; v.constant = constant; v.accessed = accessed; if (constant) { v.funcRef = funcRef; v.consRef = consRef; } } private getBB (): BasicBlock { if (this.curBB) return this.curBB; else return this.curBB = new BasicBlock(this.nextBBId++); } getCurBB (): BasicBlock { return this.curBB; } closeBB (): void { this.curBB = null; } openBB (bb: BasicBlock): void { this.closeBB(); this.curBB = bb; } genClosure(dest: LValue, func: FunctionBuilder): void { this.getBB().push(new ClosureOp(dest, func)); } genAsm (dest: LValue, bindings: RValue[], pat: AsmPattern): void { assert(!dest || bindings[0] === dest); this.getBB().push(new AsmOp(dest || nullReg, bindings, pat)); } genBeginTry (onNormal: Label, onException: Label): number { var tryId = this.tryRecordCount++; this.getBB().jump(new BeginTryOp(tryId, onNormal, onException)); this.closeBB(); return tryId; } genEndTry (tryId: number): void { this.getBB().push(new EndTryOp(tryId)); } genThrow (value: RValue): void { this.getBB().jump(new ThrowOp(value)); this.closeBB(); } genRet(src: RValue): void { this.getBB().jump(new RetOp(this.exitLabel, src)); this.closeBB(); } genGoto(target: Label): void { this.getBB().jump(new GotoOp(target)); this.closeBB(); } genSwitch (selector: RValue, defaultLab: Label, values: number[], targets: Label[]): void { assert(values.length === targets.length); if (targets.length === 1) { // optimize into IF or GOTO if (defaultLab) this.genIf(OpCode.IF_STRICT_EQ, selector, values[0], targets[0], defaultLab); else this.genGoto(targets[0]); } else { this.getBB().jump(new SwitchOp(selector, defaultLab, values, targets)); this.closeBB(); } } genIfTrue(value: RValue, onTrue: Label, onFalse: Label): void { if (isImmediate(value)) return this.genGoto(isImmediateTrue(value) ? onTrue : onFalse); this.getBB().jump(new IfOp(OpCode.IF_TRUE, value, null, onTrue, onFalse)); this.closeBB(); } genIfIsObject(value: RValue, onTrue: Label, onFalse: Label): void { if (isImmediate(value)) return this.genGoto(onFalse); this.getBB().jump(new IfOp(OpCode.IF_IS_OBJECT, value, null, onTrue, onFalse)); this.closeBB(); } genIf(op: OpCode, src1: RValue, src2: RValue, onTrue: Label, onFalse: Label): void { assert(op >= OpCode._BINCOND_FIRST && op <= OpCode._BINCOND_LAST); var folded = foldBinary(op, src1, src2); if (folded !== null) return this.genGoto(isImmediateTrue(folded) ? onTrue : onFalse); this.getBB().jump(new IfOp(op, src1, src2, onTrue, onFalse)); this.closeBB(); } genLabel(label: Label): void { assert(!label.bb); var bb = this.getBB(); // If the current basic block is not empty, we must terminate it with a jump to the label if (bb.body.length) { this.getBB().jump(new GotoOp(label)); this.closeBB(); bb = this.getBB(); } bb.placeLabel(label); } openLabel (label: Label): void { assert(label.bb); if (this.curBB !== label.bb) { assert(!this.curBB); // The last BB must have been closed this.curBB = label.bb; } } genBinop(op: OpCode, dest: LValue, src1: RValue, src2: RValue): void { assert(op >= OpCode._BINOP_FIRST && op <= OpCode._BINOP_LAST); var folded = foldBinary(op, src1, src2); if (folded !== null) return this.genAssign(dest, folded); // Reorder to make it cleaner. e.g. 'a=a+b' instead of 'a=b+a' and 'a=b+1' instead of 'a=1+b' if (isCommutative(op) && (dest === src2 || isImmediate(src1))) { var t = src1; src1 = src2; src2 = t; } this.getBB().push(new BinOp(op, dest, src1, src2)); } genUnop(op: OpCode, dest: LValue, src: RValue): void { assert(op >= OpCode._UNOP_FIRST && op <= OpCode._UNOP_LAST); var folded = foldUnary(op, src); if (folded !== null) return this.genAssign(dest, folded); this.getBB().push(new UnOp(op, dest, src)); } genCreate(dest: LValue, src: RValue): void { this.getBB().push(new UnOp(OpCode.CREATE, dest, src)); } genCreateArguments(dest: LValue): void { this.getBB().push(new UnOp(OpCode.CREATE_ARGUMENTS, dest, undefinedValue)); } genLoadRuntimeVar(dest: LValue, runtimeVar: string): void { this.getBB().push(new LoadSCOp(dest, SysConst.RUNTIME_VAR, runtimeVar)); } genAssign(dest: LValue, src: RValue): void { if (dest === src) return; this.getBB().push(new AssignOp(dest, src)); } genPropGet(dest: LValue, obj: RValue, propName: RValue): void { this.getBB().push(new BinOp(OpCode.GET, dest, obj, propName)); } genPropSet(obj: RValue, propName: RValue, src: RValue): void { this.getBB().push(new PutOp(obj, propName, src)); } private _genCall(op: OpCode, dest: LValue, closure: RValue, args: RValue[]): CallOp { if (dest === null) dest = nullReg; var bb = this.getBB(); var slots: ArgSlot[] = Array<ArgSlot>(args.length); for ( var i = 0, e = args.length; i < e; ++i ) { slots[i] = this.getArgSlot(i); bb.push(new AssignOp(slots[i], args[i])); } var res: CallOp; this.getBB().push(res = new CallOp(op, dest, null, closure, slots)); return res; } genCall(dest: LValue, closure: RValue, args: RValue[]): CallOp { return this._genCall(OpCode.CALLIND, dest, closure, args); } genCallCons(dest: LValue, closure: RValue, args: RValue[]): CallOp { return this._genCall(OpCode.CALLCONS, dest, closure, args); } genMakeForInIterator (dest: LValue, obj: RValue): void { //this.genAsm(dest, [dest, frameReg, obj], [ // "js::ForInIterator::make(",1,",&",0,",",2,".raw.oval);" //]); this.genAsm(dest, [dest, frameReg, obj], [ 0," = js::makeForInIteratorValue(",2,".raw.oval->makeIterator(",1,"));" ]); } genForInIteratorNext (more: LValue, value: LValue, iter: RValue): void { this.genAsm(more, [more, frameReg, iter, value], [ 0," = js::makeBooleanValue(((js::ForInIterator*)",2,".raw.mval)->next(",1,", &",3,"));" ]); } blockList: BasicBlock[] = []; close (): void { if (this.isBuiltIn) return; if (this.closed) return; this.closed = true; if (this.curBB) this.genRet(undefinedValue); this.genLabel(this.exitLabel); this.exitBB = this.curBB; this.closeBB(); this.blockList = buildBlockList(this.entryBB, this.exitBB); } prepareForCodegen (): void { if (this.isBuiltIn) return; this.processVars(); this.closures.forEach((fb: FunctionBuilder) => fb.prepareForCodegen()); } private processVars (): void { // Allocate locals for the arg slots this.argSlots.forEach((a: ArgSlot) => { a.local = this.newLocal(); }); // Allocate locals this.vars.forEach( (v: Var) => { if (!v.escapes && v.accessed) { if (!v.formalParam) v.local = this.newLocal(); } }); // Allocate parameter locals at the end of the local array this.paramSlotsCount = 0; this.paramSlots = []; this.vars.forEach( (v: Var) => { if (!v.escapes && v.accessed) { if (v.formalParam) { v.local = this.newLocal(); this.paramSlots.push( v.local ); ++this.paramSlotsCount; } } }); // Assign escaping var indexes this.envSize = 0; this.vars.forEach((v: Var) => { if (v.escapes && v.accessed) v.envIndex = this.envSize++; }); // Copy parameters var instIndex = 0; this.params.forEach((p: Param) => { var v = p.variable; if (!v.param && v.accessed) this.entryBB.insertAt(instIndex++, new AssignOp(v, p)); }); // Create closures this.closures.forEach((fb: FunctionBuilder) => { var clvar = fb.closureVar; if (clvar && clvar.accessed) { var inst: Instruction; if (!fb.isBuiltIn) inst = new ClosureOp(clvar, fb); else inst = new LoadSCOp(clvar, SysConst.RUNTIME_VAR, fb.runtimeVar); this.entryBB.insertAt(instIndex++, inst); } }); this.scanAllInstructions(); // For now instead of finding the lowest possible environment, just find the lowest existing one // TODO: scan all escaping variable accesses and determine which environment we really need this.lowestEnvAccessed = -1; // No environment at all for ( var curb = this.parentBuilder; curb; curb = curb.parentBuilder ) { if (curb.envSize > 0) { this.lowestEnvAccessed = curb.envLevel; break; } } } /** * Perform operations which need to access every instruction. * <ul> * <li>Change CALLIND to CALL for all known functions.</li> * </ul> */ private scanAllInstructions (): void { for ( var i = 0, e = this.blockList.length; i < e; ++i ) scanBlock(this.blockList[i]); function scanBlock (bb: BasicBlock): void { for ( var i = 0, e = bb.body.length; i < e; ++i ) { var inst = bb.body[i]; // Transform CALLIND,CALLCONS with a known funcRef/consRef into CALL(funcRef) // if (inst.op === OpCode.CALLIND) { var callInst = <CallOp>inst; var closure: Var; if (closure = isVar(callInst.closure)) { if (closure.funcRef) { callInst.op = OpCode.CALL; callInst.fref = closure.funcRef; } } } else if (inst.op === OpCode.CALLCONS) { var callInst = <CallOp>inst; var closure: Var; if (closure = isVar(callInst.closure)) { if (closure.consRef) { callInst.op = OpCode.CALL; callInst.fref = closure.consRef; } } } } } } dump (): void { if (this.isBuiltIn) return; assert(this.closed); this.closures.forEach((ifb: FunctionBuilder) => { ifb.dump(); }); function ss (slots: Local[]): string { if (!slots || !slots.length) return "0"; return `${slots[0].index}..${slots[slots.length-1].index}`; } console.log(`\n${this.mangledName}://${this.name}`); var pslots: string; if (!this.paramSlots || !this.paramSlots.length) pslots = "0"; else pslots = `${this.paramSlots[0].index}..${this.paramSlots[this.paramSlots.length-1].index}`; var aslots: string; if (!this.argSlots || !this.argSlots.length) aslots = "0"; else aslots = `${this.argSlots[0].local.index}..${this.argSlots[this.argSlots.length-1].local.index}`; console.log(`//locals: ${this.locals.length} paramSlots: ${pslots} argSlots: ${aslots} env: ${this.envSize}`); for ( var i = 0, e = this.blockList.length; i < e; ++i ) { var bb = this.blockList[i]; console.log(`B${bb.id}:`); bb.body.forEach( (inst: Instruction) => { console.log(`\t${inst}`); }); } } } export class ModuleBuilder { private nextFunctionId = 0; private topLevel: FunctionBuilder = null; /** Headers added with the __asmh__ compiler extension */ private asmHeaders : string[] = []; private asmHeadersSet = new StringMap<Object>(); public debugMode: boolean = false; constructor(debugMode: boolean) { this.debugMode = debugMode; } getTopLevel (): FunctionBuilder { return this.topLevel; } getAsmHeaders (): string[] { return this.asmHeaders; } isDebugMode (): boolean { return this.debugMode; } addAsmHeader (h: string) { if (!this.asmHeadersSet.has(h)) { this.asmHeadersSet.set(h, null); this.asmHeaders.push(h); } } newFunctionId (): number { return this.nextFunctionId++; } createTopLevel(): FunctionBuilder { assert(!this.topLevel); var fref = new FunctionBuilder(this.newFunctionId(), this, null, null, "<global>"); this.topLevel = fref; return fref; } prepareForCodegen (): void { this.topLevel.prepareForCodegen(); } }
the_stack
class TransitOptions implements JQueryTransitOptions { opacity: number; duration: number; delay: number; easing: string; complete: () => void; scale: any; } $(document).ready(function() { test_translate(); test_x(); test_y(); test_width(); test_height(); test_margin(); test_marginTop(); test_marginBottom(); test_marginRight(); test_marginLeft(); test_skewX(); test_skewY(); test_perspective(); test_rotate(); test_rotateX(); test_rotateY(); test_rotate3d(); test_transform(); // test_transformOrigin(); test_opacity(); test_scale(); test_duration(); // Wait for all tests to complete and report results setTimeout(Assert.Results, 2000); }); abstract class Assert { static totalTests: number = 0; static passedTests: number = 0; static Results() { var results = 'Tests succeeded - '; results += Assert.passedTests; results += ' out of'; results += Assert.totalTests; results += ' Tests failed - '; results += Assert.totalTests - Assert.passedTests; results += ' out of '; results += Assert.totalTests; console.log(results); } static AssertionFailed(actual: any, expected: any, test?: string) { console.log( (test || '') + ' assertion failed -- expected ' + expected.toString() + ' actual ' + actual.toString(), ); } static Equal(actual: string, expected: string, test: string) { Assert.totalTests++; expected = expected.slice(0, expected.indexOf('transition')); expected = expected.trim(); if (expected.indexOf(';') < 0) expected += ';'; if (actual === expected) { Assert.passedTests++; return; } Assert.AssertionFailed(actual, expected, test); } static NotEqual(actual: any, expected: any, test?: string) { Assert.totalTests++; if (actual !== expected) { Assert.passedTests++; return; } Assert.AssertionFailed(actual, expected, test); } } function test_signatures() { var TestObject = $('<div>'); var options = new TransitOptions(); options.opacity = 50; options.duration = 250; TestObject.css('scale', 2); TestObject.transition(options); TestObject.transition(options, 500); TestObject.transition(options, 'in'); TestObject.transition(options, function() { var test: boolean = true; }); TestObject.transition(options, 500, 'out'); TestObject.transition(options, 500, 'in-out', function() { var test: boolean = true; }); } function test_translate() { var TestObject = $('<div>'); TestObject.css('translate', [60, 30]); var cssStyle = TestObject.attr('style'); TestObject.transition({ translate: [60, 30], duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'Translate number[] transition test'); }, }); TestObject.css('translate', '60px, 30px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ translate: ['60px', '30px'], duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'Translate string[] transition test'); }, }); TestObject.css('translate', '60px, 30px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ translate: '60px, 30px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'Translate string transition test'); }, }); } function test_x() { var TestObject = $('<div>'); TestObject.css('x', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ x: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'x string transition test'); }, }); TestObject.css('x', 10); var cssStyle = TestObject.attr('style'); TestObject.transition({ x: 10, duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'x number transition test'); }, }); } function test_y() { var TestObject = $('<div>'); TestObject.css('y', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ y: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'y string transition test'); }, }); TestObject.css('y', 10); var cssStyle = TestObject.attr('style'); TestObject.transition({ y: 10, duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'y number transition test'); }, }); } function test_width() { var TestObject = $('<div>'); TestObject.css('width', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ width: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'width string transition test'); }, }); TestObject.css('width', 10); var cssStyle = TestObject.attr('style'); TestObject.transition({ width: 10, duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'width number transition test'); }, }); } function test_height() { var TestObject = $('<div>'); TestObject.css('height', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ height: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'height string transition test'); }, }); TestObject.css('height', 10); var cssStyle = TestObject.attr('style'); TestObject.transition({ height: 10, duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'height number transition test'); }, }); } function test_margin() { var TestObject = $('<div>'); TestObject.css('margin', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ margin: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'margin string transition test'); }, }); } function test_marginRight() { var TestObject = $('<div>'); TestObject.css('margin-right', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ marginRight: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'marginRight transition test'); }, }); } function test_marginLeft() { var TestObject = $('<div>'); TestObject.css('margin-left', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ marginLeft: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'marginLeft transition test'); }, }); } function test_marginTop() { var TestObject = $('<div>'); TestObject.css('margin-top', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ marginTop: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'marginTop transition test'); }, }); } function test_marginBottom() { var TestObject = $('<div>'); TestObject.css('margin-bottom', '10px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ marginBottom: '10px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'marginBottom transition test'); }, }); } function test_skewX() { var TestObject = $('<div>'); TestObject.css('transform', 'skewX(30deg)'); var cssStyle = TestObject.attr('style'); TestObject.transition({ skewX: '30deg', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'skewX transition test'); }, }); } function test_skewY() { var TestObject = $('<div>'); TestObject.css('transform', 'skewY(30deg)'); var cssStyle = TestObject.attr('style'); TestObject.transition({ skewY: '30deg', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'skewY transition test'); }, }); } function test_perspective() { var TestObject = $('<div>'); TestObject.css('perspective', '100px'); var cssStyle = TestObject.attr('style'); TestObject.transition({ perspective: '100px', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'perspective transition test'); }, }); } function test_rotate() { var TestObject = $('<div>'); TestObject.css('transform', 'rotateY(20deg)'); var cssStyle = TestObject.attr('style'); TestObject.transition({ rotateY: '20deg', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'rotateY transition test'); }, }); } function test_rotateX() { var TestObject = $('<div>'); TestObject.css('transform', 'rotateX(20deg)'); var cssStyle = TestObject.attr('style'); TestObject.transition({ rotateX: '20deg', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'rotateX transition test'); }, }); } function test_rotateY() { var TestObject = $('<div>'); TestObject.css('transform', 'rotateY(20deg)'); var cssStyle = TestObject.attr('style'); TestObject.transition({ rotateY: '20deg', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'rotateY transition test'); }, }); } function test_rotate3d() { var TestObject = $('<div>'); TestObject.css('transform', 'rotate3d(1, 1, 1, 20deg)'); var cssStyle = TestObject.attr('style'); TestObject.transition({ rotate3d: '1, 1, 1, 20deg', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'rotate3d transition test'); }, }); } function test_transform() { var TestObject = $('<div>'); TestObject.css('transform', 'scale(0.2, 0.2)'); var cssStyle = TestObject.attr('style'); TestObject.transition({ transform: 'scale(0.2)', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'transform transition test'); }, }); } function test_transformOrigin() { var TestObject = $('<div>'); TestObject.css('transformOrgin', '20% 40%'); var cssStyle = TestObject.attr('style'); TestObject.transition({ transformOrigin: '20% 40%', duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'transformOrigin transition test'); }, }); } function test_opacity() { var TestObject = $('<div>'); TestObject.css('opacity', 25); var cssStyle = TestObject.attr('style'); TestObject.transition({ opacity: 25, duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'Opacity transition test'); }, }); } function test_scale() { var TestObject = $('<div>'); TestObject.css('scale', 0.5); var cssStyle = TestObject.attr('style'); TestObject.transition({ scale: 0.5, duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'Scale transition test'); }, }); TestObject.css('scale', [2, 3]); var cssStyle = TestObject.attr('style'); TestObject.transition({ scale: [2, 3], duration: 1, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'Scale transition test'); }, }); } function test_duration() { var TestObject = $('<div>'); TestObject.css('opacity', 75); var cssStyle = TestObject.attr('style'); TestObject.transition({ opacity: 75, duration: 1000, complete: function() { Assert.Equal(TestObject.attr('style'), cssStyle, 'Duration post-transition test'); }, }); // Test the transitions state partway through and assert that we're not to our final state yet. setTimeout(function() { Assert.NotEqual(TestObject.attr('style'), cssStyle, 'Duration intra-transition test'); }, 300); }
the_stack
import type { AppInterface, sourceType, SandBoxInterface, sourceLinkInfo, sourceScriptInfo, Func, } from '@micro-app/types' import extractHtml from './source' import { execScripts } from './source/scripts' import { appStates, lifeCycles, keepAliveStates } from './constants' import SandBox from './sandbox' import { isFunction, cloneContainer, isBoolean, isPromise, logError, getRootContainer, } from './libs/utils' import dispatchLifecyclesEvent, { dispatchCustomEventToMicroApp } from './interact/lifecycles_event' import globalEnv from './libs/global_env' import { releasePatchSetAttribute } from './source/patch' import { getActiveApps } from './micro_app' // micro app instances export const appInstanceMap = new Map<string, AppInterface>() // params of CreateApp export interface CreateAppParam { name: string url: string ssrUrl?: string scopecss: boolean useSandbox: boolean inline?: boolean baseroute?: string container?: HTMLElement | ShadowRoot } export default class CreateApp implements AppInterface { private state: string = appStates.NOT_LOADED private keepAliveState: string | null = null private keepAliveContainer: HTMLElement | null = null private loadSourceLevel: -1|0|1|2 = 0 private umdHookMount: Func | null = null private umdHookUnmount: Func | null = null private libraryName: string | null = null umdMode = false isPrefetch = false prefetchResolve: (() => void) | null = null name: string url: string ssrUrl: string container: HTMLElement | ShadowRoot | null = null inline: boolean scopecss: boolean useSandbox: boolean baseroute = '' source: sourceType sandBox: SandBoxInterface | null = null constructor ({ name, url, ssrUrl, container, inline, scopecss, useSandbox, baseroute, }: CreateAppParam) { this.container = container ?? null this.inline = inline ?? false this.baseroute = baseroute ?? '' this.ssrUrl = ssrUrl ?? '' // optional during init👆 this.name = name this.url = url this.useSandbox = useSandbox this.scopecss = this.useSandbox && scopecss this.source = { links: new Map<string, sourceLinkInfo>(), scripts: new Map<string, sourceScriptInfo>(), } this.loadSourceCode() this.useSandbox && (this.sandBox = new SandBox(name, url)) } // Load resources loadSourceCode (): void { this.state = appStates.LOADING_SOURCE_CODE extractHtml(this) } /** * When resource is loaded, mount app if it is not prefetch or unmount */ onLoad (html: HTMLElement): void { if (++this.loadSourceLevel === 2) { this.source.html = html if (this.isPrefetch) { this.prefetchResolve?.() this.prefetchResolve = null } else if (appStates.UNMOUNT !== this.state) { this.state = appStates.LOAD_SOURCE_FINISHED this.mount() } } } /** * Error loading HTML * @param e Error */ onLoadError (e: Error): void { this.loadSourceLevel = -1 if (this.prefetchResolve) { this.prefetchResolve() this.prefetchResolve = null } if (appStates.UNMOUNT !== this.state) { this.onerror(e) this.state = appStates.LOAD_SOURCE_ERROR } } /** * mount app * @param container app container * @param inline js runs in inline mode * @param baseroute route prefix, default is '' */ mount ( container?: HTMLElement | ShadowRoot, inline?: boolean, baseroute?: string, ): void { if (isBoolean(inline) && inline !== this.inline) { this.inline = inline } this.container = this.container ?? container! this.baseroute = baseroute ?? this.baseroute if (this.loadSourceLevel !== 2) { this.state = appStates.LOADING_SOURCE_CODE return } dispatchLifecyclesEvent( this.container, this.name, lifeCycles.BEFOREMOUNT, ) this.state = appStates.MOUNTING cloneContainer(this.source.html as Element, this.container as Element, !this.umdMode) this.sandBox?.start(this.baseroute) let umdHookMountResult: any // result of mount function if (!this.umdMode) { let hasDispatchMountedEvent = false // if all js are executed, param isFinished will be true execScripts(this.source.scripts, this, (isFinished: boolean) => { if (!this.umdMode) { const { mount, unmount } = this.getUmdLibraryHooks() // if mount & unmount is function, the sub app is umd mode if (isFunction(mount) && isFunction(unmount)) { this.umdHookMount = mount as Func this.umdHookUnmount = unmount as Func this.umdMode = true this.sandBox?.recordUmdSnapshot() try { umdHookMountResult = this.umdHookMount() } catch (e) { logError('an error occurred in the mount function \n', this.name, e) } } } if (!hasDispatchMountedEvent && (isFinished === true || this.umdMode)) { hasDispatchMountedEvent = true this.handleMounted(umdHookMountResult) } }) } else { this.sandBox?.rebuildUmdSnapshot() try { umdHookMountResult = this.umdHookMount!() } catch (e) { logError('an error occurred in the mount function \n', this.name, e) } this.handleMounted(umdHookMountResult) } } /** * handle for promise umdHookMount * @param umdHookMountResult result of umdHookMount */ private handleMounted (umdHookMountResult: any): void { if (isPromise(umdHookMountResult)) { umdHookMountResult .then(() => this.dispatchMountedEvent()) .catch((e: Error) => this.onerror(e)) } else { this.dispatchMountedEvent() } } /** * dispatch mounted event when app run finished */ private dispatchMountedEvent (): void { if (appStates.UNMOUNT !== this.state) { this.state = appStates.MOUNTED dispatchLifecyclesEvent( this.container!, this.name, lifeCycles.MOUNTED, ) } } /** * unmount app * @param destroy completely destroy, delete cache resources * @param unmountcb callback of unmount */ unmount (destroy: boolean, unmountcb?: CallableFunction): void { if (this.state === appStates.LOAD_SOURCE_ERROR) { destroy = true } this.state = appStates.UNMOUNT this.keepAliveState = null this.keepAliveContainer = null // result of unmount function let umdHookUnmountResult: any /** * send an unmount event to the micro app or call umd unmount hook * before the sandbox is cleared */ if (this.umdHookUnmount) { try { umdHookUnmountResult = this.umdHookUnmount() } catch (e) { logError('an error occurred in the unmount function \n', this.name, e) } } // dispatch unmount event to micro app dispatchCustomEventToMicroApp('unmount', this.name) this.handleUnmounted(destroy, umdHookUnmountResult, unmountcb) } /** * handle for promise umdHookUnmount * @param destroy completely destroy, delete cache resources * @param umdHookUnmountResult result of umdHookUnmount * @param unmountcb callback of unmount */ private handleUnmounted ( destroy: boolean, umdHookUnmountResult: any, unmountcb?: CallableFunction, ): void { if (isPromise(umdHookUnmountResult)) { umdHookUnmountResult .then(() => this.actionsForUnmount(destroy, unmountcb)) .catch(() => this.actionsForUnmount(destroy, unmountcb)) } else { this.actionsForUnmount(destroy, unmountcb) } } /** * actions for unmount app * @param destroy completely destroy, delete cache resources * @param unmountcb callback of unmount */ private actionsForUnmount (destroy: boolean, unmountcb?: CallableFunction): void { if (destroy) { this.actionsForCompletelyDestroy() } else if (this.umdMode && (this.container as Element).childElementCount) { cloneContainer(this.container as Element, this.source.html as Element, false) } // this.container maybe contains micro-app element, stop sandbox should exec after cloneContainer this.sandBox?.stop() if (!getActiveApps().length) { releasePatchSetAttribute() } // dispatch unmount event to base app dispatchLifecyclesEvent( this.container!, this.name, lifeCycles.UNMOUNT, ) this.container!.innerHTML = '' this.container = null unmountcb && unmountcb() } // actions for completely destroy actionsForCompletelyDestroy (): void { if (!this.useSandbox && this.umdMode) { delete window[this.libraryName as any] } appInstanceMap.delete(this.name) } // hidden app when disconnectedCallback called with keep-alive hiddenKeepAliveApp (): void { const oldContainer = this.container cloneContainer( this.container as Element, this.keepAliveContainer ? this.keepAliveContainer : (this.keepAliveContainer = document.createElement('div')), false, ) this.container = this.keepAliveContainer this.keepAliveState = keepAliveStates.KEEP_ALIVE_HIDDEN // event should dispatch before clone node // dispatch afterhidden event to micro-app dispatchCustomEventToMicroApp('appstate-change', this.name, { appState: 'afterhidden', }) // dispatch afterhidden event to base app dispatchLifecyclesEvent( oldContainer!, this.name, lifeCycles.AFTERHIDDEN, ) } // show app when connectedCallback called with keep-alive showKeepAliveApp (container: HTMLElement | ShadowRoot): void { // dispatch beforeshow event to micro-app dispatchCustomEventToMicroApp('appstate-change', this.name, { appState: 'beforeshow', }) // dispatch beforeshow event to base app dispatchLifecyclesEvent( container, this.name, lifeCycles.BEFORESHOW, ) cloneContainer( this.container as Element, container as Element, false, ) this.container = container this.keepAliveState = keepAliveStates.KEEP_ALIVE_SHOW // dispatch aftershow event to micro-app dispatchCustomEventToMicroApp('appstate-change', this.name, { appState: 'aftershow', }) // dispatch aftershow event to base app dispatchLifecyclesEvent( this.container, this.name, lifeCycles.AFTERSHOW, ) } /** * app rendering error * @param e Error */ onerror (e: Error): void { dispatchLifecyclesEvent( this.container!, this.name, lifeCycles.ERROR, e, ) } // get app state getAppState (): string { return this.state } // get keep-alive state getKeepAliveState (): string | null { return this.keepAliveState } // get umd library, if it not exist, return empty object private getUmdLibraryHooks (): Record<string, unknown> { // after execScripts, the app maybe unmounted if (appStates.UNMOUNT !== this.state) { const global = (this.sandBox?.proxyWindow ?? globalEnv.rawWindow) as any this.libraryName = getRootContainer(this.container!).getAttribute('library') || `micro-app-${this.name}` // do not use isObject return typeof global[this.libraryName] === 'object' ? global[this.libraryName] : {} } return {} } }
the_stack
import * as nbformat from '@jupyterlab/nbformat'; import { PartialJSONObject } from '@lumino/coreutils'; import { IDisposable } from '@lumino/disposable'; import { ISignal } from '@lumino/signaling'; /** * ISharedBase defines common operations that can be performed on any shared object. */ export interface ISharedBase extends IDisposable { /** * Undo an operation. */ undo(): void; /** * Redo an operation. */ redo(): void; /** * Whether the object can redo changes. */ canUndo(): boolean; /** * Whether the object can undo changes. */ canRedo(): boolean; /** * Clear the change stack. */ clearUndoHistory(): void; /** * Perform a transaction. While the function f is called, all changes to the shared * document are bundled into a single event. */ transact(f: () => void): void; } /** * Implement an API for Context information on the shared information. * This is used by, for example, docregistry to share the file-path of the edited content. */ export interface ISharedDocument extends ISharedBase { /** * The changed signal. */ readonly changed: ISignal<this, DocumentChange>; } /** * The ISharedText interface defines models that can be bound to a text editor like CodeMirror. */ export interface ISharedText extends ISharedBase { /** * The changed signal. */ readonly changed: ISignal<this, TextChange>; /** * Gets cell's source. * * @returns Cell's source. */ getSource(): string; /** * Sets cell's source. * * @param value: New source. */ setSource(value: string): void; /** * Replace content from `start' to `end` with `value`. * * @param start: The start index of the range to replace (inclusive). * * @param end: The end index of the range to replace (exclusive). * * @param value: New source (optional). */ updateSource(start: number, end: number, value?: string): void; } /** * Text/Markdown/Code files are represented as ISharedFile */ export interface ISharedFile extends ISharedDocument, ISharedText { /** * The changed signal. */ readonly changed: ISignal<this, FileChange>; } /** * Implements an API for nbformat.INotebookContent */ export interface ISharedNotebook extends ISharedDocument { /** * The changed signal. */ readonly changed: ISignal<this, NotebookChange>; /** * The minor version number of the nbformat. */ readonly nbformat_minor: number; /** * The major version number of the nbformat. */ readonly nbformat: number; /** * The list of shared cells in the notebook. */ readonly cells: ISharedCell[]; /** * Returns the metadata associated with the notebook. * * @returns Notebook's metadata. */ getMetadata(): nbformat.INotebookMetadata; /** * Sets the metadata associated with the notebook. * * @param metadata: Notebook's metadata. */ setMetadata(metadata: nbformat.INotebookMetadata): void; /** * Updates the metadata associated with the notebook. * * @param value: Metadata's attribute to update. */ updateMetadata(value: Partial<nbformat.INotebookMetadata>): void; /** * Get a shared cell by index. * * @param index: Cell's position. * * @returns The requested shared cell. */ getCell(index: number): ISharedCell; /** * Insert a shared cell into a specific position. * * @param index: Cell's position. * * @param cell: Cell to insert. */ insertCell(index: number, cell: ISharedCell): void; /** * Insert a list of shared cells into a specific position. * * @param index: Position to insert the cells. * * @param cells: Array of shared cells to insert. */ insertCells(index: number, cells: Array<ISharedCell>): void; /** * Move a cell. * * @param fromIndex: Index of the cell to move. * * @param toIndex: New position of the cell. */ moveCell(fromIndex: number, toIndex: number): void; /** * Remove a cell. * * @param index: Index of the cell to remove. */ deleteCell(index: number): void; /** * Remove a range of cells. * * @param from: The start index of the range to remove (inclusive). * * @param to: The end index of the range to remove (exclusive). */ deleteCellRange(from: number, to: number): void; } /** * The Shared kernelspec metadata. */ export interface ISharedKernelspecMetadata extends nbformat.IKernelspecMetadata, IDisposable { [key: string]: any; name: string; display_name: string; } /** * The Shared language info metatdata. */ export interface ISharedLanguageInfoMetadata extends nbformat.ILanguageInfoMetadata, IDisposable { [key: string]: any; name: string; codemirror_mode?: string | PartialJSONObject; file_extension?: string; mimetype?: string; pygments_lexer?: string; } export declare type ISharedCell = ISharedCodeCell | ISharedRawCell | ISharedMarkdownCell | ISharedUnrecognizedCell; /** * Cell-level metadata. */ export interface ISharedBaseCellMetadata extends nbformat.IBaseCellMetadata { [key: string]: any; } /** * Implements an API for nbformat.IBaseCell. */ export interface ISharedBaseCell<Metadata extends ISharedBaseCellMetadata> extends ISharedText { /** * Whether the cell is standalone or not. * * If the cell is standalone. It cannot be * inserted into a YNotebook because the Yjs model is already * attached to an anonymous Y.Doc instance. */ readonly isStandalone: boolean; /** * The type of the cell. */ readonly cell_type: nbformat.CellType; /** * The changed signal. */ readonly changed: ISignal<this, CellChange<Metadata>>; /** * Create a new YCodeCell that can be inserted into a YNotebook. * * @todo clone should only be available in the specific implementations i.e. ISharedCodeCell */ clone(): ISharedBaseCell<Metadata>; /** * Get Cell id. * * @returns Cell id. */ getId(): string; /** * Returns the metadata associated with the notebook. * * @returns Notebook's metadata. */ getMetadata(): Partial<Metadata>; /** * Sets the metadata associated with the notebook. * * @param metadata: Notebook's metadata. */ setMetadata(metadata: Partial<Metadata>): void; /** * Serialize the model to JSON. */ toJSON(): nbformat.IBaseCell; } /** * Implements an API for nbformat.ICodeCell. */ export interface ISharedCodeCell extends ISharedBaseCell<ISharedBaseCellMetadata> { /** * The type of the cell. */ cell_type: 'code'; /** * The code cell's prompt number. Will be null if the cell has not been run. */ execution_count: nbformat.ExecutionCount; /** * Execution, display, or stream outputs. */ getOutputs(): Array<nbformat.IOutput>; /** * Add/Update output. */ setOutputs(outputs: Array<nbformat.IOutput>): void; /** * Replace content from `start' to `end` with `outputs`. * * @param start: The start index of the range to replace (inclusive). * * @param end: The end index of the range to replace (exclusive). * * @param outputs: New outputs (optional). */ updateOutputs(start: number, end: number, outputs: Array<nbformat.IOutput>): void; /** * Serialize the model to JSON. */ toJSON(): nbformat.IBaseCell; } /** * Implements an API for nbformat.IMarkdownCell. */ export interface ISharedMarkdownCell extends ISharedBaseCell<ISharedBaseCellMetadata> { /** * String identifying the type of cell. */ cell_type: 'markdown'; /** * Gets the cell attachments. * * @returns The cell attachments. */ getAttachments(): nbformat.IAttachments | undefined; /** * Sets the cell attachments * * @param attachments: The cell attachments. */ setAttachments(attachments: nbformat.IAttachments | undefined): void; /** * Serialize the model to JSON. */ toJSON(): nbformat.IMarkdownCell; } /** * Implements an API for nbformat.IRawCell. */ export interface ISharedRawCell extends ISharedBaseCell<ISharedBaseCellMetadata>, IDisposable { /** * String identifying the type of cell. */ cell_type: 'raw'; /** * Gets the cell attachments. * * @returns The cell attachments. */ getAttachments(): nbformat.IAttachments | undefined; /** * Sets the cell attachments * * @param attachments: The cell attachments. */ setAttachments(attachments: nbformat.IAttachments | undefined): void; /** * Serialize the model to JSON. */ toJSON(): nbformat.IRawCell; } /** * Changes on Sequence-like data are expressed as Quill-inspired deltas. * * @source https://quilljs.com/docs/delta/ */ export declare type Delta<T> = Array<{ insert?: T; delete?: number; retain?: number; }>; /** * Implements an API for nbformat.IUnrecognizedCell. * * @todo Is this needed? */ export interface ISharedUnrecognizedCell extends ISharedBaseCell<ISharedBaseCellMetadata>, IDisposable { /** * The type of the cell. */ cell_type: 'raw'; /** * Serialize the model to JSON. */ toJSON(): nbformat.ICodeCell; } export declare type TextChange = { sourceChange?: Delta<string>; }; /** * Definition of the shared Notebook changes. */ export declare type NotebookChange = { cellsChange?: Delta<ISharedCell[]>; metadataChange?: { oldValue: nbformat.INotebookMetadata; newValue: nbformat.INotebookMetadata | undefined; }; contextChange?: MapChange; }; export declare type FileChange = { sourceChange?: Delta<string>; contextChange?: MapChange; }; /** * Definition of the shared Cell changes. */ export declare type CellChange<MetadataType> = { sourceChange?: Delta<string>; outputsChange?: Delta<nbformat.IOutput[]>; executionCountChange?: { oldValue: number | undefined; newValue: number | undefined; }; metadataChange?: { oldValue: Partial<MetadataType> | undefined; newValue: Partial<MetadataType> | undefined; }; }; export declare type DocumentChange = { contextChange?: MapChange; }; /** * Definition of the map changes for yjs. */ export declare type MapChange = Map<string, { action: 'add' | 'update' | 'delete'; oldValue: any; newValue: any; }>;
the_stack
import React, { ExoticComponent, useState } from "react" import { Redirect, Route, Switch } from "react-router-dom" import { Button, Form, Input, message, Modal } from "antd" import "./App.less" import ApplicationServices from "./lib/services/ApplicationServices" import { CenteredSpin, GlobalError, handleError, Preloader } from "./lib/components/components" import { reloadPage, setDebugInfo } from "./lib/commons/utils" import { User } from "./lib/services/model" import { PRIVATE_PAGES, PUBLIC_PAGES, SELFHOSTED_PAGES } from "./navigation" import { ApplicationPage, emailIsNotConfirmedMessageConfig, SlackChatWidget } from "./Layout" import { checkQuotas, getCurrentSubscription, CurrentSubscription, paymentPlans } from "lib/services/billing" import { initializeAllStores } from "stores/_initializeAllStores" import { destinationsStore } from "./stores/destinations" import { sourcesStore } from "./stores/sources" import BillingBlockingModal from "./lib/components/BillingModal/BillingBlockingModal" import moment from "moment" import { OnboardingSwitch } from "lib/components/Onboarding/OnboardingSwitch" import { UpgradePlan } from "./ui/components/CurrentPlan/CurrentPlan" enum AppLifecycle { LOADING, //Application is loading REQUIRES_LOGIN, //Login form is displayed APP, //Application ERROR, //Global error (maintenance) } type AppState = { lifecycle: AppLifecycle globalErrorDetails?: string extraControls?: React.ReactNode user?: User paymentPlanStatus?: CurrentSubscription } export const initializeApplication = async ( services: ApplicationServices = ApplicationServices.get() ): Promise<{ user: User paymentPlanStatus: CurrentSubscription }> => { await services.init() const { user } = await services.userService.waitForUser() setDebugInfo("user", user) if (user) { services.analyticsService.onUserKnown(user) } let paymentPlanStatus: CurrentSubscription await Promise.all([ initializeAllStores(), (async () => { if (user && services.features.billingEnabled) { if (services.activeProject) { paymentPlanStatus = await getCurrentSubscription( services.activeProject, services.backendApiClient, destinationsStore, sourcesStore ) } else { /** project is not initialized yet, return mock result */ paymentPlanStatus = { autorenew: false, expiration: moment().add(1, "M"), usage: { events: 0, sources: 0, destinations: 0, }, currentPlan: paymentPlans.free, quotaPeriodStart: moment(), doNotBlock: true, } } } else { /** for opensource (self-hosted) only */ paymentPlanStatus = { autorenew: false, expiration: moment().add(1, "M"), usage: { events: 0, sources: 0, destinations: 0, }, currentPlan: paymentPlans.opensource, quotaPeriodStart: moment(), doNotBlock: true, } } })(), ]) services.currentSubscription = paymentPlanStatus return { user, paymentPlanStatus } } const LOGIN_TIMEOUT = 5000 export default class App extends React.Component<{}, AppState> { private readonly services: ApplicationServices constructor(props: any, context: any) { super(props, context) this.services = ApplicationServices.get() setDebugInfo("applicationServices", this.services, false) this.state = { lifecycle: AppLifecycle.LOADING, extraControls: null, } } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { this.services.analyticsService.onGlobalError(error) } public async componentDidMount() { try { const { user, paymentPlanStatus } = await initializeApplication(this.services) this.setState({ lifecycle: user ? AppLifecycle.APP : AppLifecycle.REQUIRES_LOGIN, user: user, paymentPlanStatus: paymentPlanStatus, }) if (user) { const email = await this.services.userService.getUserEmailStatus() email.needsConfirmation && !email.isConfirmed && message.warn(emailIsNotConfirmedMessageConfig) } } catch (error) { console.error("Failed to initialize ApplicationServices", error) if (this.services.analyticsService) { this.services.analyticsService.onGlobalError(error, true) } else { console.error("Failed to send error to analytics service, it's not defined yet") } this.setState({ lifecycle: AppLifecycle.ERROR }) return } window.setTimeout(() => { if (this.state.lifecycle == AppLifecycle.LOADING) { this.services.analyticsService.onGlobalError(new Error("Login timeout")) this.setState({ lifecycle: AppLifecycle.ERROR, globalErrorDetails: "Timeout" }) } }, LOGIN_TIMEOUT) } private getRenderComponent() { switch (this.state.lifecycle) { case AppLifecycle.REQUIRES_LOGIN: let pages = this.services.showSelfHostedSignUp() ? SELFHOSTED_PAGES : PUBLIC_PAGES return ( <> <Switch> {pages.map(route => { let Component = route.component as ExoticComponent return ( <Route key={route.getPrefixedPath().join("")} path={route.getPrefixedPath()} exact render={routeProps => { this.services.analyticsService.onPageLoad({ pagePath: routeProps.location.key || "/unknown", }) document["title"] = route.pageTitle return <Component {...(routeProps as any)} /> }} /> ) })} <Redirect key="rootRedirect" to="/" /> </Switch> </> ) case AppLifecycle.APP: return ( <> {this.appLayout()} {<SlackChatWidget />} </> ) case AppLifecycle.ERROR: return <GlobalError /> case AppLifecycle.LOADING: return <Preloader /> } } public render() { return <React.Suspense fallback={<CenteredSpin />}>{this.getRenderComponent()}</React.Suspense> } appLayout() { const extraForms = [<OnboardingSwitch key="onboardingTour" />] if (this.services.userService.getUser().forcePasswordChange) { return ( <SetNewPassword onCompleted={async () => { reloadPage() }} /> ) } else if (this.state.paymentPlanStatus) { const quotasMessage = checkQuotas(this.state.paymentPlanStatus) if (quotasMessage) { extraForms.push( <BillingBlockingModal key="billingBlockingModal" blockingReason={quotasMessage} subscription={this.state.paymentPlanStatus} /> ) } else if (this.state.paymentPlanStatus && window.location.search.indexOf("upgradeDialog=true") >= 0) { extraForms.push(<UpgradePlanDialog subscription={this.state.paymentPlanStatus} />) } } return ( <ApplicationPage key="applicationPage" user={this.state.user} plan={this.state.paymentPlanStatus} pages={PRIVATE_PAGES} extraForms={extraForms} /> ) } } function UpgradePlanDialog({ subscription }) { const [visible, setVisible] = useState(true) return ( <Modal destroyOnClose={true} visible={visible} width={800} onCancel={() => setVisible(false)} title={<h1 className="text-xl m-0 p-0">Upgrade subscription</h1>} footer={null} > <UpgradePlan planStatus={subscription} /> </Modal> ) } function SetNewPassword({ onCompleted }: { onCompleted: () => Promise<void> }) { let [loading, setLoading] = useState(false) let services = ApplicationServices.get() let [form] = Form.useForm() return ( <Modal title="Please, set a new password" visible={true} closable={false} footer={ <> <Button onClick={() => { services.userService.removeAuth(reloadPage) }} > Logout </Button> <Button type="primary" loading={loading} onClick={async () => { setLoading(true) let values try { values = await form.validateFields() } catch (e) { //error will be displayed on the form, not need for special handling setLoading(false) return } try { let newPassword = values["password"] await services.userService.changePassword(newPassword) await services.userService.login(services.userService.getUser().email, newPassword) let user = (await services.userService.waitForUser()).user user.forcePasswordChange = false //await services.userService.update(user); await onCompleted() } catch (e) { if ("auth/requires-recent-login" === e.code) { services.userService.removeAuth(() => { reloadPage() }) } else { handleError(e) } } finally { setLoading(false) } }} > Set new password </Button> </> } > <Form form={form} layout="vertical" requiredMark={false}> <Form.Item name="password" label="Password" rules={[ { required: true, message: "Please input your password!", }, ]} hasFeedback > <Input.Password /> </Form.Item> <Form.Item name="confirm" label="Confirm Password" dependencies={["password"]} hasFeedback rules={[ { required: true, message: "Please confirm your password!", }, ({ getFieldValue }) => ({ validator(rule, value) { if (!value || getFieldValue("password") === value) { return Promise.resolve() } return Promise.reject("The two passwords that you entered do not match!") }, }), ]} > <Input.Password /> </Form.Item> </Form> </Modal> ) }
the_stack
import { expect } from 'chai'; import { SinonStub, stub } from 'sinon'; import { promises as fs } from 'fs'; import * as systeminformation from 'systeminformation'; import * as fsUtils from '../../../src/lib/fs-utils'; import * as sysInfo from '../../../src/lib/system-info'; describe('System information', () => { before(() => { stub(systeminformation, 'fsSize'); stub(systeminformation, 'mem').resolves(mockMemory); stub(systeminformation, 'currentLoad').resolves(mockCPU.load); stub(systeminformation, 'cpuTemperature').resolves(mockCPU.temp); // @ts-ignore TS thinks we can't return a buffer... stub(fs, 'readFile').resolves(mockCPU.idBuffer); stub(fsUtils, 'exec'); }); after(() => { (systeminformation.fsSize as SinonStub).restore(); (systeminformation.mem as SinonStub).restore(); (systeminformation.currentLoad as SinonStub).restore(); (systeminformation.cpuTemperature as SinonStub).restore(); (fs.readFile as SinonStub).restore(); (fsUtils.exec as SinonStub).restore(); }); describe('isSignificantChange', () => { it('should correctly filter cpu usage', () => { expect(sysInfo.isSignificantChange('cpu_usage', 21, 20)).to.be.false; expect(sysInfo.isSignificantChange('cpu_usage', 10, 20)).to.be.true; }); it('should correctly filter cpu temperature', () => { expect(sysInfo.isSignificantChange('cpu_temp', 21, 22)).to.be.false; expect(sysInfo.isSignificantChange('cpu_temp', 10, 20)).to.be.true; }); it('should correctly filter memory usage', () => { expect(sysInfo.isSignificantChange('memory_usage', 21, 22)).to.be.false; expect(sysInfo.isSignificantChange('memory_usage', 10, 20)).to.be.true; }); it("should not filter if we didn't have a past value", () => { expect(sysInfo.isSignificantChange('cpu_usage', undefined, 22)).to.be .true; expect(sysInfo.isSignificantChange('cpu_temp', undefined, 10)).to.be.true; expect(sysInfo.isSignificantChange('memory_usage', undefined, 5)).to.be .true; }); it('should not filter if the current value is null', () => { // When the current value is null, we're sending a null patch to the // API in response to setting DISABLE_HARDWARE_METRICS to true, so // we need to include null for all values. None of the individual metrics // in systemMetrics return null (only number/undefined), so the only // reason for current to be null is when a null patch is happening. expect(sysInfo.isSignificantChange('cpu_usage', 15, null as any)).to.be .true; expect(sysInfo.isSignificantChange('cpu_temp', 55, null as any)).to.be .true; expect(sysInfo.isSignificantChange('memory_usage', 760, null as any)).to .be.true; }); it('should not filter if the current value is null', () => { // When the current value is null, we're sending a null patch to the // API in response to setting HARDWARE_METRICS to false, so // we need to include null for all values. None of the individual metrics // in systemMetrics return null (only number/undefined), so the only // reason for current to be null is when a null patch is happening. expect(sysInfo.isSignificantChange('cpu_usage', 15, null as any)).to.be .true; expect(sysInfo.isSignificantChange('cpu_temp', 55, null as any)).to.be .true; expect(sysInfo.isSignificantChange('memory_usage', 760, null as any)).to .be.true; }); }); describe('CPU information', () => { it('gets CPU usage', async () => { const cpuUsage = await sysInfo.getCpuUsage(); // Make sure it is a whole number expect(cpuUsage % 1).to.equal(0); // Make sure it's the right number given the mocked data expect(cpuUsage).to.equal(1); }); it('gets CPU temp', async () => { const tempInfo = await sysInfo.getCpuTemp(); // Make sure it is a whole number expect(tempInfo % 1).to.equal(0); // Make sure it's the right number given the mocked data expect(tempInfo).to.equal(51); }); }); describe('baseboard information', () => { afterEach(() => { (fs.readFile as SinonStub).reset(); (fsUtils.exec as SinonStub).reset(); }); // Do these two tests first so the dmidecode call is not memoized yet it('returns undefined system model if dmidecode throws', async () => { (fs.readFile as SinonStub).rejects('Not found'); (fsUtils.exec as SinonStub).rejects('Something bad happened'); const systemModel = await sysInfo.getSystemModel(); expect(systemModel).to.be.undefined; }); it('returns undefined system ID if dmidecode throws', async () => { (fs.readFile as SinonStub).rejects('Not found'); (fsUtils.exec as SinonStub).rejects('Something bad happened'); const systemId = await sysInfo.getSystemId(); expect(systemId).to.be.undefined; }); it('gets system ID', async () => { (fs.readFile as SinonStub).resolves(mockCPU.idBuffer); const cpuId = await sysInfo.getSystemId(); expect(cpuId).to.equal('1000000001b93f3f'); }); it('gets system ID from dmidecode if /proc/device-tree/serial-number is not available', async () => { (fs.readFile as SinonStub).rejects('Not found'); (fsUtils.exec as SinonStub).resolves({ stdout: mockCPU.dmidecode, }); const cpuId = await sysInfo.getSystemId(); expect(cpuId).to.equal('GEBN94600PWW'); }); it('gets system model', async () => { (fs.readFile as SinonStub).resolves('Raspberry PI 4'); const systemModel = await sysInfo.getSystemModel(); expect(systemModel).to.equal('Raspberry PI 4'); }); it('gets system model from dmidecode if /proc/device-tree/model is not available', async () => { (fs.readFile as SinonStub).rejects('Not found'); (fsUtils.exec as SinonStub).resolves({ stdout: mockCPU.dmidecode, }); const systemModel = await sysInfo.getSystemModel(); expect(systemModel).to.equal('Intel Corporation NUC7i5BNB'); }); }); describe('getMemoryInformation', async () => { it('should return the correct value for memory usage', async () => { const memoryInfo = await sysInfo.getMemoryInformation(); expect(memoryInfo).to.deep.equal({ total: sysInfo.bytesToMb(mockMemory.total), used: sysInfo.bytesToMb( mockMemory.total - mockMemory.free - (mockMemory.cached + mockMemory.buffers), ), }); }); }); describe('getStorageInfo', async () => { it('should return info on /data mount', async () => { (systeminformation.fsSize as SinonStub).resolves(mockFS); const storageInfo = await sysInfo.getStorageInfo(); expect(storageInfo).to.deep.equal({ blockDevice: '/dev/mmcblk0p6', storageUsed: 1118, storageTotal: 29023, }); }); it('should handle no /data mount', async () => { (systeminformation.fsSize as SinonStub).resolves([]); const storageInfo = await sysInfo.getStorageInfo(); expect(storageInfo).to.deep.equal({ blockDevice: '', storageUsed: undefined, storageTotal: undefined, }); }); }); describe('undervoltageDetected', () => { it('should detect undervoltage', async () => { (fsUtils.exec as SinonStub).resolves({ stdout: Buffer.from( '[58611.126996] Under-voltage detected! (0x00050005)', ), stderr: Buffer.from(''), }); expect(await sysInfo.undervoltageDetected()).to.be.true; (fsUtils.exec as SinonStub).resolves({ stdout: Buffer.from('[569378.450066] eth0: renamed from veth3aa11ca'), stderr: Buffer.from(''), }); expect(await sysInfo.undervoltageDetected()).to.be.false; }); }); describe('dmidecode', () => { it('parses dmidecode output into json', async () => { (fsUtils.exec as SinonStub).resolves({ stdout: mockCPU.dmidecode, }); expect(await sysInfo.dmidecode('baseboard')).to.deep.equal([ { type: 'Base Board Information', values: { Manufacturer: 'Intel Corporation', 'Product Name': 'NUC7i5BNB', Version: 'J31144-313', 'Serial Number': 'GEBN94600PWW', 'Location In Chassis': 'Default string', 'Chassis Handle': '0x0003', Type: 'Motherboard', 'Contained Object Handles': '0', }, }, { type: 'On Board Device 1 Information', values: { Type: 'Sound', Status: 'Enabled', Description: 'Realtek High Definition Audio Device', }, }, { type: 'Onboard Device', values: { 'Reference Designation': 'Onboard - Other', Type: 'Other', Status: 'Enabled', 'Type Instance': '1', 'Bus Address': '0000', }, }, ]); // Reset the stub (fsUtils.exec as SinonStub).reset(); }); }); }); const mockCPU = { temp: { main: 50.634, cores: [], max: 50.634, socket: [], }, load: { avgLoad: 0.6, currentLoad: 1.4602487831260142, currentLoadUser: 0.7301243915630071, currentLoadSystem: 0.7301243915630071, currentLoadNice: 0, currentLoadIdle: 98.53975121687398, currentLoadIrq: 0, rawCurrentLoad: 5400, rawCurrentLoadUser: 2700, rawCurrentLoadSystem: 2700, rawCurrentLoadNice: 0, rawCurrentLoadIdle: 364400, rawCurrentLoadIrq: 0, cpus: [ { load: 1.8660812294182216, loadUser: 0.7683863885839737, loadSystem: 1.0976948408342482, loadNice: 0, loadIdle: 98.13391877058177, loadIrq: 0, rawLoad: 1700, rawLoadUser: 700, rawLoadSystem: 1000, rawLoadNice: 0, rawLoadIdle: 89400, rawLoadIrq: 0, }, { load: 1.7204301075268817, loadUser: 0.8602150537634409, loadSystem: 0.8602150537634409, loadNice: 0, loadIdle: 98.27956989247312, loadIrq: 0, rawLoad: 1600, rawLoadUser: 800, rawLoadSystem: 800, rawLoadNice: 0, rawLoadIdle: 91400, rawLoadIrq: 0, }, { load: 1.186623516720604, loadUser: 0.9708737864077669, loadSystem: 0.2157497303128371, loadNice: 0, loadIdle: 98.8133764832794, loadIrq: 0, rawLoad: 1100, rawLoadUser: 900, rawLoadSystem: 200, rawLoadNice: 0, rawLoadIdle: 91600, rawLoadIrq: 0, }, { load: 1.0752688172043012, loadUser: 0.3225806451612903, loadSystem: 0.7526881720430108, loadNice: 0, loadIdle: 98.9247311827957, loadIrq: 0, rawLoad: 1000, rawLoadUser: 300, rawLoadSystem: 700, rawLoadNice: 0, rawLoadIdle: 92000, rawLoadIrq: 0, }, ], }, idBuffer: Buffer.from('1000000001b93f3f'), dmidecode: Buffer.from(`# dmidecode 3.3 Getting SMBIOS data from sysfs. SMBIOS 3.1.1 present. Handle 0x0002, DMI type 2, 15 bytes Base Board Information Manufacturer: Intel Corporation Product Name: NUC7i5BNB Version: J31144-313 Serial Number: GEBN94600PWW Asset Tag: Features: Board is a hosting board Board is replaceable Location In Chassis: Default string Chassis Handle: 0x0003 Type: Motherboard Contained Object Handles: 0 Handle 0x000F, DMI type 10, 20 bytes On Board Device 1 Information Type: Video Status: Enabled Description: Intel(R) HD Graphics Device On Board Device 2 Information Type: Ethernet Status: Enabled Description: Intel(R) I219-V Gigabit Network Device On Board Device 3 Information Type: Sound Status: Enabled Description: Realtek High Definition Audio Device Handle 0x003F, DMI type 41, 11 bytes Onboard Device Reference Designation: Onboard - Other Type: Other Status: Enabled Type Instance: 1 Bus Address: 0000:00:00.0 `), }; const mockFS = [ { fs: 'overlay', type: 'overlay', size: 30433308672, used: 1172959232, available: 27684696064, use: 4.06, mount: '/', }, { fs: '/dev/mmcblk0p6', type: 'ext4', size: 30433308672, used: 1172959232, available: 27684696064, use: 4.06, mount: '/data', }, { fs: '/dev/mmcblk0p1', type: 'vfat', size: 41281536, used: 7219200, available: 34062336, use: 17.49, mount: '/boot/config.json', }, { fs: '/dev/disk/by-state/resin-state', type: 'ext4', size: 19254272, used: 403456, available: 17383424, use: 2.27, mount: '/mnt/root/mnt/state', }, { fs: '/dev/disk/by-uuid/ba1eadef-4660-4b03-9e71-9f33257f292c', type: 'ext4', size: 313541632, used: 308860928, available: 0, use: 100, mount: '/mnt/root/mnt/sysroot/active', }, { fs: '/dev/mmcblk0p2', type: 'ext4', size: 313541632, used: 299599872, available: 0, use: 100, mount: '/mnt/root/mnt/sysroot/inactive', }, ]; const mockMemory = { total: 4032724992, free: 2182356992, used: 1850368000, active: 459481088, available: 3573243904, buffers: 186269696, cached: 1055621120, slab: 252219392, buffcache: 1494110208, swaptotal: 2016358400, swapused: 0, swapfree: 2016358400, };
the_stack
import { VSBuffer } from 'vs/base/common/buffer'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, dispose, IDisposable } from 'vs/base/common/lifecycle'; import * as platform from 'vs/base/common/platform'; import * as process from 'vs/base/common/process'; import { IIPCLogger, IMessagePassingProtocol, IPCClient } from 'vs/base/parts/ipc/common/ipc'; export const enum SocketCloseEventType { NodeSocketCloseEvent = 0, WebSocketCloseEvent = 1 } export interface NodeSocketCloseEvent { /** * The type of the event */ readonly type: SocketCloseEventType.NodeSocketCloseEvent; /** * `true` if the socket had a transmission error. */ readonly hadError: boolean; /** * Underlying error. */ readonly error: Error | undefined } export interface WebSocketCloseEvent { /** * The type of the event */ readonly type: SocketCloseEventType.WebSocketCloseEvent; /** * Returns the WebSocket connection close code provided by the server. */ readonly code: number; /** * Returns the WebSocket connection close reason provided by the server. */ readonly reason: string; /** * Returns true if the connection closed cleanly; false otherwise. */ readonly wasClean: boolean; /** * Underlying event. */ readonly event: any | undefined; } export type SocketCloseEvent = NodeSocketCloseEvent | WebSocketCloseEvent | undefined; export interface ISocket extends IDisposable { onData(listener: (e: VSBuffer) => void): IDisposable; onClose(listener: (e: SocketCloseEvent) => void): IDisposable; onEnd(listener: () => void): IDisposable; write(buffer: VSBuffer): void; end(): void; drain(): Promise<void>; } let emptyBuffer: VSBuffer | null = null; function getEmptyBuffer(): VSBuffer { if (!emptyBuffer) { emptyBuffer = VSBuffer.alloc(0); } return emptyBuffer; } export class ChunkStream { private _chunks: VSBuffer[]; private _totalLength: number; public get byteLength() { return this._totalLength; } constructor() { this._chunks = []; this._totalLength = 0; } public acceptChunk(buff: VSBuffer) { this._chunks.push(buff); this._totalLength += buff.byteLength; } public read(byteCount: number): VSBuffer { return this._read(byteCount, true); } public peek(byteCount: number): VSBuffer { return this._read(byteCount, false); } private _read(byteCount: number, advance: boolean): VSBuffer { if (byteCount === 0) { return getEmptyBuffer(); } if (byteCount > this._totalLength) { throw new Error(`Cannot read so many bytes!`); } if (this._chunks[0].byteLength === byteCount) { // super fast path, precisely first chunk must be returned const result = this._chunks[0]; if (advance) { this._chunks.shift(); this._totalLength -= byteCount; } return result; } if (this._chunks[0].byteLength > byteCount) { // fast path, the reading is entirely within the first chunk const result = this._chunks[0].slice(0, byteCount); if (advance) { this._chunks[0] = this._chunks[0].slice(byteCount); this._totalLength -= byteCount; } return result; } let result = VSBuffer.alloc(byteCount); let resultOffset = 0; let chunkIndex = 0; while (byteCount > 0) { const chunk = this._chunks[chunkIndex]; if (chunk.byteLength > byteCount) { // this chunk will survive const chunkPart = chunk.slice(0, byteCount); result.set(chunkPart, resultOffset); resultOffset += byteCount; if (advance) { this._chunks[chunkIndex] = chunk.slice(byteCount); this._totalLength -= byteCount; } byteCount -= byteCount; } else { // this chunk will be entirely read result.set(chunk, resultOffset); resultOffset += chunk.byteLength; if (advance) { this._chunks.shift(); this._totalLength -= chunk.byteLength; } else { chunkIndex++; } byteCount -= chunk.byteLength; } } return result; } } const enum ProtocolMessageType { None = 0, Regular = 1, Control = 2, Ack = 3, KeepAlive = 4, Disconnect = 5, ReplayRequest = 6 } export const enum ProtocolConstants { HeaderLength = 13, /** * Send an Acknowledge message at most 2 seconds later... */ AcknowledgeTime = 2000, // 2 seconds /** * If there is a message that has been unacknowledged for 10 seconds, consider the connection closed... */ AcknowledgeTimeoutTime = 20000, // 20 seconds /** * Send at least a message every 5s for keep alive reasons. */ KeepAliveTime = 5000, // 5 seconds /** * If there is no message received for 10 seconds, consider the connection closed... */ KeepAliveTimeoutTime = 20000, // 20 seconds /** * If there is no reconnection within this time-frame, consider the connection permanently closed... */ ReconnectionGraceTime = 3 * 60 * 60 * 1000, // 3hrs /** * Maximal grace time between the first and the last reconnection... */ ReconnectionShortGraceTime = 5 * 60 * 1000, // 5min } class ProtocolMessage { public writtenTime: number; constructor( public readonly type: ProtocolMessageType, public readonly id: number, public readonly ack: number, public readonly data: VSBuffer ) { this.writtenTime = 0; } public get size(): number { return this.data.byteLength; } } class ProtocolReader extends Disposable { private readonly _socket: ISocket; private _isDisposed: boolean; private readonly _incomingData: ChunkStream; public lastReadTime: number; private readonly _onMessage = this._register(new Emitter<ProtocolMessage>()); public readonly onMessage: Event<ProtocolMessage> = this._onMessage.event; private readonly _state = { readHead: true, readLen: ProtocolConstants.HeaderLength, messageType: ProtocolMessageType.None, id: 0, ack: 0 }; constructor(socket: ISocket) { super(); this._socket = socket; this._isDisposed = false; this._incomingData = new ChunkStream(); this._register(this._socket.onData(data => this.acceptChunk(data))); this.lastReadTime = Date.now(); } public acceptChunk(data: VSBuffer | null): void { if (!data || data.byteLength === 0) { return; } this.lastReadTime = Date.now(); this._incomingData.acceptChunk(data); while (this._incomingData.byteLength >= this._state.readLen) { const buff = this._incomingData.read(this._state.readLen); if (this._state.readHead) { // buff is the header // save new state => next time will read the body this._state.readHead = false; this._state.readLen = buff.readUInt32BE(9); this._state.messageType = buff.readUInt8(0); this._state.id = buff.readUInt32BE(1); this._state.ack = buff.readUInt32BE(5); } else { // buff is the body const messageType = this._state.messageType; const id = this._state.id; const ack = this._state.ack; // save new state => next time will read the header this._state.readHead = true; this._state.readLen = ProtocolConstants.HeaderLength; this._state.messageType = ProtocolMessageType.None; this._state.id = 0; this._state.ack = 0; this._onMessage.fire(new ProtocolMessage(messageType, id, ack, buff)); if (this._isDisposed) { // check if an event listener lead to our disposal break; } } } } public readEntireBuffer(): VSBuffer { return this._incomingData.read(this._incomingData.byteLength); } public override dispose(): void { this._isDisposed = true; super.dispose(); } } class ProtocolWriter { private _isDisposed: boolean; private readonly _socket: ISocket; private _data: VSBuffer[]; private _totalLength: number; public lastWriteTime: number; constructor(socket: ISocket) { this._isDisposed = false; this._socket = socket; this._data = []; this._totalLength = 0; this.lastWriteTime = 0; } public dispose(): void { try { this.flush(); } catch (err) { // ignore error, since the socket could be already closed } this._isDisposed = true; } public drain(): Promise<void> { this.flush(); return this._socket.drain(); } public flush(): void { // flush this._writeNow(); } public write(msg: ProtocolMessage) { if (this._isDisposed) { // ignore: there could be left-over promises which complete and then // decide to write a response, etc... return; } msg.writtenTime = Date.now(); this.lastWriteTime = Date.now(); const header = VSBuffer.alloc(ProtocolConstants.HeaderLength); header.writeUInt8(msg.type, 0); header.writeUInt32BE(msg.id, 1); header.writeUInt32BE(msg.ack, 5); header.writeUInt32BE(msg.data.byteLength, 9); this._writeSoon(header, msg.data); } private _bufferAdd(head: VSBuffer, body: VSBuffer): boolean { const wasEmpty = this._totalLength === 0; this._data.push(head, body); this._totalLength += head.byteLength + body.byteLength; return wasEmpty; } private _bufferTake(): VSBuffer { const ret = VSBuffer.concat(this._data, this._totalLength); this._data.length = 0; this._totalLength = 0; return ret; } private _writeSoon(header: VSBuffer, data: VSBuffer): void { if (this._bufferAdd(header, data)) { platform.setImmediate(() => { this._writeNow(); }); } } private _writeNow(): void { if (this._totalLength === 0) { return; } this._socket.write(this._bufferTake()); } } /** * A message has the following format: * ``` * /-------------------------------|------\ * | HEADER | | * |-------------------------------| DATA | * | TYPE | ID | ACK | DATA_LENGTH | | * \-------------------------------|------/ * ``` * The header is 9 bytes and consists of: * - TYPE is 1 byte (ProtocolMessageType) - the message type * - ID is 4 bytes (u32be) - the message id (can be 0 to indicate to be ignored) * - ACK is 4 bytes (u32be) - the acknowledged message id (can be 0 to indicate to be ignored) * - DATA_LENGTH is 4 bytes (u32be) - the length in bytes of DATA * * Only Regular messages are counted, other messages are not counted, nor acknowledged. */ export class Protocol extends Disposable implements IMessagePassingProtocol { private _socket: ISocket; private _socketWriter: ProtocolWriter; private _socketReader: ProtocolReader; private readonly _onMessage = new Emitter<VSBuffer>(); readonly onMessage: Event<VSBuffer> = this._onMessage.event; private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor(socket: ISocket) { super(); this._socket = socket; this._socketWriter = this._register(new ProtocolWriter(this._socket)); this._socketReader = this._register(new ProtocolReader(this._socket)); this._register(this._socketReader.onMessage((msg) => { if (msg.type === ProtocolMessageType.Regular) { this._onMessage.fire(msg.data); } })); this._register(this._socket.onClose(() => this._onDidDispose.fire())); } drain(): Promise<void> { return this._socketWriter.drain(); } getSocket(): ISocket { return this._socket; } sendDisconnect(): void { // Nothing to do... } send(buffer: VSBuffer): void { this._socketWriter.write(new ProtocolMessage(ProtocolMessageType.Regular, 0, 0, buffer)); } } export class Client<TContext = string> extends IPCClient<TContext> { static fromSocket<TContext = string>(socket: ISocket, id: TContext): Client<TContext> { return new Client(new Protocol(socket), id); } get onDidDispose(): Event<void> { return this.protocol.onDidDispose; } constructor(private protocol: Protocol | PersistentProtocol, id: TContext, ipcLogger: IIPCLogger | null = null) { super(protocol, id, ipcLogger); } override dispose(): void { super.dispose(); const socket = this.protocol.getSocket(); this.protocol.sendDisconnect(); this.protocol.dispose(); socket.end(); } } /** * Will ensure no messages are lost if there are no event listeners. */ export class BufferedEmitter<T> { private _emitter: Emitter<T>; public readonly event: Event<T>; private _hasListeners = false; private _isDeliveringMessages = false; private _bufferedMessages: T[] = []; constructor() { this._emitter = new Emitter<T>({ onFirstListenerAdd: () => { this._hasListeners = true; // it is important to deliver these messages after this call, but before // other messages have a chance to be received (to guarantee in order delivery) // that's why we're using here nextTick and not other types of timeouts process.nextTick(() => this._deliverMessages()); }, onLastListenerRemove: () => { this._hasListeners = false; } }); this.event = this._emitter.event; } private _deliverMessages(): void { if (this._isDeliveringMessages) { return; } this._isDeliveringMessages = true; while (this._hasListeners && this._bufferedMessages.length > 0) { this._emitter.fire(this._bufferedMessages.shift()!); } this._isDeliveringMessages = false; } public fire(event: T): void { if (this._hasListeners) { if (this._bufferedMessages.length > 0) { this._bufferedMessages.push(event); } else { this._emitter.fire(event); } } else { this._bufferedMessages.push(event); } } public flushBuffer(): void { this._bufferedMessages = []; } } class QueueElement<T> { public readonly data: T; public next: QueueElement<T> | null; constructor(data: T) { this.data = data; this.next = null; } } class Queue<T> { private _first: QueueElement<T> | null; private _last: QueueElement<T> | null; constructor() { this._first = null; this._last = null; } public peek(): T | null { if (!this._first) { return null; } return this._first.data; } public toArray(): T[] { let result: T[] = [], resultLen = 0; let it = this._first; while (it) { result[resultLen++] = it.data; it = it.next; } return result; } public pop(): void { if (!this._first) { return; } if (this._first === this._last) { this._first = null; this._last = null; return; } this._first = this._first.next; } public push(item: T): void { const element = new QueueElement(item); if (!this._first) { this._first = element; this._last = element; return; } this._last!.next = element; this._last = element; } } class LoadEstimator { private static _HISTORY_LENGTH = 10; private static _INSTANCE: LoadEstimator | null = null; public static getInstance(): LoadEstimator { if (!LoadEstimator._INSTANCE) { LoadEstimator._INSTANCE = new LoadEstimator(); } return LoadEstimator._INSTANCE; } private lastRuns: number[]; constructor() { this.lastRuns = []; const now = Date.now(); for (let i = 0; i < LoadEstimator._HISTORY_LENGTH; i++) { this.lastRuns[i] = now - 1000 * i; } setInterval(() => { for (let i = LoadEstimator._HISTORY_LENGTH; i >= 1; i--) { this.lastRuns[i] = this.lastRuns[i - 1]; } this.lastRuns[0] = Date.now(); }, 1000); } /** * returns an estimative number, from 0 (low load) to 1 (high load) */ private load(): number { const now = Date.now(); const historyLimit = (1 + LoadEstimator._HISTORY_LENGTH) * 1000; let score = 0; for (let i = 0; i < LoadEstimator._HISTORY_LENGTH; i++) { if (now - this.lastRuns[i] <= historyLimit) { score++; } } return 1 - score / LoadEstimator._HISTORY_LENGTH; } public hasHighLoad(): boolean { return this.load() >= 0.5; } } export interface ILoadEstimator { hasHighLoad(): boolean; } /** * Same as Protocol, but will actually track messages and acks. * Moreover, it will ensure no messages are lost if there are no event listeners. */ export class PersistentProtocol implements IMessagePassingProtocol { private _isReconnecting: boolean; private _outgoingUnackMsg: Queue<ProtocolMessage>; private _outgoingMsgId: number; private _outgoingAckId: number; private _outgoingAckTimeout: any | null; private _incomingMsgId: number; private _incomingAckId: number; private _incomingMsgLastTime: number; private _incomingAckTimeout: any | null; private _outgoingKeepAliveTimeout: any | null; private _incomingKeepAliveTimeout: any | null; private _lastReplayRequestTime: number; private _socket: ISocket; private _socketWriter: ProtocolWriter; private _socketReader: ProtocolReader; private _socketDisposables: IDisposable[]; private readonly _loadEstimator: ILoadEstimator; private readonly _onControlMessage = new BufferedEmitter<VSBuffer>(); readonly onControlMessage: Event<VSBuffer> = this._onControlMessage.event; private readonly _onMessage = new BufferedEmitter<VSBuffer>(); readonly onMessage: Event<VSBuffer> = this._onMessage.event; private readonly _onDidDispose = new BufferedEmitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; private readonly _onSocketClose = new BufferedEmitter<SocketCloseEvent>(); readonly onSocketClose: Event<SocketCloseEvent> = this._onSocketClose.event; private readonly _onSocketTimeout = new BufferedEmitter<void>(); readonly onSocketTimeout: Event<void> = this._onSocketTimeout.event; public get unacknowledgedCount(): number { return this._outgoingMsgId - this._outgoingAckId; } constructor(socket: ISocket, initialChunk: VSBuffer | null = null, loadEstimator: ILoadEstimator = LoadEstimator.getInstance()) { this._loadEstimator = loadEstimator; this._isReconnecting = false; this._outgoingUnackMsg = new Queue<ProtocolMessage>(); this._outgoingMsgId = 0; this._outgoingAckId = 0; this._outgoingAckTimeout = null; this._incomingMsgId = 0; this._incomingAckId = 0; this._incomingMsgLastTime = 0; this._incomingAckTimeout = null; this._outgoingKeepAliveTimeout = null; this._incomingKeepAliveTimeout = null; this._lastReplayRequestTime = 0; this._socketDisposables = []; this._socket = socket; this._socketWriter = new ProtocolWriter(this._socket); this._socketDisposables.push(this._socketWriter); this._socketReader = new ProtocolReader(this._socket); this._socketDisposables.push(this._socketReader); this._socketDisposables.push(this._socketReader.onMessage(msg => this._receiveMessage(msg))); this._socketDisposables.push(this._socket.onClose((e) => this._onSocketClose.fire(e))); if (initialChunk) { this._socketReader.acceptChunk(initialChunk); } this._sendKeepAliveCheck(); this._recvKeepAliveCheck(); } dispose(): void { if (this._outgoingAckTimeout) { clearTimeout(this._outgoingAckTimeout); this._outgoingAckTimeout = null; } if (this._incomingAckTimeout) { clearTimeout(this._incomingAckTimeout); this._incomingAckTimeout = null; } if (this._outgoingKeepAliveTimeout) { clearTimeout(this._outgoingKeepAliveTimeout); this._outgoingKeepAliveTimeout = null; } if (this._incomingKeepAliveTimeout) { clearTimeout(this._incomingKeepAliveTimeout); this._incomingKeepAliveTimeout = null; } this._socketDisposables = dispose(this._socketDisposables); } drain(): Promise<void> { return this._socketWriter.drain(); } sendDisconnect(): void { const msg = new ProtocolMessage(ProtocolMessageType.Disconnect, 0, 0, getEmptyBuffer()); this._socketWriter.write(msg); this._socketWriter.flush(); } private _sendKeepAliveCheck(): void { if (this._outgoingKeepAliveTimeout) { // there will be a check in the near future return; } const timeSinceLastOutgoingMsg = Date.now() - this._socketWriter.lastWriteTime; if (timeSinceLastOutgoingMsg >= ProtocolConstants.KeepAliveTime) { // sufficient time has passed since last message was written, // and no message from our side needed to be sent in the meantime, // so we will send a message containing only a keep alive. const msg = new ProtocolMessage(ProtocolMessageType.KeepAlive, 0, 0, getEmptyBuffer()); this._socketWriter.write(msg); this._sendKeepAliveCheck(); return; } this._outgoingKeepAliveTimeout = setTimeout(() => { this._outgoingKeepAliveTimeout = null; this._sendKeepAliveCheck(); }, ProtocolConstants.KeepAliveTime - timeSinceLastOutgoingMsg + 5); } private _recvKeepAliveCheck(): void { if (this._incomingKeepAliveTimeout) { // there will be a check in the near future return; } const timeSinceLastIncomingMsg = Date.now() - this._socketReader.lastReadTime; if (timeSinceLastIncomingMsg >= ProtocolConstants.KeepAliveTimeoutTime) { // It's been a long time since we received a server message // But this might be caused by the event loop being busy and failing to read messages if (!this._loadEstimator.hasHighLoad()) { // Trash the socket this._onSocketTimeout.fire(undefined); return; } } this._incomingKeepAliveTimeout = setTimeout(() => { this._incomingKeepAliveTimeout = null; this._recvKeepAliveCheck(); }, Math.max(ProtocolConstants.KeepAliveTimeoutTime - timeSinceLastIncomingMsg, 0) + 5); } public getSocket(): ISocket { return this._socket; } public getMillisSinceLastIncomingData(): number { return Date.now() - this._socketReader.lastReadTime; } public beginAcceptReconnection(socket: ISocket, initialDataChunk: VSBuffer | null): void { this._isReconnecting = true; this._socketDisposables = dispose(this._socketDisposables); this._onControlMessage.flushBuffer(); this._onSocketClose.flushBuffer(); this._onSocketTimeout.flushBuffer(); this._socket.dispose(); this._lastReplayRequestTime = 0; this._socket = socket; this._socketWriter = new ProtocolWriter(this._socket); this._socketDisposables.push(this._socketWriter); this._socketReader = new ProtocolReader(this._socket); this._socketDisposables.push(this._socketReader); this._socketDisposables.push(this._socketReader.onMessage(msg => this._receiveMessage(msg))); this._socketDisposables.push(this._socket.onClose((e) => this._onSocketClose.fire(e))); this._socketReader.acceptChunk(initialDataChunk); } public endAcceptReconnection(): void { this._isReconnecting = false; // Send again all unacknowledged messages const toSend = this._outgoingUnackMsg.toArray(); for (let i = 0, len = toSend.length; i < len; i++) { this._socketWriter.write(toSend[i]); } this._recvAckCheck(); this._sendKeepAliveCheck(); this._recvKeepAliveCheck(); } public acceptDisconnect(): void { this._onDidDispose.fire(); } private _receiveMessage(msg: ProtocolMessage): void { if (msg.ack > this._outgoingAckId) { this._outgoingAckId = msg.ack; do { const first = this._outgoingUnackMsg.peek(); if (first && first.id <= msg.ack) { // this message has been confirmed, remove it this._outgoingUnackMsg.pop(); } else { break; } } while (true); } if (msg.type === ProtocolMessageType.Regular) { if (msg.id > this._incomingMsgId) { if (msg.id !== this._incomingMsgId + 1) { // in case we missed some messages we ask the other party to resend them const now = Date.now(); if (now - this._lastReplayRequestTime > 10000) { // send a replay request at most once every 10s this._lastReplayRequestTime = now; this._socketWriter.write(new ProtocolMessage(ProtocolMessageType.ReplayRequest, 0, 0, getEmptyBuffer())); } } else { this._incomingMsgId = msg.id; this._incomingMsgLastTime = Date.now(); this._sendAckCheck(); this._onMessage.fire(msg.data); } } } else if (msg.type === ProtocolMessageType.Control) { this._onControlMessage.fire(msg.data); } else if (msg.type === ProtocolMessageType.Disconnect) { this._onDidDispose.fire(); } else if (msg.type === ProtocolMessageType.ReplayRequest) { // Send again all unacknowledged messages const toSend = this._outgoingUnackMsg.toArray(); for (let i = 0, len = toSend.length; i < len; i++) { this._socketWriter.write(toSend[i]); } this._recvAckCheck(); } } readEntireBuffer(): VSBuffer { return this._socketReader.readEntireBuffer(); } flush(): void { this._socketWriter.flush(); } send(buffer: VSBuffer): void { const myId = ++this._outgoingMsgId; this._incomingAckId = this._incomingMsgId; const msg = new ProtocolMessage(ProtocolMessageType.Regular, myId, this._incomingAckId, buffer); this._outgoingUnackMsg.push(msg); if (!this._isReconnecting) { this._socketWriter.write(msg); this._recvAckCheck(); } } /** * Send a message which will not be part of the regular acknowledge flow. * Use this for early control messages which are repeated in case of reconnection. */ sendControl(buffer: VSBuffer): void { const msg = new ProtocolMessage(ProtocolMessageType.Control, 0, 0, buffer); this._socketWriter.write(msg); } private _sendAckCheck(): void { if (this._incomingMsgId <= this._incomingAckId) { // nothink to acknowledge return; } if (this._incomingAckTimeout) { // there will be a check in the near future return; } const timeSinceLastIncomingMsg = Date.now() - this._incomingMsgLastTime; if (timeSinceLastIncomingMsg >= ProtocolConstants.AcknowledgeTime) { // sufficient time has passed since this message has been received, // and no message from our side needed to be sent in the meantime, // so we will send a message containing only an ack. this._sendAck(); return; } this._incomingAckTimeout = setTimeout(() => { this._incomingAckTimeout = null; this._sendAckCheck(); }, ProtocolConstants.AcknowledgeTime - timeSinceLastIncomingMsg + 5); } private _recvAckCheck(): void { if (this._outgoingMsgId <= this._outgoingAckId) { // everything has been acknowledged return; } if (this._outgoingAckTimeout) { // there will be a check in the near future return; } if (this._isReconnecting) { // do not cause a timeout during reconnection, // because messages will not be actually written until `endAcceptReconnection` return; } const oldestUnacknowledgedMsg = this._outgoingUnackMsg.peek()!; const timeSinceOldestUnacknowledgedMsg = Date.now() - oldestUnacknowledgedMsg.writtenTime; if (timeSinceOldestUnacknowledgedMsg >= ProtocolConstants.AcknowledgeTimeoutTime) { // It's been a long time since our sent message was acknowledged // But this might be caused by the event loop being busy and failing to read messages if (!this._loadEstimator.hasHighLoad()) { // Trash the socket this._onSocketTimeout.fire(undefined); return; } } this._outgoingAckTimeout = setTimeout(() => { this._outgoingAckTimeout = null; this._recvAckCheck(); }, Math.max(ProtocolConstants.AcknowledgeTimeoutTime - timeSinceOldestUnacknowledgedMsg, 0) + 5); } private _sendAck(): void { if (this._incomingMsgId <= this._incomingAckId) { // nothink to acknowledge return; } this._incomingAckId = this._incomingMsgId; const msg = new ProtocolMessage(ProtocolMessageType.Ack, 0, this._incomingAckId, getEmptyBuffer()); this._socketWriter.write(msg); } }
the_stack
import { defineComponent, h, PropType, ref, Ref, computed, onUnmounted, watch, reactive, nextTick } from 'vue' import XEUtils from 'xe-utils' import GlobalConfig from '../../v-x-e-table/src/conf' import { useSize } from '../../hooks/size' import { createResizeEvent, XEResizeObserver } from '../../tools/resize' import { browse } from '../../tools/dom' import { GlobalEvent } from '../../tools/event' import VxeLoading from '../../loading/index' import { VxeListConstructor, VxeListPropTypes, VxeListEmits, ListReactData, ListInternalData, ListMethods, ListPrivateRef, VxeListMethods } from '../../../types/all' export default defineComponent({ name: 'VxeList', props: { data: Array as PropType<VxeListPropTypes.Data>, height: [Number, String] as PropType<VxeListPropTypes.Height>, maxHeight: [Number, String] as PropType<VxeListPropTypes.MaxHeight>, loading: Boolean as PropType<VxeListPropTypes.Loading>, className: [String, Function] as PropType<VxeListPropTypes.ClassName>, size: { type: String as PropType<VxeListPropTypes.Size>, default: () => GlobalConfig.list.size || GlobalConfig.size }, autoResize: { type: Boolean as PropType<VxeListPropTypes.AutoResize>, default: () => GlobalConfig.list.autoResize }, syncResize: [Boolean, String, Number] as PropType<VxeListPropTypes.SyncResize>, scrollY: Object as PropType<VxeListPropTypes.ScrollY> }, emits: [ 'scroll' ] as VxeListEmits, setup (props, context) { const { slots, emit } = context const xID = XEUtils.uniqueId() const computeSize = useSize(props) const reactData = reactive({ scrollYLoad: false, bodyHeight: 0, rowHeight: 0, topSpaceHeight: 0, items: [] } as ListReactData) const refElem = ref() as Ref<HTMLDivElement> const refVirtualWrapper = ref() as Ref<HTMLDivElement> const refVirtualBody = ref() as Ref<HTMLDivElement> const internalData: ListInternalData = { fullData: [], lastScrollLeft: 0, lastScrollTop: 0, scrollYStore: { startIndex: 0, endIndex: 0, visibleSize: 0, offsetSize: 0, rowHeight: 0 } } const refMaps: ListPrivateRef = { refElem } const $xelist = { xID, props, context, reactData, internalData, getRefMaps: () => refMaps } as unknown as VxeListConstructor & VxeListMethods let listMethods = {} as ListMethods const computeSYOpts = computed(() => { return Object.assign({} as { gt: number }, GlobalConfig.list.scrollY, props.scrollY) }) const computeStyles = computed(() => { const { height, maxHeight } = props const style: { [key: string]: string | number } = {} if (height) { style.height = `${isNaN(height as number) ? height : `${height}px`}` } else if (maxHeight) { style.height = 'auto' style.maxHeight = `${isNaN(maxHeight as number) ? maxHeight : `${maxHeight}px`}` } return style }) const updateYSpace = () => { const { scrollYLoad } = reactData const { scrollYStore, fullData } = internalData reactData.bodyHeight = scrollYLoad ? fullData.length * scrollYStore.rowHeight : 0 reactData.topSpaceHeight = scrollYLoad ? Math.max(scrollYStore.startIndex * scrollYStore.rowHeight, 0) : 0 } const handleData = () => { const { scrollYLoad } = reactData const { fullData, scrollYStore } = internalData reactData.items = scrollYLoad ? fullData.slice(scrollYStore.startIndex, scrollYStore.endIndex) : fullData.slice(0) return nextTick() } const updateYData = () => { handleData() updateYSpace() } const computeScrollLoad = () => { return nextTick().then(() => { const { scrollYLoad } = reactData const { scrollYStore } = internalData const virtualBodyElem = refVirtualBody.value const sYOpts = computeSYOpts.value let rowHeight = 0 let firstItemElem: HTMLElement | undefined if (virtualBodyElem) { if (sYOpts.sItem) { firstItemElem = virtualBodyElem.querySelector(sYOpts.sItem) as HTMLElement } if (!firstItemElem) { firstItemElem = virtualBodyElem.children[0] as HTMLElement } } if (firstItemElem) { rowHeight = firstItemElem.offsetHeight } rowHeight = Math.max(20, rowHeight) scrollYStore.rowHeight = rowHeight // 计算 Y 逻辑 if (scrollYLoad) { const scrollBodyElem = refVirtualWrapper.value const visibleYSize = Math.max(8, Math.ceil(scrollBodyElem.clientHeight / rowHeight)) const offsetYSize = sYOpts.oSize ? XEUtils.toNumber(sYOpts.oSize) : (browse.edge ? 10 : 0) scrollYStore.offsetSize = offsetYSize scrollYStore.visibleSize = visibleYSize scrollYStore.endIndex = Math.max(scrollYStore.startIndex, visibleYSize + offsetYSize, scrollYStore.endIndex) updateYData() } else { updateYSpace() } reactData.rowHeight = rowHeight }) } /** * 清除滚动条 */ const clearScroll = () => { const scrollBodyElem = refVirtualWrapper.value if (scrollBodyElem) { scrollBodyElem.scrollTop = 0 } return nextTick() } /** * 如果有滚动条,则滚动到对应的位置 * @param {Number} scrollLeft 左距离 * @param {Number} scrollTop 上距离 */ const scrollTo = (scrollLeft: number | null, scrollTop?: number | null) => { const scrollBodyElem = refVirtualWrapper.value if (XEUtils.isNumber(scrollLeft)) { scrollBodyElem.scrollLeft = scrollLeft } if (XEUtils.isNumber(scrollTop)) { scrollBodyElem.scrollTop = scrollTop } if (reactData.scrollYLoad) { return new Promise(resolve => setTimeout(() => resolve(nextTick()), 50)) } return nextTick() } /** * 刷新滚动条 */ const refreshScroll = () => { const { lastScrollLeft, lastScrollTop } = internalData return clearScroll().then(() => { if (lastScrollLeft || lastScrollTop) { internalData.lastScrollLeft = 0 internalData.lastScrollTop = 0 return scrollTo(lastScrollLeft, lastScrollTop) } }) } /** * 重新计算列表 */ const recalculate = () => { const el = refElem.value if (el.clientWidth && el.clientHeight) { return computeScrollLoad() } return Promise.resolve() } const loadYData = (evnt: Event) => { const { scrollYStore } = internalData const { startIndex, endIndex, visibleSize, offsetSize, rowHeight } = scrollYStore const scrollBodyElem = evnt.target as HTMLDivElement const scrollTop = scrollBodyElem.scrollTop const toVisibleIndex = Math.floor(scrollTop / rowHeight) const offsetStartIndex = Math.max(0, toVisibleIndex - 1 - offsetSize) const offsetEndIndex = toVisibleIndex + visibleSize + offsetSize if (toVisibleIndex <= startIndex || toVisibleIndex >= endIndex - visibleSize - 1) { if (startIndex !== offsetStartIndex || endIndex !== offsetEndIndex) { scrollYStore.startIndex = offsetStartIndex scrollYStore.endIndex = offsetEndIndex updateYData() } } } const scrollEvent = (evnt: Event) => { const scrollBodyElem = evnt.target as HTMLDivElement const scrollTop = scrollBodyElem.scrollTop const scrollLeft = scrollBodyElem.scrollLeft const isX = scrollLeft !== internalData.lastScrollLeft const isY = scrollTop !== internalData.lastScrollTop internalData.lastScrollTop = scrollTop internalData.lastScrollLeft = scrollLeft if (reactData.scrollYLoad) { loadYData(evnt) } listMethods.dispatchEvent('scroll', { scrollLeft, scrollTop, isX, isY }, evnt) } listMethods = { dispatchEvent (type, params, evnt) { emit(type, Object.assign({ $list: $xelist, $event: evnt }, params)) }, /** * 加载数据 * @param {Array} datas 数据 */ loadData (datas) { const { scrollYStore } = internalData const sYOpts = computeSYOpts.value const fullData = datas || [] Object.assign(scrollYStore, { startIndex: 0, endIndex: 1, visibleSize: 0 }) internalData.fullData = fullData reactData.scrollYLoad = !!sYOpts.enabled && sYOpts.gt > -1 && sYOpts.gt <= fullData.length handleData() return computeScrollLoad().then(() => { refreshScroll() }) }, /** * 重新加载数据 * @param {Array} datas 数据 */ reloadData (datas) { clearScroll() return listMethods.loadData(datas) }, recalculate, scrollTo, refreshScroll, clearScroll } Object.assign($xelist, listMethods) watch(() => props.data, (value) => { listMethods.loadData(value || []) }) watch(() => props.syncResize, (value) => { if (value) { recalculate() nextTick(() => setTimeout(() => recalculate())) } }) let resizeObserver: XEResizeObserver nextTick(() => { GlobalEvent.on($xelist, 'resize', () => { recalculate() }) if (props.autoResize) { const el = refElem.value resizeObserver = createResizeEvent(() => recalculate()) resizeObserver.observe(el) } listMethods.loadData(props.data || []) }) onUnmounted(() => { if (resizeObserver) { resizeObserver.disconnect() } GlobalEvent.off($xelist, 'resize') }) const renderVN = () => { const { className, loading } = props const { bodyHeight, topSpaceHeight, items } = reactData const vSize = computeSize.value const styles = computeStyles.value return h('div', { ref: refElem, class: ['vxe-list', className ? (XEUtils.isFunction(className) ? className({ $list: $xelist }) : className) : '', { [`size--${vSize}`]: vSize, 'is--loading': loading }] }, [ h('div', { ref: refVirtualWrapper, class: 'vxe-list--virtual-wrapper', style: styles, onScroll: scrollEvent }, [ h('div', { class: 'vxe-list--y-space', style: { height: bodyHeight ? `${bodyHeight}px` : '' } }), h('div', { ref: refVirtualBody, class: 'vxe-list--body', style: { marginTop: topSpaceHeight ? `${topSpaceHeight}px` : '' } }, slots.default ? slots.default({ items, $list: $xelist }) : []) ]), /** * 加载中 */ h(VxeLoading, { class: 'vxe-list--loading', loading }) ]) } $xelist.renderVN = renderVN return $xelist }, render () { return this.renderVN() } })
the_stack
import { createTestEnv_artwork } from "v2/__generated__/createTestEnv_artwork.graphql" import { createTestEnvCreditCardMutation } from "v2/__generated__/createTestEnvCreditCardMutation.graphql" import { createTestEnvOrderMutation } from "v2/__generated__/createTestEnvOrderMutation.graphql" import { createTestEnvQueryRawResponse } from "v2/__generated__/createTestEnvQuery.graphql" import { createTestEnv } from "v2/DevTools/createTestEnv" import { RootTestPage, expectOne } from "v2/DevTools/RootTestPage" import { RelayProp, commitMutation, createFragmentContainer, graphql, } from "react-relay" jest.unmock("react-relay") const orderMutation = // TODO: Inputs to the mutation might have changed case of the keys! graphql` mutation createTestEnvOrderMutation( $input: CommerceCreateOrderWithArtworkInput! ) { commerceCreateOrderWithArtwork(input: $input) { orderOrError { ... on CommerceOrderWithMutationSuccess { order { internalID } } ... on CommerceOrderWithMutationFailure { error { type } } } } } ` const orderSuccess = { commerceCreateOrderWithArtwork: { orderOrError: { __typename: "CommerceOrderWithMutationSuccess", order: { __typename: "CommerceBuyOrder", internalID: "order-id", }, }, }, } const orderFailure = { commerceCreateOrderWithArtwork: { orderOrError: { __typename: "CommerceOrderWithMutationFailure", error: { type: "order-error", }, }, }, } const creditCardMutation = // TODO: Inputs to the mutation might have changed case of the keys! graphql` mutation createTestEnvCreditCardMutation($input: CreditCardInput!) { createCreditCard: createCreditCard(input: $input) { creditCardOrError { ... on CreditCardMutationSuccess { creditCard { brand } } ... on CreditCardMutationFailure { mutationError { type } } } } } ` const creditCardSuccess = { createCreditCard: { creditCardOrError: { __typename: "CreditCardMutationSuccess", creditCard: { brand: "mastercard! visa!", }, }, }, } const creditCardFailure = { createCreditCard: { creditCardOrError: { __typename: "CreditCardMutationFailure", mutationError: { type: "card-error", }, }, }, } const onCompleted = jest.fn() const onError = jest.fn() const Component = createFragmentContainer( ({ relay, artwork, }: { relay: RelayProp artwork: createTestEnv_artwork }) => ( <div> <h1>This is the main heading</h1> <p> {/* @ts-expect-error PLEASE_FIX_ME_STRICT_NULL_CHECK_MIGRATION */} The artwork is {artwork.title} by {artwork.artist.name} </p> <button onClick={() => commitMutation<createTestEnvOrderMutation>(relay.environment, { onCompleted, onError, variables: { input: { artworkId: "artwork-id" } }, // tslint:disable-next-line:relay-operation-generics mutation: orderMutation, }) } > create the order </button> <button onClick={() => commitMutation<createTestEnvCreditCardMutation>(relay.environment, { onCompleted, onError, variables: { input: { token: "card-token", oneTimeUse: true } }, // tslint:disable-next-line:relay-operation-generics mutation: creditCardMutation, }) } > create the credit card </button> </div> ), { artwork: graphql` fragment createTestEnv_artwork on Artwork { title artist { name } } `, } ) describe("test envs", () => { const { buildPage, mutations, ...hooks } = createTestEnv({ Component, TestPage: class MyTestPage extends RootTestPage { get heading() { return expectOne(this.find("h1")) } get orderSubmitButton() { return expectOne( this.find("button").filterWhere(button => button.text().includes("create the order") ) ) } get creditCardSubmitButton() { return expectOne( this.find("button").filterWhere(button => button.text().includes("create the credit card") ) ) } }, defaultData: { artwork: { title: "Test Artwork", artist: { name: "David Sheldrick" }, }, } as createTestEnvQueryRawResponse, defaultMutationResults: { ...orderSuccess, ...creditCardSuccess, }, query: graphql` query createTestEnvQuery @raw_response_type { artwork(id: "unused") { ...createTestEnv_artwork } } `, }) beforeEach(() => { onCompleted.mockReset() onError.mockReset() hooks.clearErrors() }) afterEach(hooks.clearMocksAndErrors) it("lets you make a page", async () => { const page = await buildPage() expect(page.heading.text()).toMatchInlineSnapshot( `"This is the main heading"` ) expect(page.find("p").text()).toMatchInlineSnapshot( `"The artwork is Test Artwork by David Sheldrick"` ) expect(page.orderSubmitButton).toBeTruthy() expect(page.creditCardSubmitButton).toBeTruthy() }) it("lets you override the default data", async () => { const page = await buildPage({ mockData: { artwork: { title: "New Artwork", artist: { name: "Daisy O'Doherty", }, }, }, }) expect(page.find("p").text()).toMatchInlineSnapshot( `"The artwork is New Artwork by Daisy O'Doherty"` ) }) it("lets you commit mutations", async () => { const page = await buildPage() page.creditCardSubmitButton.simulate("click") await page.update() expect(mutations.resolvers.createCreditCard).toHaveBeenCalled() expect(mutations.lastFetchVariables).toMatchObject({ input: { oneTimeUse: true, token: "card-token", }, }) expect(onCompleted).toHaveBeenCalledTimes(1) expect( onCompleted.mock.calls[0][0].createCreditCard.creditCardOrError.creditCard ).toMatchObject( creditCardSuccess.createCreditCard.creditCardOrError.creditCard ) }) it("lets you change the mutations results at any time", async () => { const page = await buildPage() page.creditCardSubmitButton.simulate("click") await page.update() expect(onCompleted).toHaveBeenCalledTimes(1) expect(onError).toHaveBeenCalledTimes(0) expect( onCompleted.mock.calls[0][0].createCreditCard.creditCardOrError.creditCard ).toMatchObject( creditCardSuccess.createCreditCard.creditCardOrError.creditCard ) mutations.useResultsOnce(creditCardFailure) page.creditCardSubmitButton.simulate("click") await page.update() expect(onCompleted).toHaveBeenCalledTimes(2) expect(onError).toHaveBeenCalledTimes(0) expect( onCompleted.mock.calls[1][0].createCreditCard.creditCardOrError .mutationError ).toMatchObject( creditCardFailure.createCreditCard.creditCardOrError.mutationError ) }) it("lets you simulate a network error", async () => { const page = await buildPage() mutations.mockNetworkFailureOnce() page.creditCardSubmitButton.simulate("click") await page.update() expect(onCompleted).not.toHaveBeenCalled() expect(onError).toHaveBeenCalledTimes(1) }) it("lets you do more than one mutation type", async () => { const page = await buildPage() page.orderSubmitButton.simulate("click") page.creditCardSubmitButton.simulate("click") await page.update() expect(onCompleted).toHaveBeenCalledTimes(2) expect( onCompleted.mock.calls[0][0].commerceCreateOrderWithArtwork.orderOrError ).toMatchObject({ order: {} }) expect( onCompleted.mock.calls[1][0].createCreditCard.creditCardOrError ).toMatchObject({ creditCard: {} }) onCompleted.mockReset() mutations.useResultsOnce({ ...creditCardFailure, ...orderFailure, }) page.orderSubmitButton.simulate("click") page.creditCardSubmitButton.simulate("click") await page.update() expect( onCompleted.mock.calls[0][0].commerceCreateOrderWithArtwork.orderOrError ).toMatchObject({ error: {} }) expect( onCompleted.mock.calls[1][0].createCreditCard.creditCardOrError ).toMatchObject({ mutationError: {} }) }) it("resets the mutation mocks after every test", () => { expect(mutations.resolvers.createCreditCard).not.toHaveBeenCalled() expect( mutations.resolvers.commerceCreateOrderWithArtwork ).not.toHaveBeenCalled() }) it("lets you inspect mutation variables", async () => { const page = await buildPage() page.orderSubmitButton.simulate("click") expect(mutations.lastFetchVariables).toMatchObject({ input: { artworkId: "artwork-id", }, }) await page.update() page.creditCardSubmitButton.simulate("click") expect(mutations.lastFetchVariables).toMatchObject({ input: { oneTimeUse: true, token: "card-token", }, }) }) it("doesn't matter if you call mutations.useResultsOnce before or after buildPage", async () => { mutations.useResultsOnce(orderFailure) const page = await buildPage() page.orderSubmitButton.simulate("click") await page.update() expect( onCompleted.mock.calls[0][0].commerceCreateOrderWithArtwork.orderOrError ).toMatchObject({ error: {} }) }) it("stacks .useResultsOnce calls", async () => { mutations.useResultsOnce(orderFailure) mutations.useResultsOnce(orderFailure) const page = await buildPage() page.orderSubmitButton.simulate("click") await page.update() expect( onCompleted.mock.calls[0][0].commerceCreateOrderWithArtwork.orderOrError ).toMatchObject({ error: {} }) page.orderSubmitButton.simulate("click") await page.update() expect( onCompleted.mock.calls[1][0].commerceCreateOrderWithArtwork.orderOrError ).toMatchObject({ error: {} }) page.orderSubmitButton.simulate("click") await page.update() expect( mutations.resolvers.commerceCreateOrderWithArtwork ).toHaveBeenCalledTimes(3) expect(onCompleted).toHaveBeenCalledTimes(3) expect( onCompleted.mock.calls[2][0].commerceCreateOrderWithArtwork.orderOrError ).toMatchObject({ order: {} }) }) })
the_stack
import { TileKey } from "@here/harp-geoutils"; import { expect } from "chai"; import * as sinon from "sinon"; import * as THREE from "three"; import { MapView } from "../lib/MapView"; import { PickHandler } from "../lib/PickHandler"; import { Tile } from "../lib/Tile"; describe("PickHandler", function () { let pickHandler: PickHandler; let mapViewMock: MapView; let tile: Tile; beforeEach(function () { const size = new THREE.Vector2(800, 600); const camera = new THREE.PerspectiveCamera(); tile = ({ boundingBox: { extents: new THREE.Vector3(1252344.2714, 1252344.2714, 11064), position: new THREE.Vector3(21289852.6142, 26299229.6999, 11064), xAxis: new THREE.Vector3(1, 0, 0), yAxis: new THREE.Vector3(0, 1, 0), zAxis: new THREE.Vector3(0, 0, 1) }, computeWorldOffsetX: () => 0, dependencies: [], tileKey: TileKey.fromRowColumnLevel(1, 2, 3) } as unknown) as Tile; mapViewMock = ({ camera, worldCenter: new THREE.Vector3(21429001.9777, 25228494.0575, 2160787.9966), renderer: { getSize: () => size }, mapAnchors: { children: [] }, getNormalizedScreenCoordinates: (x: number, y: number) => new THREE.Vector3(x / size.x - 1, -y / size.y + 1, 0), visibleTileSet: { dataSourceTileList: [ { dataSource: { enablePicking: true }, renderedTiles: new Map().set(1, tile) } ] }, getWorldPositionAt: () => {} // to be overridden (by stubs) for given coords } as unknown) as MapView; pickHandler = new PickHandler(mapViewMock, camera, true); }); describe("#intersectMapObjects", function () { let raycasterFromScreenPointStub: sinon.SinonStub<[x: number, y: number], THREE.Raycaster>; beforeEach(function () { raycasterFromScreenPointStub = sinon.stub(pickHandler, "raycasterFromScreenPoint"); }); it("collects results for objects based on '.faceIndex' of intersection", function () { sinon .stub(mapViewMock, "getWorldPositionAt") .callsFake(() => new THREE.Vector3(21604645.272347387, 25283546.433446992, 0)); raycasterFromScreenPointStub.callsFake((x: number, y: number) => { const raycaster = raycasterFromScreenPointStub.wrappedMethod.call( pickHandler, x, y ); sinon .stub(raycaster, "intersectObjects") .callsFake((objects, recursive, target: THREE.Intersection[] = []) => { // contains ".face" and ".faceIndex", but doesn't contain ".index" target.push({ distance: 2168613.8654252696, point: new THREE.Vector3(175643.2946, 55052.3759, -2160787.9966), face: { a: 1661, b: 1737, c: 1736, materialIndex: 0, normal: new THREE.Vector3(0, 0, 1) }, faceIndex: 1653, object: ({ renderOrder: 1000, userData: { dataSource: "geojson", feature: { geometryType: 7, starts: [ 0, 558, 690, 1329, 1704, 2169, 2448, 2778, 3282, 3726, 3789, 3795, 3804, 3810, 3816, 3822, 3825, 4128, 4131, 4383, 4797, 5031, 5223, 5370, 5523, 5550, 5658, 5688, 5694 ], objInfos: [ // duplicate entries are taken from original multi-polygons // and correspond to the index defined in ".starts" { $id: "KLRKDk6pCr", name: "piemonte" }, { $id: "XBfAalZEh7", name: "valle d'aosta" }, { $id: "Xgfuk2roHZ", name: "lombardia" }, { $id: "pJMwZ8oREr", name: "trentino-alto adige" }, { $id: "ZKFRobO3Pm", name: "veneto" }, { $id: "QogIXpZ2Z6", name: "friuli venezia giulia" }, { $id: "Qu7fcJcV84", name: "liguria" }, { $id: "7FkQc7sUxe", name: "emilia-romagna" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "vaPSWJfKuh", name: "umbria" }, { $id: "vaPSWJfKuh", name: "umbria" }, { $id: "ZOU85Bs5O0", name: "marche" }, { $id: "jmfNYjkZJr", name: "lazio" }, { $id: "yVgD20bhJO", name: "abruzzo" }, { $id: "GwuetqFMcf", name: "molise" }, { $id: "2J3GTgA5fc", name: "campania" }, { $id: "tZ9VB13xm1", name: "puglia" }, { $id: "GT1soJEJke", name: "basilicata" }, { $id: "z3HpNZ0YaQ", name: "sardegna" }, { $id: "z3HpNZ0YaQ", name: "sardegna" }, { $id: "z3HpNZ0YaQ", name: "sardegna" }, { $id: "z3HpNZ0YaQ", name: "sardegna" } ] } } } as unknown) as THREE.Object3D }); return target; }); return raycaster; }); const results = pickHandler.intersectMapObjects(467, 279); expect(results).not.to.be.empty; expect(results[0].featureId).to.equal("yVgD20bhJO"); expect(results[0].userData).to.deep.equal({ $id: "yVgD20bhJO", name: "abruzzo" }); }); it("collects results for objects based on '.index' of intersection", function () { sinon .stub(mapViewMock, "getWorldPositionAt") .callsFake(() => new THREE.Vector3(21604645.272347387, 25315004.93397993, 0)); raycasterFromScreenPointStub.callsFake((x: number, y: number) => { const raycaster = raycasterFromScreenPointStub.wrappedMethod.call( pickHandler, x, y ); sinon .stub(raycaster, "intersectObjects") .callsFake((objects, recursive, target: THREE.Intersection[] = []) => { // contains ".index", but doesn't contain ".face" and ".faceIndex" target.push({ distance: 2168743.4081880464, point: new THREE.Vector3(174781.2243, 62415.6655, -2160787.9966), index: 3318, object: ({ renderOrder: 1000, userData: { dataSource: "geojson", feature: { geometryType: 7, starts: [ 0, 378, 472, 904, 1160, 1476, 1668, 1894, 2234, 2536, 2584, 2594, 2606, 2616, 2626, 2636, 2644, 2852, 2860, 3034, 3316, 3478, 3612, 3712, 3828, 3848, 3922, 3948, 3958 ], objInfos: [ { $id: "KLRKDk6pCr", name: "piemonte" }, { $id: "XBfAalZEh7", name: "valle d'aosta" }, { $id: "Xgfuk2roHZ", name: "lombardia" }, { $id: "pJMwZ8oREr", name: "trentino-alto adige" }, { $id: "ZKFRobO3Pm", name: "veneto" }, { $id: "QogIXpZ2Z6", name: "friuli venezia giulia" }, { $id: "Qu7fcJcV84", name: "liguria" }, { $id: "7FkQc7sUxe", name: "emilia-romagna" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "cWl3QbtsTR", name: "toscana" }, { $id: "vaPSWJfKuh", name: "umbria" }, { $id: "vaPSWJfKuh", name: "umbria" }, { $id: "ZOU85Bs5O0", name: "marche" }, { $id: "jmfNYjkZJr", name: "lazio" }, { $id: "yVgD20bhJO", name: "abruzzo" }, { $id: "GwuetqFMcf", name: "molise" }, { $id: "2J3GTgA5fc", name: "campania" }, { $id: "tZ9VB13xm1", name: "puglia" }, { $id: "GT1soJEJke", name: "basilicata" }, { $id: "z3HpNZ0YaQ", name: "sardegna" }, { $id: "z3HpNZ0YaQ", name: "sardegna" }, { $id: "z3HpNZ0YaQ", name: "sardegna" }, { $id: "z3HpNZ0YaQ", name: "sardegna" } ] } } } as unknown) as THREE.Object3D }); return target; }); return raycaster; }); const results = pickHandler.intersectMapObjects(467, 276); expect(results).not.to.be.empty; expect(results[0].featureId).to.equal("yVgD20bhJO"); expect(results[0].userData).to.deep.equal({ $id: "yVgD20bhJO", name: "abruzzo" }); }); it("returns an array of PickResult objects each having the expected properties", function () { sinon .stub(mapViewMock, "getWorldPositionAt") .callsFake(() => new THREE.Vector3(21604645.272347387, 25315004.93397993, 0)); raycasterFromScreenPointStub.callsFake((x: number, y: number) => { const raycaster = raycasterFromScreenPointStub.wrappedMethod.call( pickHandler, x, y ); sinon .stub(raycaster, "intersectObjects") .callsFake((objects, recursive, target: THREE.Intersection[] = []) => { target.push({ point: new THREE.Vector3(174781.2243, 62415.6655, -2160787.9966), distance: 2168613.8654252696, object: ({ userData: {} } as any) as THREE.Object3D }); return target; }); return raycaster; }); const results = pickHandler.intersectMapObjects(467, 276); expect(results).not.to.be.empty; expect(results[0].tileKey).to.equal(tile.tileKey); // TODO: expand to other properties in PickResult }); }); });
the_stack
import './segment_list.css'; import debounce from 'lodash/debounce'; import throttle from 'lodash/throttle'; import {SegmentationDisplayState, SegmentWidgetWithExtraColumnsFactory} from 'neuroglancer/segmentation_display_state/frontend'; import {changeTagConstraintInSegmentQuery, executeSegmentQuery, ExplicitIdQuery, FilterQuery, findQueryResultIntersectionSize, forEachQueryResultSegmentId, InlineSegmentNumericalProperty, isQueryUnconstrained, NumericalPropertyConstraint, parseSegmentQuery, PreprocessedSegmentPropertyMap, PropertyHistogram, queryIncludesColumn, QueryResult, unparseSegmentQuery, updatePropertyHistograms} from 'neuroglancer/segmentation_display_state/property_map'; import type {SegmentationUserLayer} from 'neuroglancer/segmentation_user_layer'; import {observeWatchable, WatchableValue, WatchableValueInterface} from 'neuroglancer/trackable_value'; import {getDefaultSelectBindings} from 'neuroglancer/ui/default_input_event_bindings'; import {animationFrameDebounce} from 'neuroglancer/util/animation_frame_debounce'; import {ArraySpliceOp, getMergeSplices} from 'neuroglancer/util/array'; import {setClipboard} from 'neuroglancer/util/clipboard'; import {RefCounted} from 'neuroglancer/util/disposable'; import {removeChildren, updateInputFieldWidth} from 'neuroglancer/util/dom'; import {EventActionMap, KeyboardEventBinder, registerActionListener} from 'neuroglancer/util/keyboard_bindings'; import {MouseEventBinder} from 'neuroglancer/util/mouse_bindings'; import {neverSignal, Signal} from 'neuroglancer/util/signal'; import {Uint64} from 'neuroglancer/util/uint64'; import {CheckboxIcon} from 'neuroglancer/widget/checkbox_icon'; import {makeCopyButton} from 'neuroglancer/widget/copy_button'; import {DependentViewWidget} from 'neuroglancer/widget/dependent_view_widget'; import {Tab} from 'neuroglancer/widget/tab_view'; import {VirtualList, VirtualListSource} from 'neuroglancer/widget/virtual_list'; import {clampToInterval, computeInvlerp, dataTypeCompare, DataTypeInterval, dataTypeIntervalEqual, getClampedInterval, getIntervalBoundsEffectiveFraction, parseDataTypeValue} from 'neuroglancer/util/lerp'; import {CdfController, getUpdatedRangeAndWindowParameters, RangeAndWindowIntervals} from 'neuroglancer/widget/invlerp'; import {makeToolButton} from 'neuroglancer/ui/tool'; import {ANNOTATE_MERGE_SEGMENTS_TOOL_ID, ANNOTATE_SPLIT_SEGMENTS_TOOL_ID} from 'neuroglancer/ui/segment_split_merge_tools'; const tempUint64 = new Uint64(); class SegmentListSource extends RefCounted implements VirtualListSource { length: number; changed = new Signal<(splices: readonly Readonly<ArraySpliceOp>[]) => void>(); // The segment list is the concatenation of two lists: the `explicitSegments` list, specified as // explicit uint64 ids, and the `matches`, list, specifying the indices into the // `segmentPropertyMap` of the matching segments. explicitSegments: Uint64[]|undefined; explicitSegmentsVisible: boolean = false; visibleSegmentsGeneration = -1; prevQuery: string|undefined; queryResult = new WatchableValue<QueryResult|undefined>(undefined); statusText = new WatchableValue<string>(''); selectedMatches: number = 0; matchStatusTextPrefix: string = ''; get numMatches() { return this.queryResult.value?.count ?? 0; } private update() { const query = this.query.value; const {segmentPropertyMap} = this; const prevQueryResult = this.queryResult.value; let queryResult: QueryResult; if (this.prevQuery === query) { queryResult = prevQueryResult!; } else { const queryParseResult = parseSegmentQuery(segmentPropertyMap, query); queryResult = executeSegmentQuery(segmentPropertyMap, queryParseResult); } const splices: ArraySpliceOp[] = []; let changed = false; let matchStatusTextPrefix = ''; const {visibleSegments} = this.segmentationDisplayState.segmentationGroupState.value; const visibleSegmentsGeneration = visibleSegments.changed.count; const prevVisibleSegmentsGeneration = this.visibleSegmentsGeneration; const unconstrained = isQueryUnconstrained(queryResult.query); if (unconstrained) { // Full list of visible segments is shown only if no query is specified. if (prevVisibleSegmentsGeneration !== visibleSegmentsGeneration || this.explicitSegments === undefined || !this.explicitSegmentsVisible) { this.visibleSegmentsGeneration = visibleSegmentsGeneration; const newSortedVisibleSegments = Array.from(visibleSegments, x => x.clone()); newSortedVisibleSegments.sort(Uint64.compare); const {explicitSegments} = this; if (explicitSegments === undefined) { this.explicitSegments = newSortedVisibleSegments; splices.push( {retainCount: 0, insertCount: newSortedVisibleSegments.length, deleteCount: 0}); } else { splices.push( ...getMergeSplices(explicitSegments, newSortedVisibleSegments, Uint64.compare)); } this.explicitSegments = newSortedVisibleSegments; changed = true; } else { splices.push({retainCount: this.explicitSegments.length, deleteCount: 0, insertCount: 0}); } this.explicitSegmentsVisible = true; } else { this.visibleSegmentsGeneration = visibleSegmentsGeneration; if (this.explicitSegments !== undefined && this.explicitSegmentsVisible) { splices.push({deleteCount: this.explicitSegments.length, retainCount: 0, insertCount: 0}); this.explicitSegments = undefined; changed = true; } this.explicitSegmentsVisible = false; } const {explicitIds} = queryResult; if (explicitIds !== undefined) { this.explicitSegments = explicitIds; } else if (!this.explicitSegmentsVisible) { this.explicitSegments = undefined; } if (prevQueryResult !== queryResult) { splices.push({ retainCount: 0, deleteCount: prevQueryResult?.count ?? 0, insertCount: queryResult.count, }); changed = true; this.queryResult.value = queryResult; } if (queryResult.explicitIds !== undefined) { matchStatusTextPrefix = `${queryResult.count} ids`; } else if (unconstrained) { matchStatusTextPrefix = `${queryResult.count} listed ids`; } else if (queryResult.total > 0) { matchStatusTextPrefix = `${queryResult.count}/${queryResult.total} matches`; } if (prevQueryResult !== queryResult || visibleSegmentsGeneration !== prevVisibleSegmentsGeneration) { let statusText = matchStatusTextPrefix; let selectedMatches = 0; if (segmentPropertyMap !== undefined && queryResult.count > 0) { // Recompute selectedMatches. selectedMatches = findQueryResultIntersectionSize(segmentPropertyMap, queryResult, visibleSegments); statusText += ` (${selectedMatches} visible)`; } this.selectedMatches = selectedMatches; this.statusText.value = statusText; } this.prevQuery = query; this.matchStatusTextPrefix = matchStatusTextPrefix; const {explicitSegments} = this; this.length = (this.explicitSegmentsVisible ? explicitSegments!.length : 0) + queryResult.count; if (changed) { this.changed.dispatch(splices); } } debouncedUpdate = debounce(() => this.update(), 0); constructor( public query: WatchableValueInterface<string>, public segmentPropertyMap: PreprocessedSegmentPropertyMap|undefined, public segmentationDisplayState: SegmentationDisplayState, public parentElement: HTMLElement) { super(); this.update(); this.registerDisposer( segmentationDisplayState.segmentationGroupState.value.visibleSegments.changed.add( this.debouncedUpdate)); this.registerDisposer(query.changed.add(this.debouncedUpdate)); } private updateRendering(element: HTMLElement) { this.segmentWidgetFactory.update(element); } segmentWidgetFactory: SegmentWidgetWithExtraColumnsFactory; render = (index: number) => { const {explicitSegments} = this; let id: Uint64; let visibleList = false; if (explicitSegments !== undefined && index < explicitSegments.length) { id = explicitSegments[index]; visibleList = this.explicitSegmentsVisible; } else { if (explicitSegments !== undefined) { index -= explicitSegments.length; } id = tempUint64; const propIndex = this.queryResult.value!.indices![index]; const {ids} = this.segmentPropertyMap!.segmentPropertyMap.inlineProperties!; id.low = ids[propIndex * 2]; id.high = ids[propIndex * 2 + 1]; } const container = this.segmentWidgetFactory.get(id); if (visibleList) { container.dataset.visibleList = 'true'; } return container; }; updateRenderedItems(list: VirtualList) { list.forEachRenderedItem(element => { this.updateRendering(element); }); } } const keyMap = EventActionMap.fromObject({ 'enter': {action: 'toggle-listed'}, 'shift+enter': {action: 'hide-listed'}, 'control+enter': {action: 'hide-all'}, 'escape': {action: 'cancel'}, }); const selectSegmentConfirmationThreshold = 100; interface NumericalBoundElements { container: HTMLElement; inputs: [HTMLInputElement, HTMLInputElement]; spacers: [HTMLElement, HTMLElement, HTMLElement]|undefined; } interface NumericalPropertySummary { element: HTMLElement; controller: CdfController<RangeAndWindowIntervals>; property: InlineSegmentNumericalProperty; boundElements: { window: NumericalBoundElements, range: NumericalBoundElements, }; plotImg: HTMLImageElement; propertyHistogram: PropertyHistogram|undefined; bounds: RangeAndWindowIntervals; columnCheckbox: HTMLInputElement; sortIcon: HTMLElement; } function updateInputBoundWidth(inputElement: HTMLInputElement) { updateInputFieldWidth(inputElement, Math.max(1, inputElement.value.length + 0.1)); } function updateInputBoundValue(inputElement: HTMLInputElement, bound: number) { let boundString: string; if (Number.isInteger(bound)) { boundString = bound.toString(); } else { const sFull = bound.toString(); const sPrecision = bound.toPrecision(6); boundString = (sFull.length < sPrecision.length) ? sFull : sPrecision; } inputElement.value = boundString; updateInputBoundWidth(inputElement); } function createBoundInput(boundType: 'range'|'window', endpointIndex: 0|1) { const e = document.createElement('input'); e.addEventListener('focus', () => { e.select(); }); e.classList.add(`neuroglancer-segment-query-result-numerical-plot-${boundType}-bound`); e.classList.add('neuroglancer-segment-query-result-numerical-plot-bound'); e.type = 'text'; e.spellcheck = false; e.autocomplete = 'off'; e.title = (endpointIndex === 0 ? 'Lower' : 'Upper') + ' bound ' + (boundType === 'range' ? 'range' : 'for distribution'); e.addEventListener('input', () => { updateInputBoundWidth(e); }); return e; } function toggleIncludeColumn( queryResult: QueryResult|undefined, setQuery: (query: FilterQuery) => void, fieldId: string) { if (queryResult === undefined) return; if (queryResult.indices === undefined) return; const query = queryResult.query as FilterQuery; let {sortBy, includeColumns} = query; const included = queryIncludesColumn(query, fieldId); if (included) { sortBy = sortBy.filter(x => x.fieldId !== fieldId); includeColumns = includeColumns.filter(x => x !== fieldId); } else { includeColumns.push(fieldId); } setQuery({...query, sortBy, includeColumns}); } function toggleSortOrder( queryResult: QueryResult|undefined, setQuery: (query: FilterQuery) => void, id: string) { const query = queryResult?.query; const sortBy = query?.sortBy; if (sortBy === undefined) return; const {includeColumns} = (query as FilterQuery); const prevOrder = sortBy.find(x => x.fieldId === id)?.order; const newOrder = (prevOrder === '<') ? '>' : '<'; const newIncludeColumns = includeColumns.filter(x => x !== id); for (const s of sortBy) { if (s.fieldId !== 'id' && s.fieldId !== 'label' && s.fieldId !== id) { newIncludeColumns.push(s.fieldId); } } setQuery({ ...query as FilterQuery, sortBy: [{fieldId: id, order: newOrder}], includeColumns: newIncludeColumns, }); } function updateColumnSortIcon( queryResult: QueryResult|undefined, sortIcon: HTMLElement, id: string) { const sortBy = queryResult?.query?.sortBy; const order = sortBy?.find(s => s.fieldId === id)?.order; sortIcon.textContent = order === '>' ? '▼' : '▲'; sortIcon.style.visibility = order === undefined ? '' : 'visible'; sortIcon.title = `Sort by ${id} in ${order === '<' ? 'descending' : 'ascending'} order`; } class NumericalPropertiesSummary extends RefCounted { listElement: HTMLElement|undefined; properties: NumericalPropertySummary[]; propertyHistograms: PropertyHistogram[] = []; bounds = { window: new WatchableValue<DataTypeInterval[]>([]), range: new WatchableValue<DataTypeInterval[]>([]), }; throttledUpdate = this.registerCancellable(throttle(() => this.updateHistograms(), 100)); debouncedRender = this.registerCancellable(animationFrameDebounce(() => this.updateHistogramRenderings())); debouncedSetQuery = this.registerCancellable(debounce(() => this.setQueryFromBounds(), 200)); constructor( public segmentPropertyMap: PreprocessedSegmentPropertyMap|undefined, public queryResult: WatchableValueInterface<QueryResult|undefined>, public setQuery: (query: FilterQuery) => void) { super(); const properties = segmentPropertyMap?.numericalProperties; const propertySummaries: NumericalPropertySummary[] = []; let listElement: HTMLElement|undefined; if (properties !== undefined && properties.length > 0) { listElement = document.createElement('details'); const summaryElement = document.createElement('summary'); summaryElement.textContent = `${properties.length} numerical propert${properties.length > 1 ? 'ies' : 'y'}`; listElement.appendChild(summaryElement); listElement.classList.add('neuroglancer-segment-query-result-numerical-list'); const windowBounds = this.bounds.window.value; for (let i = 0, numProperties = properties.length; i < numProperties; ++i) { const property = properties[i]; const summary = this.makeNumericalPropertySummary(i, property); propertySummaries.push(summary); listElement.appendChild(summary.element); windowBounds[i] = property.bounds; } } this.listElement = listElement; this.properties = propertySummaries; this.registerDisposer(this.queryResult.changed.add(() => { this.handleNewQueryResult(); })); // When window bounds change, we need to recompute histograms. Throttle this to avoid // excessive computation time. this.registerDisposer(this.bounds.window.changed.add(this.throttledUpdate)); // When window bounds or constraint bounds change, re-render the plot on the next animation // frame. this.registerDisposer(this.bounds.window.changed.add(this.debouncedRender)); this.registerDisposer(this.bounds.range.changed.add(this.debouncedRender)); this.registerDisposer(this.bounds.range.changed.add(this.debouncedSetQuery)); this.handleNewQueryResult(); } private setQueryFromBounds() { const queryResult = this.queryResult.value; if (queryResult === undefined) return; if (queryResult.indices === undefined) return; const query = queryResult.query as FilterQuery; const numericalConstraints: NumericalPropertyConstraint[] = []; const constraintBounds = this.bounds.range.value; const {properties} = this; for (let i = 0, numProperties = properties.length; i < numProperties; ++i) { const property = properties[i].property; numericalConstraints.push({fieldId: property.id, bounds: constraintBounds[i]}); } this.setQuery({...query, numericalConstraints}); } private getBounds(propertyIndex: number) { const {bounds} = this; return {range: bounds.range.value[propertyIndex], window: bounds.window.value[propertyIndex]}; } private setBounds(propertyIndex: number, value: RangeAndWindowIntervals) { const {property} = this.properties[propertyIndex]; let newRange = getClampedInterval(property.bounds, value.range); if (dataTypeCompare(newRange[0], newRange[1]) > 0) { newRange = [newRange[1], newRange[0]] as DataTypeInterval; } const newWindow = getClampedInterval(property.bounds, value.window); const oldValue = this.getBounds(propertyIndex); const {dataType} = this.properties[propertyIndex].property; if (!dataTypeIntervalEqual(dataType, newWindow, oldValue.window)) { this.bounds.window.value[propertyIndex] = newWindow; this.bounds.window.changed.dispatch(); } if (!dataTypeIntervalEqual(dataType, newRange, oldValue.range)) { this.bounds.range.value[propertyIndex] = newRange; this.bounds.range.changed.dispatch(); } } private setBound( boundType: 'range'|'window', endpoint: 0|1, propertyIndex: number, value: number) { const property = this.segmentPropertyMap!.numericalProperties[propertyIndex]; const baseBounds = property.bounds; value = clampToInterval(baseBounds, value) as number; const params = this.getBounds(propertyIndex); const newParams = getUpdatedRangeAndWindowParameters( params, boundType, endpoint, value, /*fitRangeInWindow=*/ true); this.setBounds(propertyIndex, newParams); } private handleNewQueryResult() { const queryResult = this.queryResult.value; const {listElement} = this; if (listElement === undefined) return; if (queryResult?.indices !== undefined) { const {numericalConstraints} = (queryResult!.query as FilterQuery); const {numericalProperties} = this.segmentPropertyMap!; const constraintBounds = this.bounds.range.value; const numConstraints = numericalConstraints.length; const numProperties = numericalProperties.length; constraintBounds.length = numProperties; for (let i = 0; i < numProperties; ++i) { constraintBounds[i] = numericalProperties[i].bounds; } for (let i = 0; i < numConstraints; ++i) { const constraint = numericalConstraints[i]; const propertyIndex = numericalProperties.findIndex(p => p.id === constraint.fieldId); constraintBounds[propertyIndex] = constraint.bounds; } } this.updateHistograms(); this.throttledUpdate.cancel(); } private updateHistograms() { const queryResult = this.queryResult.value; const {listElement} = this; if (listElement === undefined) return; updatePropertyHistograms( this.segmentPropertyMap, queryResult, this.propertyHistograms, this.bounds.window.value); this.updateHistogramRenderings(); } private updateHistogramRenderings() { this.debouncedRender.cancel(); const {listElement} = this; if (listElement === undefined) return; const {propertyHistograms} = this; if (propertyHistograms.length === 0) { listElement.style.display = 'none'; return; } listElement.style.display = ''; const {properties} = this; for (let i = 0, n = properties.length; i < n; ++i) { this.updateNumericalPropertySummary(i, properties[i], propertyHistograms[i]); } } private makeNumericalPropertySummary( propertyIndex: number, property: InlineSegmentNumericalProperty): NumericalPropertySummary { const plotContainer = document.createElement('div'); plotContainer.classList.add('neuroglancer-segment-query-result-numerical-plot-container'); const plotImg = document.createElement('img'); plotImg.classList.add('neuroglancer-segment-query-result-numerical-plot'); const controller = new CdfController( plotImg, property.dataType, () => this.getBounds(propertyIndex), bounds => this.setBounds(propertyIndex, bounds)); const sortIcon = document.createElement('span'); sortIcon.classList.add('neuroglancer-segment-query-result-numerical-plot-sort'); const columnCheckbox = document.createElement('input'); columnCheckbox.type = 'checkbox'; columnCheckbox.addEventListener('click', () => { toggleIncludeColumn(this.queryResult.value, this.setQuery, property.id); }); const makeBoundElements = (boundType: 'window'|'range'): NumericalBoundElements => { const container = document.createElement('div'); container.classList.add('neuroglancer-segment-query-result-numerical-plot-bounds'); container.classList.add( `neuroglancer-segment-query-result-numerical-plot-bounds-${boundType}`); const makeBoundElement = (endpointIndex: 0|1) => { const e = createBoundInput(boundType, endpointIndex); e.addEventListener('change', () => { const existingBounds = this.bounds[boundType].value[propertyIndex]; if (existingBounds === undefined) return; try { const value = parseDataTypeValue(property.dataType, e.value); this.setBound(boundType, endpointIndex, propertyIndex, value as number); this.bounds[boundType].changed.dispatch(); } catch { } updateInputBoundValue( e, this.bounds[boundType].value[propertyIndex][endpointIndex] as number); }); return e; }; const inputs: [HTMLInputElement, HTMLInputElement] = [makeBoundElement(0), makeBoundElement(1)]; let spacers: [HTMLElement, HTMLElement, HTMLElement]|undefined; if (boundType === 'range') { spacers = [ document.createElement('div'), document.createElement('div'), document.createElement('div'), ]; spacers[1].classList.add( 'neuroglancer-segment-query-result-numerical-plot-bound-constraint-spacer'); spacers[1].appendChild(columnCheckbox); const label = document.createElement('span'); label.classList.add('neuroglancer-segment-query-result-numerical-plot-label'); label.appendChild(document.createTextNode(property.id)); label.appendChild(sortIcon); label.addEventListener('click', () => { toggleSortOrder(this.queryResult.value, this.setQuery, property.id); }); spacers[1].appendChild(label); const {description} = property; if (description) { spacers[1].title = description; } container.appendChild(spacers[0]); container.appendChild(inputs[0]); const lessEqual1 = document.createElement('div'); lessEqual1.textContent = '≤'; lessEqual1.classList.add( 'neuroglancer-segment-query-result-numerical-plot-bound-constraint-symbol'); container.appendChild(lessEqual1); container.appendChild(spacers[1]); const lessEqual2 = document.createElement('div'); lessEqual2.textContent = '≤'; lessEqual2.classList.add( 'neuroglancer-segment-query-result-numerical-plot-bound-constraint-symbol'); container.appendChild(lessEqual2); container.appendChild(inputs[1]); container.appendChild(spacers[2]); } else { container.appendChild(inputs[0]); container.appendChild(inputs[1]); } return {container, spacers, inputs}; }; const boundElements = { range: makeBoundElements('range'), window: makeBoundElements('window'), }; plotContainer.appendChild(boundElements.range.container); plotContainer.appendChild(plotImg); plotContainer.appendChild(boundElements.window.container); return { property, controller, element: plotContainer, plotImg, boundElements, bounds: { window: [NaN, NaN], range: [NaN, NaN], }, propertyHistogram: undefined, columnCheckbox, sortIcon, }; } private updateNumericalPropertySummary( propertyIndex: number, summary: NumericalPropertySummary, propertyHistogram: PropertyHistogram) { const prevWindowBounds = summary.bounds.window; const windowBounds = this.bounds.window.value[propertyIndex]!; const prevConstraintBounds = summary.bounds.range; const constraintBounds = this.bounds.range.value[propertyIndex]!; const {property} = summary; const queryResult = this.queryResult.value; const isIncluded = queryIncludesColumn(queryResult?.query, property.id); summary.columnCheckbox.checked = isIncluded; summary.columnCheckbox.title = isIncluded ? 'Remove column from result table' : 'Add column to result table'; updateColumnSortIcon(queryResult, summary.sortIcon, property.id); // Check if we need to update the image. if (summary.propertyHistogram === propertyHistogram && dataTypeIntervalEqual(property.dataType, prevWindowBounds, windowBounds) && dataTypeIntervalEqual(property.dataType, prevConstraintBounds, constraintBounds)) { return; } const {histogram} = propertyHistogram; const svgNs = 'http://www.w3.org/2000/svg'; const plotElement = document.createElementNS(svgNs, 'svg'); plotElement.setAttribute('width', `1`); plotElement.setAttribute('height', `1`); plotElement.setAttribute('preserveAspectRatio', 'none'); const rect = document.createElementNS(svgNs, 'rect'); const constraintStartX = computeInvlerp(windowBounds, constraintBounds[0]); const constraintEndX = computeInvlerp(windowBounds, constraintBounds[1]); rect.setAttribute('x', `${constraintStartX}`); rect.setAttribute('y', '0'); rect.setAttribute('width', `${constraintEndX - constraintStartX}`); rect.setAttribute('height', '1'); rect.setAttribute('fill', '#4f4f4f'); plotElement.appendChild(rect); const numBins = histogram.length; const makeCdfLine = (startBinIndex: number, endBinIndex: number, endBinIndexForTotal: number) => { const polyLine = document.createElementNS(svgNs, 'polyline'); let points = ''; let totalCount = 0; for (let i = startBinIndex; i < endBinIndexForTotal; ++i) { totalCount += histogram[i]; } if (totalCount === 0) return undefined; const startBinX = computeInvlerp(windowBounds, propertyHistogram.window[0]); const endBinX = computeInvlerp(windowBounds, propertyHistogram.window[1]); const addPoint = (i: number, height: number) => { const fraction = i / (numBins - 2); const x = startBinX * (1 - fraction) + endBinX * fraction; points += ` ${x},${1 - height}`; }; if (startBinIndex !== 0) { addPoint(startBinIndex, 0); } let cumSum = 0; for (let i = startBinIndex; i < endBinIndex; ++i) { const count = histogram[i]; cumSum += count; addPoint(i, cumSum / totalCount); } polyLine.setAttribute('fill', 'none'); polyLine.setAttribute('stroke-width', '1px'); polyLine.setAttribute('points', points); polyLine.setAttribute('vector-effect', 'non-scaling-stroke'); return polyLine; }; { const polyLine = makeCdfLine(0, numBins - 1, numBins); if (polyLine !== undefined) { polyLine.setAttribute('stroke', 'cyan'); plotElement.appendChild(polyLine); } } if (!dataTypeIntervalEqual(property.dataType, property.bounds, constraintBounds)) { // Also plot CDF restricted to data that satisfies the constraint. const constraintStartBin = Math.floor( Math.max(0, Math.min(1, computeInvlerp(propertyHistogram.window, constraintBounds[0]))) * (numBins - 2)); const constraintEndBin = Math.ceil( Math.max(0, Math.min(1, computeInvlerp(propertyHistogram.window, constraintBounds[1]))) * (numBins - 2)); const polyLine = makeCdfLine(constraintStartBin, constraintEndBin, constraintEndBin); if (polyLine !== undefined) { polyLine.setAttribute('stroke', 'white'); plotElement.appendChild(polyLine); } } // Embed the svg as an img rather than embedding it directly, in order to // allow it to be scaled using CSS. const xml = (new XMLSerializer).serializeToString(plotElement); summary.plotImg.src = `data:image/svg+xml;base64,${btoa(xml)}`; summary.propertyHistogram = propertyHistogram; for (let endpointIndex = 0; endpointIndex < 2; ++endpointIndex) { prevWindowBounds[endpointIndex] = windowBounds[endpointIndex]; updateInputBoundValue( summary.boundElements.window.inputs[endpointIndex], windowBounds[endpointIndex] as number); prevConstraintBounds[endpointIndex] = constraintBounds[endpointIndex]; updateInputBoundValue( summary.boundElements.range.inputs[endpointIndex], constraintBounds[endpointIndex] as number); } const spacers = summary.boundElements.range.spacers!; const clampedRange = getClampedInterval(windowBounds, constraintBounds); const effectiveFraction = getIntervalBoundsEffectiveFraction(property.dataType, windowBounds); const leftOffset = computeInvlerp(windowBounds, clampedRange[0]) * effectiveFraction; const rightOffset = computeInvlerp(windowBounds, clampedRange[1]) * effectiveFraction + (1 - effectiveFraction); spacers[0].style.width = `${leftOffset * 100}%`; spacers[2].style.width = `${(1 - rightOffset) * 100}%`; } } function renderTagSummary( queryResult: QueryResult, setQuery: (query: FilterQuery) => void): HTMLElement|undefined { const {tags} = queryResult; if (tags === undefined || tags.length === 0) return undefined; const filterQuery = queryResult.query as FilterQuery; const tagList = document.createElement('div'); tagList.classList.add('neuroglancer-segment-query-result-tag-list'); for (const {tag, count} of tags) { const tagElement = document.createElement('div'); tagElement.classList.add('neuroglancer-segment-query-result-tag'); const tagName = document.createElement('span'); tagName.classList.add('neuroglancer-segment-query-result-tag-name'); tagName.textContent = tag; tagList.appendChild(tagElement); const included = filterQuery.includeTags.includes(tag); const excluded = filterQuery.excludeTags.includes(tag); let toggleTooltip: string; if (included) { toggleTooltip = 'Remove tag from required set'; } else if (excluded) { toggleTooltip = 'Remove tag from excluded set'; } else { toggleTooltip = 'Add tag to required set'; } tagName.addEventListener('click', () => { setQuery(changeTagConstraintInSegmentQuery(filterQuery, tag, true, !included && !excluded)); }); tagName.title = toggleTooltip; const inQuery = included || excluded; const addIncludeExcludeButton = (include: boolean) => { const includeExcludeCount = include ? count : queryResult.count - count; const includeElement = document.createElement('div'); includeElement.classList.add(`neuroglancer-segment-query-result-tag-toggle`); includeElement.classList.add( `neuroglancer-segment-query-result-tag-${include ? 'include' : 'exclude'}`); tagElement.appendChild(includeElement); if (!inQuery && includeExcludeCount === 0) return; const selected = include ? included : excluded; includeElement.appendChild( new CheckboxIcon( { get value() { return selected; }, set value(value: boolean) { setQuery(changeTagConstraintInSegmentQuery(filterQuery, tag, include, value)); }, changed: neverSignal, }, { text: include ? '+' : '-', enableTitle: `Add tag to ${include ? 'required' : 'exclusion'} set`, disableTitle: `Remove tag from ${include ? 'required' : 'exclusion'} set`, backgroundScheme: 'dark', }) .element); }; addIncludeExcludeButton(true); addIncludeExcludeButton(false); tagElement.appendChild(tagName); const numElement = document.createElement('span'); numElement.classList.add('neuroglancer-segment-query-result-tag-count'); if (!inQuery) { numElement.textContent = count.toString(); } tagElement.appendChild(numElement); } return tagList; } export class SegmentDisplayTab extends Tab { constructor(public layer: SegmentationUserLayer) { super(); const {element} = this; element.classList.add('neuroglancer-segment-display-tab'); element.appendChild( this.registerDisposer(new DependentViewWidget( layer.displayState.segmentationGroupState.value.graph, (graph, parent, context) => { if (graph === undefined) return; const toolbox = document.createElement('div'); toolbox.className = 'neuroglancer-segmentation-toolbox'; toolbox.appendChild(makeToolButton(context, layer, { toolJson: ANNOTATE_MERGE_SEGMENTS_TOOL_ID, label: 'Merge', title: 'Merge segments' })); toolbox.appendChild(makeToolButton(context, layer, { toolJson: ANNOTATE_SPLIT_SEGMENTS_TOOL_ID, label: 'Split', title: 'Split segments' })); parent.appendChild(toolbox); })) .element); const queryElement = document.createElement('input'); queryElement.classList.add('neuroglancer-segment-list-query'); queryElement.addEventListener('focus', () => { queryElement.select(); }); const keyboardHandler = this.registerDisposer(new KeyboardEventBinder(queryElement, keyMap)); keyboardHandler.allShortcutsAreGlobal = true; const {segmentQuery} = this.layer.displayState; const debouncedUpdateQueryModel = this.registerCancellable(debounce(() => { segmentQuery.value = queryElement.value; }, 200)); queryElement.autocomplete = 'off'; queryElement.title = keyMap.describe(); queryElement.spellcheck = false; queryElement.placeholder = 'Enter ID, name prefix or /regexp'; this.registerDisposer(observeWatchable(q => { queryElement.value = q; }, segmentQuery)); this.registerDisposer(observeWatchable(t => { if (Date.now() - t < 100) { setTimeout(() => { queryElement.focus(); }, 0); this.layer.segmentQueryFocusTime.value = Number.NEGATIVE_INFINITY; } }, this.layer.segmentQueryFocusTime)); element.appendChild(queryElement); element.appendChild( this .registerDisposer(new DependentViewWidget( // segmentLabelMap is guaranteed to change if segmentationGroupState changes. layer.displayState.segmentPropertyMap, (segmentPropertyMap, parent, context) => { const setQuery = (newQuery: ExplicitIdQuery|FilterQuery) => { queryElement.focus(); queryElement.select(); const value = unparseSegmentQuery(segmentPropertyMap, newQuery); document.execCommand('insertText', false, value); segmentQuery.value = value; queryElement.select(); }; const listSource = context.registerDisposer(new SegmentListSource( segmentQuery, segmentPropertyMap, layer.displayState, parent)); const group = layer.displayState.segmentationGroupState.value; const queryErrors = document.createElement('ul'); queryErrors.classList.add('neuroglancer-segment-query-errors'); parent.appendChild(queryErrors); const queryStatisticsContainer = document.createElement('div'); queryStatisticsContainer.classList.add( 'neuroglancer-segment-query-result-statistics'); const selectionStatusContainer = document.createElement('span'); const selectionClearButton = document.createElement('input'); selectionClearButton.type = 'checkbox'; selectionClearButton.checked = true; selectionClearButton.title = 'Deselect all segment IDs'; selectionClearButton.addEventListener('change', () => { group.visibleSegments.clear(); }); const selectionCopyButton = makeCopyButton({ title: 'Copy visible segment IDs', onClick: () => { const visibleSegments = Array.from(group.visibleSegments, x => x.clone()); visibleSegments.sort(Uint64.compare); setClipboard(visibleSegments.join(', ')); }, }); const selectionStatusMessage = document.createElement('span'); selectionStatusContainer.appendChild(selectionCopyButton); selectionStatusContainer.appendChild(selectionClearButton); selectionStatusContainer.appendChild(selectionStatusMessage); const matchStatusContainer = document.createElement('span'); const matchCheckbox = document.createElement('input'); const matchCopyButton = makeCopyButton({ onClick: () => { debouncedUpdateQueryModel(); debouncedUpdateQueryModel.flush(); listSource.debouncedUpdate.flush(); const queryResult = listSource.queryResult.value; if (queryResult === undefined) return; const segmentStrings = new Array<string>(queryResult.count); forEachQueryResultSegmentId(segmentPropertyMap, queryResult, (id, i) => { segmentStrings[i] = id.toString(); }); setClipboard(segmentStrings.join(', ')); }, }); matchCheckbox.type = 'checkbox'; const toggleMatches = () => { debouncedUpdateQueryModel(); debouncedUpdateQueryModel.flush(); listSource.debouncedUpdate.flush(); const queryResult = listSource.queryResult.value; if (queryResult === undefined) return; const {visibleSegments} = group; const {selectedMatches} = listSource; const shouldSelect = (selectedMatches !== queryResult.count); if (shouldSelect && queryResult.count - selectedMatches > selectSegmentConfirmationThreshold) { if (!hasConfirmed) { hasConfirmed = true; matchStatusMessage.textContent = `Confirm: show ${queryResult.count - selectedMatches} segments?`; return false; } hasConfirmed = false; updateStatus(); } forEachQueryResultSegmentId(segmentPropertyMap, queryResult, id => { visibleSegments.set(id, shouldSelect); }); return true; }; matchCheckbox.addEventListener('click', event => { if (!toggleMatches()) event.preventDefault(); }); const matchStatusMessage = document.createElement('span'); matchStatusContainer.appendChild(matchCopyButton); matchStatusContainer.appendChild(matchCheckbox); matchStatusContainer.appendChild(matchStatusMessage); selectionStatusContainer.classList.add('neuroglancer-segment-list-status'); matchStatusContainer.classList.add('neuroglancer-segment-list-status'); parent.appendChild(queryStatisticsContainer); const queryStatisticsSeparator = document.createElement('div'); queryStatisticsSeparator.classList.add( 'neuroglancer-segment-query-result-statistics-separator'); parent.appendChild(queryStatisticsSeparator); parent.appendChild(matchStatusContainer); parent.appendChild(selectionStatusContainer); let prevNumSelected = -1; const updateStatus = () => { const numSelected = group.visibleSegments.size; if (prevNumSelected !== numSelected) { prevNumSelected = numSelected; selectionStatusMessage.textContent = `${numSelected} visible in total`; selectionClearButton.checked = numSelected > 0; selectionClearButton.style.visibility = numSelected ? 'visible' : 'hidden'; selectionCopyButton.style.visibility = numSelected ? 'visible' : 'hidden'; } matchStatusMessage.textContent = listSource.statusText.value; const {numMatches, selectedMatches} = listSource; matchCopyButton.style.visibility = numMatches ? 'visible' : 'hidden'; matchCopyButton.title = `Copy ${numMatches} segment ID(s)`; matchCheckbox.style.visibility = numMatches ? 'visible' : 'hidden'; if (selectedMatches === 0) { matchCheckbox.checked = false; matchCheckbox.indeterminate = false; matchCheckbox.title = `Show ${numMatches} segment ID(s)`; } else if (selectedMatches === numMatches) { matchCheckbox.checked = true; matchCheckbox.indeterminate = false; matchCheckbox.title = `Hide ${selectedMatches} segment ID(s)`; } else { matchCheckbox.checked = true; matchCheckbox.indeterminate = true; matchCheckbox.title = `Show ${numMatches - selectedMatches} segment ID(s)`; } }; updateStatus(); listSource.statusText.changed.add(updateStatus); context.registerDisposer(group.visibleSegments.changed.add(updateStatus)); let hasConfirmed = false; context.registerEventListener(queryElement, 'input', () => { debouncedUpdateQueryModel(); if (hasConfirmed) { hasConfirmed = false; updateStatus(); } }); context.registerDisposer(registerActionListener(queryElement, 'cancel', () => { queryElement.focus(); queryElement.select(); document.execCommand('delete'); queryElement.blur(); queryElement.value = ''; segmentQuery.value = ''; hasConfirmed = false; updateStatus(); })); context.registerDisposer( registerActionListener(queryElement, 'toggle-listed', toggleMatches)); context.registerDisposer(registerActionListener(queryElement, 'hide-all', () => { group.visibleSegments.clear(); })); context.registerDisposer( registerActionListener(queryElement, 'hide-listed', () => { debouncedUpdateQueryModel(); debouncedUpdateQueryModel.flush(); listSource.debouncedUpdate.flush(); const {visibleSegments} = group; if (segmentQuery.value === '') { visibleSegments.clear(); } else { const queryResult = listSource.queryResult.value; if (queryResult === undefined) return; forEachQueryResultSegmentId(segmentPropertyMap, queryResult, id => { visibleSegments.delete(id); }); } })); const list = context.registerDisposer( new VirtualList({source: listSource, horizontalScroll: true})); const updateListItems = context.registerCancellable(animationFrameDebounce(() => { listSource.updateRenderedItems(list); })); const {displayState} = this.layer; context.registerDisposer( displayState.segmentSelectionState.changed.add(updateListItems)); context.registerDisposer(group.visibleSegments.changed.add(updateListItems)); context.registerDisposer( displayState.segmentColorHash.changed.add(updateListItems)); context.registerDisposer( displayState.segmentStatedColors.changed.add(updateListItems)); context.registerDisposer( displayState.segmentDefaultColor.changed.add(updateListItems)); list.element.classList.add('neuroglancer-segment-list'); context.registerDisposer(layer.bindSegmentListWidth(list.element)); context.registerDisposer( new MouseEventBinder(list.element, getDefaultSelectBindings())); const numericalPropertySummaries = context.registerDisposer(new NumericalPropertiesSummary( segmentPropertyMap, listSource.queryResult, setQuery)); { const {listElement} = numericalPropertySummaries; if (listElement !== undefined) { queryStatisticsContainer.appendChild(listElement); } } let tagSummary: HTMLElement|undefined = undefined; const updateQueryErrors = (queryResult: QueryResult|undefined) => { const errors = queryResult?.errors; removeChildren(queryErrors); if (errors === undefined) return; for (const error of errors) { const errorElement = document.createElement('li'); errorElement.textContent = error.message; queryErrors.appendChild(errorElement); } }; observeWatchable((queryResult: QueryResult|undefined) => { listSource.segmentWidgetFactory = new SegmentWidgetWithExtraColumnsFactory( listSource.segmentationDisplayState, listSource.parentElement, property => queryIncludesColumn(queryResult?.query, property.id)); list.scrollToTop(); removeChildren(list.header); if (segmentPropertyMap !== undefined) { const header = listSource.segmentWidgetFactory.getHeader(); header.container.classList.add('neuroglancer-segment-list-header'); for (const headerLabel of header.propertyLabels) { const {label, sortIcon, id} = headerLabel; label.addEventListener('click', () => { toggleSortOrder(listSource.queryResult.value, setQuery, id); }); updateColumnSortIcon(queryResult, sortIcon, id); } list.header.appendChild(header.container); } updateQueryErrors(queryResult); queryStatisticsSeparator.style.display = 'none'; tagSummary?.remove(); if (queryResult === undefined) return; let {query} = queryResult; if (query.errors !== undefined || query.ids !== undefined) return; tagSummary = renderTagSummary(queryResult, setQuery); if (tagSummary !== undefined) { queryStatisticsContainer.appendChild(tagSummary); } if (numericalPropertySummaries.properties.length > 0 || tagSummary !== undefined) { queryStatisticsSeparator.style.display = ''; } }, listSource.queryResult); parent.appendChild(list.element); })) .element); } }
the_stack
import { expect } from 'chai'; import { of as observableOf } from 'rxjs'; import { deepEqual, instance, mock, when } from 'ts-mockito'; import { Convert } from '../../src/core/format/Convert'; import { MetadataRepository } from '../../src/infrastructure/MetadataRepository'; import { Page } from '../../src/infrastructure/Page'; import { Account } from '../../src/model/account/Account'; import { Metadata } from '../../src/model/metadata/Metadata'; import { MetadataEntry } from '../../src/model/metadata/MetadataEntry'; import { MetadataType } from '../../src/model/metadata/MetadataType'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; import { NetworkType } from '../../src/model/network/NetworkType'; import { AccountMetadataTransaction } from '../../src/model/transaction/AccountMetadataTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { MosaicMetadataTransaction } from '../../src/model/transaction/MosaicMetadataTransaction'; import { NamespaceMetadataTransaction } from '../../src/model/transaction/NamespaceMetadataTransaction'; import { TransactionType } from '../../src/model/transaction/TransactionType'; import { UInt64 } from '../../src/model/UInt64'; import { MetadataTransactionService } from '../../src/service/MetadataTransactionService'; import { TestingAccount } from '../conf/conf.spec'; describe('MetadataTransactionService', () => { let account: Account; let metadataTransactionService: MetadataTransactionService; const key = UInt64.fromHex('85BBEA6CC462B244'); const value = 'TEST'; const deltaValue = 'dalta'; const targetIdHex = '941299B2B7E1291C'; const epochAdjustment = 1573430400; function mockMetadata(type: MetadataType): Metadata { let targetId; if (type === MetadataType.Account) { targetId = undefined; } else if (type === MetadataType.Mosaic) { targetId = new MosaicId(targetIdHex); } else if (type === MetadataType.Namespace) { targetId = NamespaceId.createFromEncoded(targetIdHex); } return new Metadata( '59DFBA84B2E9E7000135E80C', new MetadataEntry( 1, '5E628EA59818D97AA4118780D9A88C5512FCE7A21C195E1574727EFCE5DF7C0D', account.address, account.address, key, MetadataType.Account, value, targetId, ), ); } const mockMetadataRepository: MetadataRepository = mock(); before(() => { account = TestingAccount; when( mockMetadataRepository.search( deepEqual({ targetAddress: account.address, scopedMetadataKey: key.toHex(), sourceAddress: account.address, metadataType: MetadataType.Account, }), ), ).thenReturn(observableOf(new Page<Metadata>([mockMetadata(MetadataType.Account)], 1, 20))); when( mockMetadataRepository.search( deepEqual({ targetId: new MosaicId(targetIdHex), scopedMetadataKey: key.toHex(), sourceAddress: account.address, metadataType: MetadataType.Mosaic, }), ), ).thenReturn(observableOf(new Page<Metadata>([mockMetadata(MetadataType.Mosaic)], 1, 20))); when( mockMetadataRepository.search( deepEqual({ targetId: NamespaceId.createFromEncoded(targetIdHex), scopedMetadataKey: key.toHex(), sourceAddress: account.address, metadataType: MetadataType.Namespace, }), ), ).thenReturn(observableOf(new Page<Metadata>([mockMetadata(MetadataType.Namespace)], 1, 20))); const metadataRepository = instance(mockMetadataRepository); metadataTransactionService = new MetadataTransactionService(metadataRepository); }); it('should create AccountMetadataTransaction', (done) => { metadataTransactionService .createAccountMetadataTransaction( Deadline.create(epochAdjustment), NetworkType.TEST_NET, account.address, key, value + deltaValue, account.address, UInt64.fromUint(2000), ) .subscribe((transaction: AccountMetadataTransaction) => { expect(transaction.type).to.be.equal(TransactionType.ACCOUNT_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); expect(Convert.uint8ToHex(transaction.value)).to.be.equal( Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue)), ); expect(transaction.valueSizeDelta).to.be.equal(deltaValue.length); expect(transaction.targetAddress.equals(account.address)).to.be.true; done(); }); }); it('should create MosaicMetadataTransaction', (done) => { metadataTransactionService .createMosaicMetadataTransaction( Deadline.create(epochAdjustment), NetworkType.TEST_NET, account.address, new MosaicId(targetIdHex), key, value + deltaValue, account.address, UInt64.fromUint(2000), ) .subscribe((transaction: MosaicMetadataTransaction) => { expect(transaction.type).to.be.equal(TransactionType.MOSAIC_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); expect(Convert.uint8ToHex(transaction.value)).to.be.equal( Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue)), ); expect(transaction.targetMosaicId.toHex()).to.be.equal(targetIdHex); expect(transaction.valueSizeDelta).to.be.equal(deltaValue.length); expect(transaction.targetAddress.equals(account.address)).to.be.true; done(); }); }); it('should create NamespaceMetadataTransaction', (done) => { metadataTransactionService .createNamespaceMetadataTransaction( Deadline.create(epochAdjustment), NetworkType.TEST_NET, account.address, NamespaceId.createFromEncoded(targetIdHex), key, value + deltaValue, account.address, UInt64.fromUint(2000), ) .subscribe((transaction: NamespaceMetadataTransaction) => { expect(transaction.type).to.be.equal(TransactionType.NAMESPACE_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); expect(Convert.uint8ToHex(transaction.value)).to.be.equal( Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue)), ); expect(transaction.targetNamespaceId.toHex()).to.be.equal(targetIdHex); expect(transaction.valueSizeDelta).to.be.equal(deltaValue.length); expect(transaction.targetAddress.equals(account.address)).to.be.true; done(); }); }); it('should throw error with invalid address', () => { when( mockMetadataRepository.search( deepEqual({ targetAddress: account.address, scopedMetadataKey: key.toHex(), sourceAddress: account.address, metadataType: MetadataType.Account, }), ), ).thenReject(); expect(() => { metadataTransactionService.createAccountMetadataTransaction( Deadline.create(epochAdjustment), NetworkType.TEST_NET, account.address, key, value + deltaValue, account.address, UInt64.fromUint(2000), ); }).to.throw; }); it('should throw error with invalid mosaicId', () => { when( mockMetadataRepository.search( deepEqual({ targetId: new MosaicId(targetIdHex), scopedMetadataKey: key.toHex(), sourceAddress: account.address, metadataType: MetadataType.Mosaic, }), ), ).thenReject(); expect(() => { metadataTransactionService.createMosaicMetadataTransaction( Deadline.create(epochAdjustment), NetworkType.TEST_NET, account.address, new MosaicId(targetIdHex), key, value + deltaValue, account.address, UInt64.fromUint(2000), ); }).to.throw; }); it('should throw error with invalid NamespaceId', () => { when( mockMetadataRepository.search( deepEqual({ targetId: NamespaceId.createFromEncoded(targetIdHex), scopedMetadataKey: key.toHex(), sourceAddress: account.address, metadataType: MetadataType.Namespace, }), ), ).thenReject(); expect(() => { metadataTransactionService.createNamespaceMetadataTransaction( Deadline.create(epochAdjustment), NetworkType.TEST_NET, account.address, NamespaceId.createFromEncoded(targetIdHex), key, value + deltaValue, account.address, UInt64.fromUint(2000), ); }).to.throw; }); });
the_stack
import React from 'react'; import * as d3Zoom from 'd3-zoom'; import * as d3Selection from 'd3-selection'; import useTheme from '@material-ui/core/styles/useTheme'; import dagre from 'dagre'; import debounce from 'lodash/debounce'; import { BackstageTheme } from '@backstage/theme'; import { DependencyEdge, DependencyNode, Direction, Alignment, Ranker, RenderNodeFunction, RenderLabelFunction, LabelPosition, } from './types'; import { Node } from './Node'; import { Edge, GraphEdge } from './Edge'; import { ARROW_MARKER_ID } from './constants'; /** * Properties of {@link DependencyGraph} * * @remarks * <NodeData> and <EdgeData> are useful when rendering custom or edge labels */ export interface DependencyGraphProps<NodeData, EdgeData> extends React.SVGProps<SVGSVGElement> { /** * Edges of graph */ edges: DependencyEdge<EdgeData>[]; /** * Nodes of Graph */ nodes: DependencyNode<NodeData>[]; /** * Graph {@link DependencyGraphTypes.Direction | direction} * * @remarks * * Default: `DependencyGraphTypes.Direction.TOP_BOTTOM` */ direction?: Direction; /** * Node {@link DependencyGraphTypes.Alignment | alignment} */ align?: Alignment; /** * Margin between nodes on each rank * * @remarks * * Default: 50 */ nodeMargin?: number; /** * Margin between edges * * @remarks * * Default: 10 */ edgeMargin?: number; /** * Margin between each rank * * @remarks * * Default: 50 */ rankMargin?: number; /** * Margin on left and right of whole graph * * @remarks * * Default: 0 */ paddingX?: number; /** * Margin on top and bottom of whole graph * * @remarks * * Default: 0 */ paddingY?: number; /** * Heuristic used to find set of edges that will make graph acyclic */ acyclicer?: 'greedy'; /** * {@link DependencyGraphTypes.Ranker | Algorithm} used to rank nodes * * @remarks * * Default: `DependencyGraphTypes.Ranker.NETWORK_SIMPLEX` */ ranker?: Ranker; /** * {@link DependencyGraphTypes.LabelPosition | Position} of label in relation to edge * * @remarks * * Default: `DependencyGraphTypes.LabelPosition.RIGHT` */ labelPosition?: LabelPosition; /** * How much to move label away from edge * * @remarks * * Applies only when {@link DependencyGraphProps.labelPosition} is `DependencyGraphTypes.LabelPosition.LEFT` or * `DependencyGraphTypes.LabelPosition.RIGHT` */ labelOffset?: number; /** * Minimum number of ranks to keep between connected nodes */ edgeRanks?: number; /** * Weight applied to edges in graph */ edgeWeight?: number; /** * Custom node rendering component */ renderNode?: RenderNodeFunction<NodeData>; /** * Custom label rendering component */ renderLabel?: RenderLabelFunction<EdgeData>; /** * {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs | Defs} shared by rendered SVG to be used by * {@link DependencyGraphProps.renderNode} and/or {@link DependencyGraphProps.renderLabel} */ defs?: SVGDefsElement | SVGDefsElement[]; /** * Controls zoom behavior of graph * * @remarks * * Default: `enabled` */ zoom?: 'enabled' | 'disabled' | 'enable-on-click'; } const WORKSPACE_ID = 'workspace'; /** * Graph component used to visualize relations between entities */ export function DependencyGraph<NodeData, EdgeData>( props: DependencyGraphProps<NodeData, EdgeData>, ) { const { edges, nodes, renderNode, direction = Direction.TOP_BOTTOM, align, nodeMargin = 50, edgeMargin = 10, rankMargin = 50, paddingX = 0, paddingY = 0, acyclicer, ranker = Ranker.NETWORK_SIMPLEX, labelPosition = LabelPosition.RIGHT, labelOffset = 10, edgeRanks = 1, edgeWeight = 1, renderLabel, defs, zoom = 'enabled', ...svgProps } = props; const theme: BackstageTheme = useTheme(); const [containerWidth, setContainerWidth] = React.useState<number>(100); const [containerHeight, setContainerHeight] = React.useState<number>(100); const graph = React.useRef<dagre.graphlib.Graph<DependencyNode<NodeData>>>( new dagre.graphlib.Graph(), ); const [graphWidth, setGraphWidth] = React.useState<number>( graph.current.graph()?.width || 0, ); const [graphHeight, setGraphHeight] = React.useState<number>( graph.current.graph()?.height || 0, ); const [graphNodes, setGraphNodes] = React.useState<string[]>([]); const [graphEdges, setGraphEdges] = React.useState<dagre.Edge[]>([]); const maxWidth = Math.max(graphWidth, containerWidth); const maxHeight = Math.max(graphHeight, containerHeight); const containerRef = React.useMemo( () => debounce((node: SVGSVGElement) => { if (!node) { return; } // Set up zooming + panning const container = d3Selection.select<SVGSVGElement, null>(node); const workspace = d3Selection.select(node.getElementById(WORKSPACE_ID)); function enableZoom() { container.call( d3Zoom .zoom<SVGSVGElement, null>() .scaleExtent([1, 10]) .on('zoom', event => { event.transform.x = Math.min( 0, Math.max( event.transform.x, maxWidth - maxWidth * event.transform.k, ), ); event.transform.y = Math.min( 0, Math.max( event.transform.y, maxHeight - maxHeight * event.transform.k, ), ); workspace.attr('transform', event.transform); }), ); } if (zoom === 'enabled') { enableZoom(); } else if (zoom === 'enable-on-click') { container.on('click', () => enableZoom()); } const { width: newContainerWidth, height: newContainerHeight } = node.getBoundingClientRect(); if (containerWidth !== newContainerWidth) { setContainerWidth(newContainerWidth); } if (containerHeight !== newContainerHeight) { setContainerHeight(newContainerHeight); } }, 100), [containerHeight, containerWidth, maxWidth, maxHeight, zoom], ); const setNodesAndEdges = React.useCallback(() => { // Cleaning up lingering nodes and edges const currentGraphNodes = graph.current.nodes(); const currentGraphEdges = graph.current.edges(); currentGraphNodes.forEach(nodeId => { const remainingNode = nodes.some(node => node.id === nodeId); if (!remainingNode) { graph.current.removeNode(nodeId); } }); currentGraphEdges.forEach(e => { const remainingEdge = edges.some( edge => edge.from === e.v && edge.to === e.w, ); if (!remainingEdge) { graph.current.removeEdge(e.v, e.w); } }); // Adding/updating nodes and edges nodes.forEach(node => { const existingNode = graph.current .nodes() .find(nodeId => node.id === nodeId); if (existingNode && graph.current.node(existingNode)) { const { width, height, x, y } = graph.current.node(existingNode); graph.current.setNode(existingNode, { ...node, width, height, x, y }); } else { graph.current.setNode(node.id, { ...node, width: 0, height: 0 }); } }); edges.forEach(e => { graph.current.setEdge(e.from, e.to, { ...e, label: e.label, width: 0, height: 0, labelpos: labelPosition, labeloffset: labelOffset, weight: edgeWeight, minlen: edgeRanks, }); }); }, [edges, nodes, labelPosition, labelOffset, edgeWeight, edgeRanks]); const updateGraph = React.useMemo( () => debounce( () => { dagre.layout(graph.current); const { height, width } = graph.current.graph(); const newHeight = Math.max(0, height || 0); const newWidth = Math.max(0, width || 0); setGraphWidth(newWidth); setGraphHeight(newHeight); setGraphNodes(graph.current.nodes()); setGraphEdges(graph.current.edges()); }, 250, { leading: true }, ), [], ); React.useEffect(() => { graph.current.setGraph({ rankdir: direction, align, nodesep: nodeMargin, edgesep: edgeMargin, ranksep: rankMargin, marginx: paddingX, marginy: paddingY, acyclicer, ranker, }); setNodesAndEdges(); updateGraph(); return updateGraph.cancel; }, [ acyclicer, align, direction, edgeMargin, paddingX, paddingY, nodeMargin, rankMargin, ranker, setNodesAndEdges, updateGraph, ]); function setNode(id: string, node: DependencyNode<NodeData>) { graph.current.setNode(id, node); updateGraph(); return graph.current; } function setEdge(id: dagre.Edge, edge: DependencyEdge<EdgeData>) { graph.current.setEdge(id, edge); updateGraph(); return graph.current; } return ( <svg ref={containerRef} {...svgProps} width="100%" height={maxHeight} viewBox={`0 0 ${maxWidth} ${maxHeight}`} > <defs> <marker id={ARROW_MARKER_ID} viewBox="0 0 24 24" markerWidth="14" markerHeight="14" refX="16" refY="12" orient="auto" markerUnits="strokeWidth" > <path fill={theme.palette.textSubtle} d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z" /> </marker> {defs} </defs> <g id={WORKSPACE_ID}> <svg width={graphWidth} height={graphHeight} y={maxHeight / 2 - graphHeight / 2} x={maxWidth / 2 - graphWidth / 2} viewBox={`0 0 ${graphWidth} ${graphHeight}`} > {graphEdges.map(e => { const edge = graph.current.edge(e) as GraphEdge<EdgeData>; if (!edge) return null; return ( <Edge key={`${e.v}-${e.w}`} id={e} setEdge={setEdge} render={renderLabel} edge={edge} /> ); })} {graphNodes.map((id: string) => { const node = graph.current.node(id); if (!node) return null; return ( <Node key={id} setNode={setNode} render={renderNode} node={node} /> ); })} </svg> </g> </svg> ); }
the_stack
'use strict'; import 'vs/css!./goToDeclaration'; import * as nls from 'vs/nls'; import { Throttler } from 'vs/base/common/async'; import { onUnexpectedError } from 'vs/base/common/errors'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { MarkedString } from 'vs/base/common/htmlContent'; import { KeyCode, KeyMod, KeyChord } from 'vs/base/common/keyCodes'; import * as platform from 'vs/base/common/platform'; import Severity from 'vs/base/common/severity'; import { TPromise } from 'vs/base/common/winjs.base'; import * as browser from 'vs/base/browser/browser'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { IEditorService } from 'vs/platform/editor/common/editor'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IMessageService } from 'vs/platform/message/common/message'; import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { editorAction, IActionOptions, ServicesAccessor, EditorAction } from 'vs/editor/common/editorCommonExtensions'; import { Location, DefinitionProviderRegistry } from 'vs/editor/common/modes'; import { ICodeEditor, IEditorMouseEvent, IMouseTarget, MouseTargetType } from 'vs/editor/browser/editorBrowser'; import { editorContribution } from 'vs/editor/browser/editorBrowserExtensions'; import { getDefinitionsAtPosition, getImplementationsAtPosition, getTypeDefinitionsAtPosition } from 'vs/editor/contrib/goToDeclaration/common/goToDeclaration'; import { ReferencesController } from 'vs/editor/contrib/referenceSearch/browser/referencesController'; import { ReferencesModel } from 'vs/editor/contrib/referenceSearch/browser/referencesModel'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { PeekContext } from 'vs/editor/contrib/zoneWidget/browser/peekViewWidget'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { ITextModelResolverService } from 'vs/editor/common/services/resolverService'; import { MessageController } from './messageController'; import * as corePosition from 'vs/editor/common/core/position'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { ICursorSelectionChangedEvent } from 'vs/editor/common/controller/cursorEvents'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorActiveLinkForeground } from 'vs/platform/theme/common/colorRegistry'; import { EditorState, CodeEditorStateFlag } from 'vs/editor/common/core/editorState'; export class DefinitionActionConfig { constructor( public openToSide = false, public openInPeek = false, public filterCurrent = true ) { // } } export class DefinitionAction extends EditorAction { private _configuration: DefinitionActionConfig; constructor(configuration: DefinitionActionConfig, opts: IActionOptions) { super(opts); this._configuration = configuration; } public run(accessor: ServicesAccessor, editor: editorCommon.ICommonCodeEditor): TPromise<void> { const messageService = accessor.get(IMessageService); const editorService = accessor.get(IEditorService); let model = editor.getModel(); let pos = editor.getPosition(); return this.getDeclarationsAtPosition(model, pos).then(references => { // * remove falsy references // * remove reference at the current pos let result: Location[] = []; for (let i = 0; i < references.length; i++) { let reference = references[i]; if (!reference || !reference.range) { continue; } let { uri, range } = reference; if (!this._configuration.filterCurrent || uri.toString() !== model.uri.toString() || !Range.containsPosition(range, pos)) { result.push({ uri, range }); } } if (result.length === 0) { const info = model.getWordAtPosition(pos); MessageController.get(editor).showMessage(this.getNoResultFoundMessage(info), pos); return; } return this._onResult(editorService, editor, new ReferencesModel(result)); }, (err) => { // report an error messageService.show(Severity.Error, err); return false; }); } protected getDeclarationsAtPosition(model: editorCommon.IModel, position: corePosition.Position): TPromise<Location[]> { return getDefinitionsAtPosition(model, position); } protected getNoResultFoundMessage(info?: editorCommon.IWordAtPosition): string { return info && info.word ? nls.localize('noResultWord', "No definition found for '{0}'", info.word) : nls.localize('generic.noResults', "No definition found"); } protected getMetaTitle(model: ReferencesModel): string { return model.references.length > 1 && nls.localize('meta.title', " – {0} definitions", model.references.length); } private _onResult(editorService: IEditorService, editor: editorCommon.ICommonCodeEditor, model: ReferencesModel) { const msg = model.getAriaMessage(); alert(msg); if (this._configuration.openInPeek) { this._openInPeek(editorService, editor, model); } else { let next = model.nearestReference(editor.getModel().uri, editor.getPosition()); this._openReference(editorService, next, this._configuration.openToSide).then(editor => { if (editor && model.references.length > 1) { this._openInPeek(editorService, editor, model); } else { model.dispose(); } }); } } private _openReference(editorService: IEditorService, reference: Location, sideBySide: boolean): TPromise<editorCommon.ICommonCodeEditor> { let { uri, range } = reference; return editorService.openEditor({ resource: uri, options: { selection: Range.collapseToStart(range), revealIfVisible: !sideBySide } }, sideBySide).then(editor => { return editor && <editorCommon.IEditor>editor.getControl(); }); } private _openInPeek(editorService: IEditorService, target: editorCommon.ICommonCodeEditor, model: ReferencesModel) { let controller = ReferencesController.get(target); if (controller) { controller.toggleWidget(target.getSelection(), TPromise.as(model), { getMetaTitle: (model) => { return this.getMetaTitle(model); }, onGoto: (reference) => { controller.closeWidget(); return this._openReference(editorService, reference, false); } }); } else { model.dispose(); } } } const goToDeclarationKb = platform.isWeb ? KeyMod.CtrlCmd | KeyCode.F12 : KeyCode.F12; @editorAction export class GoToDefinitionAction extends DefinitionAction { public static ID = 'editor.action.goToDeclaration'; constructor() { super(new DefinitionActionConfig(), { id: GoToDefinitionAction.ID, label: nls.localize('actions.goToDecl.label', "Go to Definition"), alias: 'Go to Definition', precondition: ContextKeyExpr.and( EditorContextKeys.hasDefinitionProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: goToDeclarationKb }, menuOpts: { group: 'navigation', order: 1.1 } }); } } @editorAction export class OpenDefinitionToSideAction extends DefinitionAction { public static ID = 'editor.action.openDeclarationToTheSide'; constructor() { super(new DefinitionActionConfig(true), { id: OpenDefinitionToSideAction.ID, label: nls.localize('actions.goToDeclToSide.label', "Open Definition to the Side"), alias: 'Open Definition to the Side', precondition: ContextKeyExpr.and( EditorContextKeys.hasDefinitionProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, goToDeclarationKb) } }); } } @editorAction export class PeekDefinitionAction extends DefinitionAction { constructor() { super(new DefinitionActionConfig(void 0, true, false), { id: 'editor.action.previewDeclaration', label: nls.localize('actions.previewDecl.label', "Peek Definition"), alias: 'Peek Definition', precondition: ContextKeyExpr.and( EditorContextKeys.hasDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyCode.F12, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.F10 } }, menuOpts: { group: 'navigation', order: 1.2 } }); } } export class ImplementationAction extends DefinitionAction { protected getDeclarationsAtPosition(model: editorCommon.IModel, position: corePosition.Position): TPromise<Location[]> { return getImplementationsAtPosition(model, position); } protected getNoResultFoundMessage(info?: editorCommon.IWordAtPosition): string { return info && info.word ? nls.localize('goToImplementation.noResultWord', "No implementation found for '{0}'", info.word) : nls.localize('goToImplementation.generic.noResults', "No implementation found"); } protected getMetaTitle(model: ReferencesModel): string { return model.references.length > 1 && nls.localize('meta.implementations.title', " – {0} implementations", model.references.length); } } @editorAction export class GoToImplementationAction extends ImplementationAction { public static ID = 'editor.action.goToImplementation'; constructor() { super(new DefinitionActionConfig(), { id: GoToImplementationAction.ID, label: nls.localize('actions.goToImplementation.label', "Go to Implementation"), alias: 'Go to Implementation', precondition: ContextKeyExpr.and( EditorContextKeys.hasImplementationProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyCode.F12 }, menuOpts: { group: 'navigation', order: 1.3 } }); } } @editorAction export class PeekImplementationAction extends ImplementationAction { public static ID = 'editor.action.peekImplementation'; constructor() { super(new DefinitionActionConfig(false, true, false), { id: PeekImplementationAction.ID, label: nls.localize('actions.peekImplementation.label', "Peek Implementation"), alias: 'Peek Implementation', precondition: ContextKeyExpr.and( EditorContextKeys.hasImplementationProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.F12 } }); } } export class TypeDefinitionAction extends DefinitionAction { protected getDeclarationsAtPosition(model: editorCommon.IModel, position: corePosition.Position): TPromise<Location[]> { return getTypeDefinitionsAtPosition(model, position); } protected getNoResultFoundMessage(info?: editorCommon.IWordAtPosition): string { return info && info.word ? nls.localize('goToTypeDefinition.noResultWord', "No type definition found for '{0}'", info.word) : nls.localize('goToTypeDefinition.generic.noResults', "No type definition found"); } protected getMetaTitle(model: ReferencesModel): string { return model.references.length > 1 && nls.localize('meta.typeDefinitions.title', " – {0} type definitions", model.references.length); } } @editorAction export class GoToTypeDefintionAction extends TypeDefinitionAction { public static ID = 'editor.action.goToTypeDefinition'; constructor() { super(new DefinitionActionConfig(), { id: GoToTypeDefintionAction.ID, label: nls.localize('actions.goToTypeDefinition.label', "Go to Type Definition"), alias: 'Go to Type Definition', precondition: ContextKeyExpr.and( EditorContextKeys.hasTypeDefinitionProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: 0 }, menuOpts: { group: 'navigation', order: 1.4 } }); } } @editorAction export class PeekTypeDefinitionAction extends TypeDefinitionAction { public static ID = 'editor.action.peekTypeDefinition'; constructor() { super(new DefinitionActionConfig(false, true, false), { id: PeekTypeDefinitionAction.ID, label: nls.localize('actions.peekTypeDefinition.label', "Peek Type Definition"), alias: 'Peek Type Definition', precondition: ContextKeyExpr.and( EditorContextKeys.hasTypeDefinitionProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()), kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: 0 } }); } } // --- Editor Contribution to goto definition using the mouse and a modifier key @editorContribution class GotoDefinitionWithMouseEditorContribution implements editorCommon.IEditorContribution { private static ID = 'editor.contrib.gotodefinitionwithmouse'; static TRIGGER_MODIFIER = platform.isMacintosh ? 'metaKey' : 'ctrlKey'; static TRIGGER_SIDEBYSIDE_KEY_VALUE = KeyCode.Alt; static TRIGGER_KEY_VALUE = platform.isMacintosh ? KeyCode.Meta : KeyCode.Ctrl; static MAX_SOURCE_PREVIEW_LINES = 8; private editor: ICodeEditor; private toUnhook: IDisposable[]; private decorations: string[]; private currentWordUnderMouse: editorCommon.IWordAtPosition; private throttler: Throttler; private lastMouseMoveEvent: IEditorMouseEvent; private hasTriggerKeyOnMouseDown: boolean; constructor( editor: ICodeEditor, @ITextModelResolverService private textModelResolverService: ITextModelResolverService, @IModeService private modeService: IModeService ) { this.toUnhook = []; this.decorations = []; this.editor = editor; this.throttler = new Throttler(); this.toUnhook.push(this.editor.onMouseDown((e: IEditorMouseEvent) => this.onEditorMouseDown(e))); this.toUnhook.push(this.editor.onMouseUp((e: IEditorMouseEvent) => this.onEditorMouseUp(e))); this.toUnhook.push(this.editor.onMouseMove((e: IEditorMouseEvent) => this.onEditorMouseMove(e))); this.toUnhook.push(this.editor.onMouseDrag(() => this.resetHandler())); this.toUnhook.push(this.editor.onKeyDown((e: IKeyboardEvent) => this.onEditorKeyDown(e))); this.toUnhook.push(this.editor.onKeyUp((e: IKeyboardEvent) => this.onEditorKeyUp(e))); this.toUnhook.push(this.editor.onDidChangeCursorSelection((e) => this.onDidChangeCursorSelection(e))); this.toUnhook.push(this.editor.onDidChangeModel((e) => this.resetHandler())); this.toUnhook.push(this.editor.onDidChangeModelContent(() => this.resetHandler())); this.toUnhook.push(this.editor.onDidScrollChange((e) => { if (e.scrollTopChanged || e.scrollLeftChanged) { this.resetHandler(); } })); } private onDidChangeCursorSelection(e: ICursorSelectionChangedEvent): void { if (e.selection && e.selection.startColumn !== e.selection.endColumn) { this.resetHandler(); // immediately stop this feature if the user starts to select (https://github.com/Microsoft/vscode/issues/7827) } } private onEditorMouseMove(mouseEvent: IEditorMouseEvent, withKey?: IKeyboardEvent): void { this.lastMouseMoveEvent = mouseEvent; this.startFindDefinition(mouseEvent, withKey); } private startFindDefinition(mouseEvent: IEditorMouseEvent, withKey?: IKeyboardEvent): void { if (!this.isEnabled(mouseEvent, withKey)) { this.currentWordUnderMouse = null; this.removeDecorations(); return; } // Find word at mouse position let position = mouseEvent.target.position; let word = position ? this.editor.getModel().getWordAtPosition(position) : null; if (!word) { this.currentWordUnderMouse = null; this.removeDecorations(); return; } // Return early if word at position is still the same if (this.currentWordUnderMouse && this.currentWordUnderMouse.startColumn === word.startColumn && this.currentWordUnderMouse.endColumn === word.endColumn && this.currentWordUnderMouse.word === word.word) { return; } this.currentWordUnderMouse = word; // Find definition and decorate word if found let state = new EditorState(this.editor, CodeEditorStateFlag.Position | CodeEditorStateFlag.Value | CodeEditorStateFlag.Selection | CodeEditorStateFlag.Scroll); this.throttler.queue(() => { return state.validate(this.editor) ? this.findDefinition(mouseEvent.target) : TPromise.as<Location[]>(null); }).then(results => { if (!results || !results.length || !state.validate(this.editor)) { this.removeDecorations(); return; } // Multiple results if (results.length > 1) { this.addDecoration(new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn), nls.localize('multipleResults', "Click to show {0} definitions.", results.length)); } // Single result else { let result = results[0]; if (!result.uri) { return; } this.textModelResolverService.createModelReference(result.uri).then(ref => { if (!ref.object || !ref.object.textEditorModel) { ref.dispose(); return; } const { object: { textEditorModel } } = ref; const { startLineNumber } = result.range; if (textEditorModel.getLineMaxColumn(startLineNumber) === 0) { ref.dispose(); return; } const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber); const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionWithMouseEditorContribution.MAX_SOURCE_PREVIEW_LINES); let endLineNumber = startLineNumber + 1; let minIndent = startIndent; for (; endLineNumber < maxLineNumber; endLineNumber++) { let endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber); minIndent = Math.min(minIndent, endIndent); if (startIndent === endIndent) { break; } } const previewRange = new Range(startLineNumber, 1, endLineNumber + 1, 1); const value = textEditorModel.getValueInRange(previewRange).replace(new RegExp(`^\\s{${minIndent - 1}}`, 'gm'), '').trim(); this.addDecoration(new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn), { language: this.modeService.getModeIdByFilenameOrFirstLine(textEditorModel.uri.fsPath), value }); ref.dispose(); }); } }).done(undefined, onUnexpectedError); } private addDecoration(range: Range, hoverMessage: MarkedString): void { const newDecorations: editorCommon.IModelDeltaDecoration = { range: range, options: { inlineClassName: 'goto-definition-link', hoverMessage } }; this.decorations = this.editor.deltaDecorations(this.decorations, [newDecorations]); } private removeDecorations(): void { if (this.decorations.length > 0) { this.decorations = this.editor.deltaDecorations(this.decorations, []); } } private onEditorKeyDown(e: IKeyboardEvent): void { if ( this.lastMouseMoveEvent && ( e.keyCode === GotoDefinitionWithMouseEditorContribution.TRIGGER_KEY_VALUE || // User just pressed Ctrl/Cmd (normal goto definition) e.keyCode === GotoDefinitionWithMouseEditorContribution.TRIGGER_SIDEBYSIDE_KEY_VALUE && e[GotoDefinitionWithMouseEditorContribution.TRIGGER_MODIFIER] // User pressed Ctrl/Cmd+Alt (goto definition to the side) ) ) { this.startFindDefinition(this.lastMouseMoveEvent, e); } else if (e[GotoDefinitionWithMouseEditorContribution.TRIGGER_MODIFIER]) { this.removeDecorations(); // remove decorations if user holds another key with ctrl/cmd to prevent accident goto declaration } } private resetHandler(): void { this.lastMouseMoveEvent = null; this.hasTriggerKeyOnMouseDown = false; this.removeDecorations(); } private onEditorMouseDown(mouseEvent: IEditorMouseEvent): void { // We need to record if we had the trigger key on mouse down because someone might select something in the editor // holding the mouse down and then while mouse is down start to press Ctrl/Cmd to start a copy operation and then // release the mouse button without wanting to do the navigation. // With this flag we prevent goto definition if the mouse was down before the trigger key was pressed. this.hasTriggerKeyOnMouseDown = !!mouseEvent.event[GotoDefinitionWithMouseEditorContribution.TRIGGER_MODIFIER]; } private onEditorMouseUp(mouseEvent: IEditorMouseEvent): void { if (this.isEnabled(mouseEvent) && this.hasTriggerKeyOnMouseDown) { this.gotoDefinition(mouseEvent.target, mouseEvent.event.altKey).done(() => { this.removeDecorations(); }, (error: Error) => { this.removeDecorations(); onUnexpectedError(error); }); } } private onEditorKeyUp(e: IKeyboardEvent): void { if (e.keyCode === GotoDefinitionWithMouseEditorContribution.TRIGGER_KEY_VALUE) { this.removeDecorations(); this.currentWordUnderMouse = null; } } private isEnabled(mouseEvent: IEditorMouseEvent, withKey?: IKeyboardEvent): boolean { return this.editor.getModel() && (browser.isIE || mouseEvent.event.detail <= 1) && // IE does not support event.detail properly mouseEvent.target.type === MouseTargetType.CONTENT_TEXT && (mouseEvent.event[GotoDefinitionWithMouseEditorContribution.TRIGGER_MODIFIER] || (withKey && withKey.keyCode === GotoDefinitionWithMouseEditorContribution.TRIGGER_KEY_VALUE)) && DefinitionProviderRegistry.has(this.editor.getModel()); } private findDefinition(target: IMouseTarget): TPromise<Location[]> { let model = this.editor.getModel(); if (!model) { return TPromise.as(null); } return getDefinitionsAtPosition(this.editor.getModel(), target.position); } private gotoDefinition(target: IMouseTarget, sideBySide: boolean): TPromise<any> { const targetAction = sideBySide ? OpenDefinitionToSideAction.ID : GoToDefinitionAction.ID; // just run the corresponding action this.editor.setPosition(target.position); return this.editor.getAction(targetAction).run(); } public getId(): string { return GotoDefinitionWithMouseEditorContribution.ID; } public dispose(): void { this.toUnhook = dispose(this.toUnhook); } } registerThemingParticipant((theme, collector) => { let activeLinkForeground = theme.getColor(editorActiveLinkForeground); if (activeLinkForeground) { collector.addRule(`.monaco-editor.${theme.selector} .goto-definition-link { color: ${activeLinkForeground} !important; }`); } });
the_stack
import { assert, expect } from "chai"; import * as semver from "semver"; import { AccessToken, DbResult, GuidString, Id64, Id64String } from "@itwin/core-bentley"; import { Code, ColorDef, GeometryStreamProps, IModel, QueryRowFormat, RequestNewBriefcaseProps, SchemaState, SubCategoryAppearance, } from "@itwin/core-common"; import { Arc3d, IModelJson, Point3d } from "@itwin/core-geometry"; import { DrawingCategory } from "../../Category"; import { BriefcaseDb, BriefcaseManager, DictionaryModel, IModelHost, IModelJsFs, SpatialCategory, SqliteStatement, SqliteValue, SqliteValueType, } from "../../core-backend"; import { ECSqlStatement } from "../../ECSqlStatement"; import { HubMock } from "../HubMock"; import { IModelTestUtils, TestUserType } from "../IModelTestUtils"; import { HubWrappers } from ".."; export async function createNewModelAndCategory(rwIModel: BriefcaseDb, parent?: Id64String) { // Create a new physical model. const [, modelId] = await IModelTestUtils.createAndInsertPhysicalPartitionAndModelAsync(rwIModel, IModelTestUtils.getUniqueModelCode(rwIModel, "newPhysicalModel"), true, parent); // Find or create a SpatialCategory. const dictionary: DictionaryModel = rwIModel.models.getModel<DictionaryModel>(IModel.dictionaryId); const newCategoryCode = IModelTestUtils.getUniqueSpatialCategoryCode(dictionary, "ThisTestSpatialCategory"); const category = SpatialCategory.create(rwIModel, IModel.dictionaryId, newCategoryCode.value); const spatialCategoryId = rwIModel.elements.insertElement(category.toJSON()); category.setDefaultAppearance(new SubCategoryAppearance({ color: 0xff0000 })); // const spatialCategoryId: Id64String = SpatialCategory.insert(rwIModel, IModel.dictionaryId, newCategoryCode.value!, new SubCategoryAppearance({ color: 0xff0000 })); return { modelId, spatialCategoryId }; } describe("IModelWriteTest", () => { let managerAccessToken: AccessToken; let superAccessToken: AccessToken; let testITwinId: string; let readWriteTestIModelId: GuidString; let readWriteTestIModelName: string; before(async () => { // IModelTestUtils.setupDebugLogLevels(); HubMock.startup("IModelWriteTest"); testITwinId = HubMock.iTwinId; readWriteTestIModelName = IModelTestUtils.generateUniqueName("ReadWriteTest"); readWriteTestIModelId = await HubWrappers.recreateIModel({ accessToken: managerAccessToken, iTwinId: testITwinId, iModelName: readWriteTestIModelName }); // Purge briefcases that are close to reaching the acquire limit await HubWrappers.purgeAcquiredBriefcasesById(managerAccessToken, readWriteTestIModelId); }); after(async () => { try { await HubWrappers.deleteIModel(managerAccessToken, "iModelJsIntegrationTest", readWriteTestIModelName); HubMock.shutdown(); } catch (err) { // eslint-disable-next-line no-console console.log(err); } }); it("should handle undo/redo", async () => { const adminAccessToken = await HubWrappers.getAccessToken(TestUserType.SuperManager); // Delete any existing iModels with the same name as the read-write test iModel const iModelName = "CodesUndoRedoPushTest"; const iModelId = await IModelHost.hubAccess.queryIModelByName({ accessToken: adminAccessToken, iTwinId: testITwinId, iModelName }); if (iModelId) await IModelHost.hubAccess.deleteIModel({ accessToken: adminAccessToken, iTwinId: testITwinId, iModelId }); // Create a new empty iModel on the Hub & obtain a briefcase const rwIModelId = await IModelHost.hubAccess.createNewIModel({ accessToken: adminAccessToken, iTwinId: testITwinId, iModelName, description: "TestSubject" }); assert.isNotEmpty(rwIModelId); const rwIModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken: adminAccessToken, iTwinId: testITwinId, iModelId: rwIModelId }); // create and insert a new model with code1 const code1 = IModelTestUtils.getUniqueModelCode(rwIModel, "newPhysicalModel1"); await IModelTestUtils.createAndInsertPhysicalPartitionAndModelAsync(rwIModel, code1, true); assert.isTrue(rwIModel.elements.getElement(code1) !== undefined); // throws if element is not found // create a local txn with that change rwIModel.saveChanges("inserted newPhysicalModel"); // Reverse that local txn rwIModel.txns.reverseSingleTxn(); try { // The model that I just created with code1 should no longer be there. const theNewModel = rwIModel.elements.getElement(code1); // throws if element is not found assert.isTrue(theNewModel === undefined); // really should not be here. assert.fail(); // should not be here. } catch (_err) { // this is what I expect } // Create and insert a model with code2 const code2 = IModelTestUtils.getUniqueModelCode(rwIModel, "newPhysicalModel2"); await IModelTestUtils.createAndInsertPhysicalPartitionAndModelAsync(rwIModel, code2, true); rwIModel.saveChanges("inserted generic objects"); // The iModel should have a model with code1 and not code2 assert.isTrue(rwIModel.elements.getElement(code2) !== undefined); // throws if element is not found // Push the changes to the hub const prePushChangeset = rwIModel.changeset; await rwIModel.pushChanges({ accessToken: adminAccessToken, description: "test" }); const postPushChangeset = rwIModel.changeset; assert(!!postPushChangeset); expect(prePushChangeset !== postPushChangeset); rwIModel.close(); // The iModel should have code1 marked as used and not code2 // timer = new Timer("querying codes"); // const codes = await IModelHubAccess.iModelClient.codes.get(adminRequestContext, rwIModelId); // timer.end(); // assert.isTrue(codes.find((code) => (code.value === "newPhysicalModel2" && code.state === CodeState.Used)) !== undefined); // assert.isFalse(codes.find((code) => (code.value === "newPhysicalModel" && code.state === CodeState.Used)) !== undefined); }); it("Run plain SQL against fixed version connection", async () => { const iModel = await HubWrappers.downloadAndOpenBriefcase({ accessToken: managerAccessToken, iTwinId: testITwinId, iModelId: readWriteTestIModelId }); try { iModel.withPreparedSqliteStatement("CREATE TABLE Test(Id INTEGER PRIMARY KEY, Name TEXT NOT NULL, Code INTEGER)", (stmt: SqliteStatement) => { assert.equal(stmt.step(), DbResult.BE_SQLITE_DONE); }); iModel.withPreparedSqliteStatement("INSERT INTO Test(Name,Code) VALUES(?,?)", (stmt: SqliteStatement) => { stmt.bindValue(1, "Dummy 1"); stmt.bindValue(2, 100); assert.equal(stmt.step(), DbResult.BE_SQLITE_DONE); }); iModel.withPreparedSqliteStatement("INSERT INTO Test(Name,Code) VALUES(?,?)", (stmt: SqliteStatement) => { stmt.bindValues(["Dummy 2", 200]); assert.equal(stmt.step(), DbResult.BE_SQLITE_DONE); }); iModel.withPreparedSqliteStatement("INSERT INTO Test(Name,Code) VALUES(:p1,:p2)", (stmt: SqliteStatement) => { stmt.bindValue(":p1", "Dummy 3"); stmt.bindValue(":p2", 300); assert.equal(stmt.step(), DbResult.BE_SQLITE_DONE); }); iModel.withPreparedSqliteStatement("INSERT INTO Test(Name,Code) VALUES(:p1,:p2)", (stmt: SqliteStatement) => { stmt.bindValues({ ":p1": "Dummy 4", ":p2": 400 }); assert.equal(stmt.step(), DbResult.BE_SQLITE_DONE); }); iModel.saveChanges(); iModel.withPreparedSqliteStatement("SELECT Id,Name,Code FROM Test ORDER BY Id", (stmt: SqliteStatement) => { for (let i: number = 1; i <= 4; i++) { assert.equal(stmt.step(), DbResult.BE_SQLITE_ROW); assert.equal(stmt.getColumnCount(), 3); const val0: SqliteValue = stmt.getValue(0); assert.equal(val0.columnName, "Id"); assert.equal(val0.type, SqliteValueType.Integer); assert.isFalse(val0.isNull); assert.equal(val0.getInteger(), i); const val1: SqliteValue = stmt.getValue(1); assert.equal(val1.columnName, "Name"); assert.equal(val1.type, SqliteValueType.String); assert.isFalse(val1.isNull); assert.equal(val1.getString(), `Dummy ${i}`); const val2: SqliteValue = stmt.getValue(2); assert.equal(val2.columnName, "Code"); assert.equal(val2.type, SqliteValueType.Integer); assert.isFalse(val2.isNull); assert.equal(val2.getInteger(), i * 100); const row: any = stmt.getRow(); assert.equal(row.id, i); assert.equal(row.name, `Dummy ${i}`); assert.equal(row.code, i * 100); } assert.equal(stmt.step(), DbResult.BE_SQLITE_DONE); }); } finally { // delete the briefcase as the test modified it locally. let briefcasePath: string | undefined; if (iModel.isOpen) briefcasePath = iModel.pathName; await HubWrappers.closeAndDeleteBriefcaseDb(managerAccessToken, iModel); if (!!briefcasePath && IModelJsFs.existsSync(briefcasePath)) IModelJsFs.unlinkSync(briefcasePath); } }); it("Run plain SQL against readonly connection", async () => { const iModel = await HubWrappers.downloadAndOpenCheckpoint({ accessToken: managerAccessToken, iTwinId: testITwinId, iModelId: readWriteTestIModelId }); iModel.withPreparedSqliteStatement("SELECT Name,StrData FROM be_Prop WHERE Namespace='ec_Db'", (stmt: SqliteStatement) => { let rowCount = 0; while (stmt.step() === DbResult.BE_SQLITE_ROW) { rowCount++; assert.equal(stmt.getColumnCount(), 2); const nameVal: SqliteValue = stmt.getValue(0); assert.equal(nameVal.columnName, "Name"); assert.equal(nameVal.type, SqliteValueType.String); assert.isFalse(nameVal.isNull); const name: string = nameVal.getString(); const versionVal = stmt.getValue(1); assert.equal(versionVal.columnName, "StrData"); assert.equal(versionVal.type, SqliteValueType.String); assert.isFalse(versionVal.isNull); const profileVersion: any = JSON.parse(versionVal.getString()); assert.isTrue(name === "SchemaVersion" || name === "InitialSchemaVersion"); if (name === "SchemaVersion") { assert.equal(profileVersion.major, 4); assert.equal(profileVersion.minor, 0); assert.equal(profileVersion.sub1, 0); assert.isAtLeast(profileVersion.sub2, 1); } else if (name === "InitialSchemaVersion") { assert.equal(profileVersion.major, 4); assert.equal(profileVersion.minor, 0); assert.equal(profileVersion.sub1, 0); assert.isAtLeast(profileVersion.sub2, 1); } } assert.equal(rowCount, 2); }); iModel.close(); }); it("should be able to upgrade a briefcase with an older schema", async () => { const iTwinId = HubMock.iTwinId; /** * Test validates that - * - User "manager" upgrades the BisCore schema in the briefcase from version 1.0.0 to 1.0.10+ * - User "super" can get the upgrade "manager" made */ /* Setup test - Push an iModel with an old BisCore schema up to the Hub */ const pathname = IModelTestUtils.resolveAssetFile("CompatibilityTestSeed.bim"); const hubName = IModelTestUtils.generateUniqueName("CompatibilityTest"); const iModelId = await HubWrappers.pushIModel(managerAccessToken, iTwinId, pathname, hubName, true); // Download two copies of the briefcase - manager and super const args: RequestNewBriefcaseProps = { iTwinId, iModelId }; const managerBriefcaseProps = await BriefcaseManager.downloadBriefcase({ accessToken: managerAccessToken, ...args }); const superBriefcaseProps = await BriefcaseManager.downloadBriefcase({ accessToken: superAccessToken, ...args }); /* User "manager" upgrades the briefcase */ // Validate the original state of the BisCore schema in the briefcase let iModel = await BriefcaseDb.open({ fileName: managerBriefcaseProps.fileName }); const beforeVersion = iModel.querySchemaVersion("BisCore"); assert.isTrue(semver.satisfies(beforeVersion!, "= 1.0.0")); assert.isFalse(iModel.nativeDb.hasPendingTxns()); iModel.close(); // Validate that the BisCore schema is recognized as a recommended upgrade let schemaState = BriefcaseDb.validateSchemas(managerBriefcaseProps.fileName, true); assert.strictEqual(schemaState, SchemaState.UpgradeRecommended); // Upgrade the schemas await BriefcaseDb.upgradeSchemas(managerBriefcaseProps); // Validate state after upgrade iModel = await BriefcaseDb.open({ fileName: managerBriefcaseProps.fileName }); const afterVersion = iModel.querySchemaVersion("BisCore"); assert.isTrue(semver.satisfies(afterVersion!, ">= 1.0.10")); assert.isFalse(iModel.nativeDb.hasPendingTxns()); assert.isFalse(iModel.holdsSchemaLock); assert.isFalse(iModel.nativeDb.hasUnsavedChanges()); iModel.close(); /* User "super" can get the upgrade "manager" made */ // Validate that the BisCore schema is recognized as a recommended upgrade schemaState = BriefcaseDb.validateSchemas(superBriefcaseProps.fileName, true); assert.strictEqual(schemaState, SchemaState.UpgradeRecommended); // SKIPPED FOR NOW - locking not mocked yet // Upgrade the schemas - should fail, since user hasn't pulled changes done by manager // // let result: IModelHubStatus = IModelHubStatus.Success; // try { // await BriefcaseDb.upgradeSchemas(superRequestContext, superBriefcaseProps); // } catch (err) { // // result = err.errorNumber; // } // assert.strictEqual(result, IModelHubStatus.PullIsRequired); // Open briefcase and pull change sets to upgrade const superIModel = await BriefcaseDb.open({ fileName: superBriefcaseProps.fileName }); (superBriefcaseProps.changeset as any) = await superIModel.pullChanges({ accessToken: superAccessToken }); const superVersion = superIModel.querySchemaVersion("BisCore"); assert.isTrue(semver.satisfies(superVersion!, ">= 1.0.10")); assert.isFalse(superIModel.nativeDb.hasUnsavedChanges()); // Validate no changes were made assert.isFalse(superIModel.nativeDb.hasPendingTxns()); // Validate no changes were made superIModel.close(); // Validate that there are no upgrades required schemaState = BriefcaseDb.validateSchemas(superBriefcaseProps.fileName, true); assert.strictEqual(schemaState, SchemaState.UpToDate); // Upgrade the schemas - ensure this is a no-op await BriefcaseDb.upgradeSchemas(superBriefcaseProps); await IModelHost.hubAccess.deleteIModel({ accessToken: managerAccessToken, iTwinId, iModelId }); }); it("changeset size and ec schema version change", async () => { const adminToken = "super manager token"; const iTwinId = HubMock.iTwinId; const iModelName = IModelTestUtils.generateUniqueName("changeset_size"); const rwIModelId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName, description: "TestSubject", accessToken: adminToken }); assert.isNotEmpty(rwIModelId); const rwIModel = await HubWrappers.downloadAndOpenBriefcase({ iTwinId, iModelId: rwIModelId, accessToken: adminToken }); assert.equal(rwIModel.nativeDb.enableChangesetSizeStats(true), DbResult.BE_SQLITE_OK); const schema = `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestDomain" alias="ts" version="01.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.1"> <ECSchemaReference name="BisCore" version="01.00" alias="bis"/> <ECEntityClass typeName="Test2dElement"> <BaseClass>bis:GraphicalElement2d</BaseClass> <ECProperty propertyName="s" typeName="string"/> </ECEntityClass> </ECSchema>`; await rwIModel.importSchemaStrings([schema]); rwIModel.saveChanges("user 1: schema changeset"); if ("push changes") { // Push the changes to the hub const prePushChangeSetId = rwIModel.changeset.id; await rwIModel.pushChanges({ description: "push schema changeset", accessToken: adminToken }); const postPushChangeSetId = rwIModel.changeset.id; assert(!!postPushChangeSetId); expect(prePushChangeSetId !== postPushChangeSetId); const changesets = await IModelHost.hubAccess.queryChangesets({ iModelId: rwIModelId, accessToken: superAccessToken }); assert.equal(changesets.length, 1); } await rwIModel.locks.acquireLocks({ shared: IModel.dictionaryId }); const codeProps = Code.createEmpty(); codeProps.value = "DrawingModel"; let totalEl = 0; const [, drawingModelId] = IModelTestUtils.createAndInsertDrawingPartitionAndModel(rwIModel, codeProps, true); let drawingCategoryId = DrawingCategory.queryCategoryIdByName(rwIModel, IModel.dictionaryId, "MyDrawingCategory"); if (undefined === drawingCategoryId) drawingCategoryId = DrawingCategory.insert(rwIModel, IModel.dictionaryId, "MyDrawingCategory", new SubCategoryAppearance({ color: ColorDef.fromString("rgb(255,0,0)").toJSON() })); const insertElements = (imodel: BriefcaseDb, className: string = "Test2dElement", noOfElements: number = 10, userProp: (n: number) => object) => { for (let m = 0; m < noOfElements; ++m) { const geomArray: Arc3d[] = [ Arc3d.createXY(Point3d.create(0, 0), 5), Arc3d.createXY(Point3d.create(5, 5), 2), Arc3d.createXY(Point3d.create(-5, -5), 20), ]; const geometryStream: GeometryStreamProps = []; for (const geom of geomArray) { const arcData = IModelJson.Writer.toIModelJson(geom); geometryStream.push(arcData); } const prop = userProp(++totalEl); // Create props const geomElement = { classFullName: `TestDomain:${className}`, model: drawingModelId, category: drawingCategoryId, code: Code.createEmpty(), geom: geometryStream, ...prop, }; const id = imodel.elements.insertElement(geomElement); assert.isTrue(Id64.isValidId64(id), "insert worked"); } }; const str = new Array(1024).join("x"); insertElements(rwIModel, "Test2dElement", 1024, () => { return { s: str }; }); assert.equal(1357661, rwIModel.nativeDb.getChangesetSize()); rwIModel.saveChanges("user 1: data"); assert.equal(0, rwIModel.nativeDb.getChangesetSize()); await rwIModel.pushChanges({ description: "schema changeset", accessToken: adminToken }); rwIModel.close(); }); it("clear cache on schema changes", async () => { const adminToken = await HubWrappers.getAccessToken(TestUserType.SuperManager); const userToken = await HubWrappers.getAccessToken(TestUserType.Super); const iTwinId = HubMock.iTwinId; // Delete any existing iModels with the same name as the OptimisticConcurrencyTest iModel const iModelName = IModelTestUtils.generateUniqueName("SchemaChanges"); // Create a new empty iModel on the Hub & obtain a briefcase const rwIModelId = await IModelHost.hubAccess.createNewIModel({ iTwinId, iModelName, description: "TestSubject" }); assert.isNotEmpty(rwIModelId); const rwIModel = await HubWrappers.downloadAndOpenBriefcase({ iTwinId, iModelId: rwIModelId, accessToken: adminToken }); const rwIModel2 = await HubWrappers.downloadAndOpenBriefcase({ iTwinId, iModelId: rwIModelId, accessToken: userToken }); // enable change tracking assert.equal(rwIModel.nativeDb.enableChangesetSizeStats(true), DbResult.BE_SQLITE_OK); assert.equal(rwIModel2.nativeDb.enableChangesetSizeStats(true), DbResult.BE_SQLITE_OK); const schema = `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestDomain" alias="ts" version="01.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.1"> <ECSchemaReference name="BisCore" version="01.00" alias="bis"/> <ECEntityClass typeName="Test2dElement"> <BaseClass>bis:GraphicalElement2d</BaseClass> <ECProperty propertyName="s" typeName="string"/> </ECEntityClass> </ECSchema>`; await rwIModel.importSchemaStrings([schema]); rwIModel.saveChanges("user 1: schema changeset"); if ("push changes") { // Push the changes to the hub const prePushChangeSetId = rwIModel.changeset.id; await rwIModel.pushChanges({ description: "schema changeset", accessToken: adminToken }); const postPushChangeSetId = rwIModel.changeset.id; assert(!!postPushChangeSetId); expect(prePushChangeSetId !== postPushChangeSetId); const changesets = await IModelHost.hubAccess.queryChangesets({ iModelId: rwIModelId, accessToken: superAccessToken }); assert.equal(changesets.length, 1); } const codeProps = Code.createEmpty(); codeProps.value = "DrawingModel"; let totalEl = 0; await rwIModel.locks.acquireLocks({ shared: IModel.dictionaryId }); const [, drawingModelId] = IModelTestUtils.createAndInsertDrawingPartitionAndModel(rwIModel, codeProps, true); let drawingCategoryId = DrawingCategory.queryCategoryIdByName(rwIModel, IModel.dictionaryId, "MyDrawingCategory"); if (undefined === drawingCategoryId) drawingCategoryId = DrawingCategory.insert(rwIModel, IModel.dictionaryId, "MyDrawingCategory", new SubCategoryAppearance({ color: ColorDef.fromString("rgb(255,0,0)").toJSON() })); const insertElements = (imodel: BriefcaseDb, className: string = "Test2dElement", noOfElements: number = 10, userProp: (n: number) => object) => { for (let m = 0; m < noOfElements; ++m) { const geomArray: Arc3d[] = [ Arc3d.createXY(Point3d.create(0, 0), 5), Arc3d.createXY(Point3d.create(5, 5), 2), Arc3d.createXY(Point3d.create(-5, -5), 20), ]; const geometryStream: GeometryStreamProps = []; for (const geom of geomArray) { const arcData = IModelJson.Writer.toIModelJson(geom); geometryStream.push(arcData); } const prop = userProp(++totalEl); // Create props const geomElement = { classFullName: `TestDomain:${className}`, model: drawingModelId, category: drawingCategoryId, code: Code.createEmpty(), geom: geometryStream, ...prop, }; const id = imodel.elements.insertElement(geomElement); assert.isTrue(Id64.isValidId64(id), "insert worked"); } }; insertElements(rwIModel, "Test2dElement", 10, (n: number) => { return { s: `s-${n}` }; }); assert.equal(3902, rwIModel.nativeDb.getChangesetSize()); rwIModel.saveChanges("user 1: data changeset"); if ("push changes") { // Push the changes to the hub const prePushChangeSetId = rwIModel.changeset.id; await rwIModel.pushChanges({ description: "10 instances of test2dElement", accessToken: adminToken }); const postPushChangeSetId = rwIModel.changeset.id; assert(!!postPushChangeSetId); expect(prePushChangeSetId !== postPushChangeSetId); const changesets = await IModelHost.hubAccess.queryChangesets({ iModelId: rwIModelId, accessToken: superAccessToken }); assert.equal(changesets.length, 2); } let rows: any[] = []; rwIModel.withPreparedStatement("SELECT * FROM TestDomain.Test2dElement", (stmt: ECSqlStatement) => { while (stmt.step() === DbResult.BE_SQLITE_ROW) { rows.push(stmt.getRow()); } }); assert.equal(rows.length, 10); assert.equal(rows.map((r) => r.s).filter((v) => v).length, 10); rows = []; for await (const row of rwIModel.query("SELECT * FROM TestDomain.Test2dElement", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { rows.push(row); } assert.equal(rows.length, 10); assert.equal(rows.map((r) => r.s).filter((v) => v).length, 10); // ==================================================================================================== if ("user pull/merge") { // pull and merge changes await rwIModel2.pullChanges({ accessToken: userToken }); rows = []; rwIModel2.withPreparedStatement("SELECT * FROM TestDomain.Test2dElement", (stmt: ECSqlStatement) => { while (stmt.step() === DbResult.BE_SQLITE_ROW) { rows.push(stmt.getRow()); } }); assert.equal(rows.length, 10); assert.equal(rows.map((r) => r.s).filter((v) => v).length, 10); rows = []; for await (const row of rwIModel2.query("SELECT * FROM TestDomain.Test2dElement", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { rows.push(row); } assert.equal(rows.length, 10); assert.equal(rows.map((r) => r.s).filter((v) => v).length, 10); // create some element and push those changes await rwIModel2.locks.acquireLocks({ shared: drawingModelId }); insertElements(rwIModel2, "Test2dElement", 10, (n: number) => { return { s: `s-${n}` }; }); assert.equal(13, rwIModel.nativeDb.getChangesetSize()); rwIModel2.saveChanges("user 2: data changeset"); if ("push changes") { // Push the changes to the hub const prePushChangeSetId = rwIModel2.changeset.id; await rwIModel2.pushChanges({ accessToken: userToken, description: "10 instances of test2dElement" }); const postPushChangeSetId = rwIModel2.changeset.id; assert(!!postPushChangeSetId); expect(prePushChangeSetId !== postPushChangeSetId); const changesets = await IModelHost.hubAccess.queryChangesets({ iModelId: rwIModelId, accessToken: userToken }); assert.equal(changesets.length, 3); } } await rwIModel.pullChanges({ accessToken: adminToken }); // second schema import ============================================================== const schemaV2 = `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestDomain" alias="ts" version="01.01" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.1"> <ECSchemaReference name="BisCore" version="01.00" alias="bis"/> <ECEntityClass typeName="Test2dElement"> <BaseClass>bis:GraphicalElement2d</BaseClass> <ECProperty propertyName="s" typeName="string"/> <ECProperty propertyName="v" typeName="string"/> </ECEntityClass> <ECEntityClass typeName="Test2dElement2nd"> <BaseClass>bis:GraphicalElement2d</BaseClass> <ECProperty propertyName="t" typeName="string"/> <ECProperty propertyName="r" typeName="string"/> </ECEntityClass> </ECSchema>`; await rwIModel.importSchemaStrings([schemaV2]); assert.equal(0, rwIModel.nativeDb.getChangesetSize()); rwIModel.saveChanges("user 1: schema changeset2"); if ("push changes") { // Push the changes to the hub const prePushChangeSetId = rwIModel.changeset.id; await rwIModel.pushChanges({ accessToken: adminToken, description: "schema changeset" }); const postPushChangeSetId = rwIModel.changeset.id; assert(!!postPushChangeSetId); expect(prePushChangeSetId !== postPushChangeSetId); const changesets = await IModelHost.hubAccess.queryChangesets({ iModelId: rwIModelId, accessToken: superAccessToken }); assert.equal(changesets.length, 4); } // create some element and push those changes await rwIModel.locks.acquireLocks({ shared: drawingModelId }); insertElements(rwIModel, "Test2dElement", 10, (n: number) => { return { s: `s-${n}`, v: `v-${n}`, }; }); // create some element and push those changes insertElements(rwIModel, "Test2dElement2nd", 10, (n: number) => { return { t: `t-${n}`, r: `r-${n}`, }; }); assert.equal(6279, rwIModel.nativeDb.getChangesetSize()); rwIModel.saveChanges("user 1: data changeset"); if ("push changes") { // Push the changes to the hub const prePushChangeSetId = rwIModel.changeset.id; await rwIModel.pushChanges({ accessToken: adminToken, description: "10 instances of test2dElement" }); const postPushChangeSetId = rwIModel.changeset.id; assert(!!postPushChangeSetId); expect(prePushChangeSetId !== postPushChangeSetId); const changesets = await IModelHost.hubAccess.queryChangesets({ iModelId: rwIModelId, accessToken: superAccessToken }); assert.equal(changesets.length, 5); } rows = []; rwIModel.withPreparedStatement("SELECT * FROM TestDomain.Test2dElement", (stmt: ECSqlStatement) => { while (stmt.step() === DbResult.BE_SQLITE_ROW) { rows.push(stmt.getRow()); } }); assert.equal(rows.length, 30); assert.equal(rows.map((r) => r.s).filter((v) => v).length, 30); assert.equal(rows.map((r) => r.v).filter((v) => v).length, 10); rows = []; for await (const row of rwIModel.query("SELECT * FROM TestDomain.Test2dElement", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { rows.push(row); } assert.equal(rows.length, 30); assert.equal(rows.map((r) => r.s).filter((v) => v).length, 30); assert.equal(rows.map((r) => r.v).filter((v) => v).length, 10); rows = []; rwIModel.withPreparedStatement("SELECT * FROM TestDomain.Test2dElement2nd", (stmt: ECSqlStatement) => { while (stmt.step() === DbResult.BE_SQLITE_ROW) { rows.push(stmt.getRow()); } }); assert.equal(rows.length, 10); assert.equal(rows.map((r) => r.t).filter((v) => v).length, 10); assert.equal(rows.map((r) => r.r).filter((v) => v).length, 10); rows = []; for await (const row of rwIModel.query("SELECT * FROM TestDomain.Test2dElement2nd", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { rows.push(row); } assert.equal(rows.length, 10); assert.equal(rows.map((r) => r.t).filter((v) => v).length, 10); assert.equal(rows.map((r) => r.r).filter((v) => v).length, 10); // ==================================================================================================== if ("user pull/merge") { // pull and merge changes await rwIModel2.pullChanges({ accessToken: userToken }); rows = []; // Following fail without the fix in briefcase manager where we clear statement cache on schema changeset apply rwIModel2.withPreparedStatement("SELECT * FROM TestDomain.Test2dElement", (stmt: ECSqlStatement) => { while (stmt.step() === DbResult.BE_SQLITE_ROW) { rows.push(stmt.getRow()); } }); assert.equal(rows.length, 30); assert.equal(rows.map((r) => r.s).filter((v) => v).length, 30); assert.equal(rows.map((r) => r.v).filter((v) => v).length, 10); rows = []; // Following fail without native side fix where we clear concurrent query cache on schema changeset apply for await (const row of rwIModel2.query("SELECT * FROM TestDomain.Test2dElement", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { rows.push(row); } assert.equal(rows.length, 30); assert.equal(rows.map((r) => r.s).filter((v) => v).length, 30); assert.equal(rows.map((r) => r.v).filter((v) => v).length, 10); for (const row of rows) { const el: any = rwIModel2.elements.getElementProps(row.id); assert.isDefined(el); if (row.s) { assert.equal(row.s, el.s); } else { assert.isUndefined(el.s); } if (row.v) { assert.equal(row.v, el.v); } else { assert.isUndefined(el.v); } } rows = []; rwIModel2.withPreparedStatement("SELECT * FROM TestDomain.Test2dElement2nd", (stmt: ECSqlStatement) => { while (stmt.step() === DbResult.BE_SQLITE_ROW) { rows.push(stmt.getRow()); } }); assert.equal(rows.length, 10); assert.equal(rows.map((r) => r.t).filter((v) => v).length, 10); assert.equal(rows.map((r) => r.r).filter((v) => v).length, 10); for (const row of rows) { const el: any = rwIModel2.elements.getElementProps(row.id); assert.isDefined(el); if (row.s) { assert.equal(row.s, el.s); } else { assert.isUndefined(el.s); } if (row.v) { assert.equal(row.v, el.v); } else { assert.isUndefined(el.v); } } rows = []; for await (const row of rwIModel2.query("SELECT * FROM TestDomain.Test2dElement2nd", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { rows.push(row); } assert.equal(rows.length, 10); assert.equal(rows.map((r) => r.t).filter((v) => v).length, 10); assert.equal(rows.map((r) => r.r).filter((v) => v).length, 10); for (const row of rows) { const el: any = rwIModel2.elements.getElementProps(row.id); assert.isDefined(el); if (row.t) { assert.equal(row.t, el.t); } else { assert.isUndefined(el.t); } if (row.r) { assert.equal(row.r, el.r); } else { assert.isUndefined(el.r); } } } rwIModel.close(); rwIModel2.close(); }); });
the_stack
import { encodeBech32Pubkey } from "@cosmjs/amino"; import { fromBase64 } from "@cosmjs/encoding"; import { coin, coins } from "@cosmjs/proto-signing"; import { MsgMultiSend, MsgSend } from "cosmjs-types/cosmos/bank/v1beta1/tx"; import { MsgFundCommunityPool, MsgSetWithdrawAddress, MsgWithdrawDelegatorReward, MsgWithdrawValidatorCommission, } from "cosmjs-types/cosmos/distribution/v1beta1/tx"; import { TextProposal, VoteOption } from "cosmjs-types/cosmos/gov/v1beta1/gov"; import { MsgDeposit, MsgSubmitProposal, MsgVote } from "cosmjs-types/cosmos/gov/v1beta1/tx"; import { MsgBeginRedelegate, MsgCreateValidator, MsgDelegate, MsgEditValidator, MsgUndelegate, } from "cosmjs-types/cosmos/staking/v1beta1/tx"; import { MsgTransfer } from "cosmjs-types/ibc/applications/transfer/v1/tx"; import Long from "long"; import { AminoMsgBeginRedelegate, AminoMsgCreateValidator, AminoMsgDelegate, AminoMsgDeposit, AminoMsgEditValidator, AminoMsgFundCommunityPool, AminoMsgMultiSend, AminoMsgSend, AminoMsgSetWithdrawAddress, AminoMsgSubmitProposal, AminoMsgTransfer, AminoMsgUndelegate, AminoMsgVote, AminoMsgWithdrawDelegatorReward, AminoMsgWithdrawValidatorCommission, } from "./aminomsgs"; import { AminoTypes } from "./aminotypes"; describe("AminoTypes", () => { describe("toAmino", () => { // bank it("works for MsgSend", () => { const msg: MsgSend = { fromAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", toAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coins(1234, "ucosm"), }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.bank.v1beta1.MsgSend", value: msg, }); const expected: AminoMsgSend = { type: "cosmos-sdk/MsgSend", value: { from_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", to_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coins(1234, "ucosm"), }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgMultiSend", () => { const msg: MsgMultiSend = { inputs: [ { address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", coins: coins(1234, "ucosm") }, { address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", coins: coins(5678, "ucosm") }, ], outputs: [ { address: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", coins: coins(6000, "ucosm") }, { address: "cosmos142u9fgcjdlycfcez3lw8x6x5h7rfjlnfhpw2lx", coins: coins(912, "ucosm") }, ], }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.bank.v1beta1.MsgMultiSend", value: msg, }); const expected: AminoMsgMultiSend = { type: "cosmos-sdk/MsgMultiSend", value: { inputs: [ { address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", coins: coins(1234, "ucosm") }, { address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", coins: coins(5678, "ucosm") }, ], outputs: [ { address: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", coins: coins(6000, "ucosm") }, { address: "cosmos142u9fgcjdlycfcez3lw8x6x5h7rfjlnfhpw2lx", coins: coins(912, "ucosm") }, ], }, }; expect(aminoMsg).toEqual(expected); }); // gov it("works for MsgDeposit", () => { const msg: MsgDeposit = { amount: [{ amount: "12300000", denom: "ustake" }], depositor: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", proposalId: Long.fromNumber(5), }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.gov.v1beta1.MsgDeposit", value: msg, }); const expected: AminoMsgDeposit = { type: "cosmos-sdk/MsgDeposit", value: { amount: [{ amount: "12300000", denom: "ustake" }], depositor: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", proposal_id: "5", }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgSubmitProposal", () => { const msg: MsgSubmitProposal = { initialDeposit: [{ amount: "12300000", denom: "ustake" }], proposer: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", content: { typeUrl: "/cosmos.gov.v1beta1.TextProposal", value: TextProposal.encode({ description: "This proposal proposes to test whether this proposal passes", title: "Test Proposal", }).finish(), }, }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.gov.v1beta1.MsgSubmitProposal", value: msg, }); const expected: AminoMsgSubmitProposal = { type: "cosmos-sdk/MsgSubmitProposal", value: { initial_deposit: [{ amount: "12300000", denom: "ustake" }], proposer: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", content: { type: "cosmos-sdk/TextProposal", value: { description: "This proposal proposes to test whether this proposal passes", title: "Test Proposal", }, }, }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgVote", () => { const msg: MsgVote = { option: VoteOption.VOTE_OPTION_NO_WITH_VETO, proposalId: Long.fromNumber(5), voter: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.gov.v1beta1.MsgVote", value: msg, }); const expected: AminoMsgVote = { type: "cosmos-sdk/MsgVote", value: { option: 4, proposal_id: "5", voter: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", }, }; expect(aminoMsg).toEqual(expected); }); // distribution it("works for MsgFundCommunityPool", async () => { const msg: MsgFundCommunityPool = { amount: coins(1234, "ucosm"), depositor: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.distribution.v1beta1.MsgFundCommunityPool", value: msg, }); const expected: AminoMsgFundCommunityPool = { type: "cosmos-sdk/MsgFundCommunityPool", value: { amount: coins(1234, "ucosm"), depositor: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgSetWithdrawAddress", async () => { const msg: MsgSetWithdrawAddress = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", withdrawAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.distribution.v1beta1.MsgSetWithdrawAddress", value: msg, }); const expected: AminoMsgSetWithdrawAddress = { type: "cosmos-sdk/MsgModifyWithdrawAddress", value: { delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", withdraw_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgWithdrawDelegatorReward", async () => { const msg: MsgWithdrawDelegatorReward = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward", value: msg, }); const expected: AminoMsgWithdrawDelegatorReward = { type: "cosmos-sdk/MsgWithdrawDelegationReward", value: { delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgWithdrawValidatorCommission", async () => { const msg: MsgWithdrawValidatorCommission = { validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission", value: msg, }); const expected: AminoMsgWithdrawValidatorCommission = { type: "cosmos-sdk/MsgWithdrawValidatorCommission", value: { validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }, }; expect(aminoMsg).toEqual(expected); }); // staking it("works for MsgBeginRedelegate", () => { const msg: MsgBeginRedelegate = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorSrcAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", validatorDstAddress: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", amount: coin(1234, "ucosm"), }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.staking.v1beta1.MsgBeginRedelegate", value: msg, }); const expected: AminoMsgBeginRedelegate = { type: "cosmos-sdk/MsgBeginRedelegate", value: { delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_src_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", validator_dst_address: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", amount: coin(1234, "ucosm"), }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgCreateValidator", () => { const msg: MsgCreateValidator = { description: { moniker: "validator", identity: "me", website: "valid.com", securityContact: "Hamburglar", details: "...", }, commission: { rate: "0.2", maxRate: "0.3", maxChangeRate: "0.1", }, minSelfDelegation: "123", delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", pubkey: { typeUrl: "/cosmos.crypto.secp256k1.PubKey", value: fromBase64("A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ"), }, value: coin(1234, "ucosm"), }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.staking.v1beta1.MsgCreateValidator", value: msg, }); const expected: AminoMsgCreateValidator = { type: "cosmos-sdk/MsgCreateValidator", value: { description: { moniker: "validator", identity: "me", website: "valid.com", security_contact: "Hamburglar", details: "...", }, commission: { rate: "0.2", max_rate: "0.3", max_change_rate: "0.1", }, min_self_delegation: "123", delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", pubkey: encodeBech32Pubkey( { type: "tendermint/PubKeySecp256k1", value: "A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ" }, "cosmos", ), value: coin(1234, "ucosm"), }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgDelegate", () => { const msg: MsgDelegate = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.staking.v1beta1.MsgDelegate", value: msg, }); const expected: AminoMsgDelegate = { type: "cosmos-sdk/MsgDelegate", value: { delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgEditValidator", () => { const msg: MsgEditValidator = { description: { moniker: "validator", identity: "me", website: "valid.com", securityContact: "Hamburglar", details: "...", }, commissionRate: "0.2", minSelfDelegation: "123", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.staking.v1beta1.MsgEditValidator", value: msg, }); const expected: AminoMsgEditValidator = { type: "cosmos-sdk/MsgEditValidator", value: { description: { moniker: "validator", identity: "me", website: "valid.com", security_contact: "Hamburglar", details: "...", }, commission_rate: "0.2", min_self_delegation: "123", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgUndelegate", () => { const msg: MsgUndelegate = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/cosmos.staking.v1beta1.MsgUndelegate", value: msg, }); const expected: AminoMsgUndelegate = { type: "cosmos-sdk/MsgUndelegate", value: { delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }, }; expect(aminoMsg).toEqual(expected); }); // ibc it("works for MsgTransfer", () => { const msg: MsgTransfer = { sourcePort: "testport", sourceChannel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeoutHeight: { revisionHeight: Long.fromString("123", true), revisionNumber: Long.fromString("456", true), }, timeoutTimestamp: Long.fromString("789", true), }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/ibc.applications.transfer.v1.MsgTransfer", value: msg, }); const expected: AminoMsgTransfer = { type: "cosmos-sdk/MsgTransfer", value: { source_port: "testport", source_channel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeout_height: { revision_height: "123", revision_number: "456", }, timeout_timestamp: "789", }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgTransfer with empty values", () => { const msg: MsgTransfer = { sourcePort: "testport", sourceChannel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeoutHeight: { revisionHeight: Long.UZERO, revisionNumber: Long.UZERO, }, timeoutTimestamp: Long.UZERO, }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/ibc.applications.transfer.v1.MsgTransfer", value: msg, }); const expected: AminoMsgTransfer = { type: "cosmos-sdk/MsgTransfer", value: { source_port: "testport", source_channel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeout_height: { revision_height: undefined, revision_number: undefined, }, timeout_timestamp: undefined, }, }; expect(aminoMsg).toEqual(expected); }); it("works for MsgTransfer with no height timeout", () => { const msg: MsgTransfer = { sourcePort: "testport", sourceChannel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeoutHeight: undefined, timeoutTimestamp: Long.UZERO, }; const aminoMsg = new AminoTypes().toAmino({ typeUrl: "/ibc.applications.transfer.v1.MsgTransfer", value: msg, }); const expected: AminoMsgTransfer = { type: "cosmos-sdk/MsgTransfer", value: { source_port: "testport", source_channel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeout_height: {}, timeout_timestamp: undefined, }, }; expect(aminoMsg).toEqual(expected); }); // other it("works with custom type url", () => { const msg = { foo: "bar", }; const aminoMsg = new AminoTypes({ additions: { "/my.CustomType": { aminoType: "my-sdk/CustomType", toAmino: ({ foo, }: { readonly foo: string; }): { readonly foo: string; readonly constant: string } => ({ foo: `amino-prefix-${foo}`, constant: "something-for-amino", }), fromAmino: () => {}, }, }, }).toAmino({ typeUrl: "/my.CustomType", value: msg }); expect(aminoMsg).toEqual({ type: "my-sdk/CustomType", value: { foo: "amino-prefix-bar", constant: "something-for-amino", }, }); }); it("works with overridden type url", () => { const msg: MsgDelegate = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }; const aminoMsg = new AminoTypes({ additions: { "/cosmos.staking.v1beta1.MsgDelegate": { aminoType: "my-override/MsgDelegate", toAmino: (m: MsgDelegate): { readonly foo: string } => ({ foo: m.delegatorAddress ?? "", }), fromAmino: () => {}, }, }, }).toAmino({ typeUrl: "/cosmos.staking.v1beta1.MsgDelegate", value: msg, }); const expected = { type: "my-override/MsgDelegate", value: { foo: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", }, }; expect(aminoMsg).toEqual(expected); }); it("throws for unknown type url", () => { expect(() => new AminoTypes().toAmino({ typeUrl: "/xxx.Unknown", value: { foo: "bar" } })).toThrowError( /Type URL does not exist in the Amino message type register./i, ); }); }); describe("fromAmino", () => { // bank it("works for MsgSend", () => { const aminoMsg: AminoMsgSend = { type: "cosmos-sdk/MsgSend", value: { from_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", to_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coins(1234, "ucosm"), }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgSend = { fromAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", toAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coins(1234, "ucosm"), }; expect(msg).toEqual({ typeUrl: "/cosmos.bank.v1beta1.MsgSend", value: expectedValue, }); }); it("works for MsgMultiSend", () => { const aminoMsg: AminoMsgMultiSend = { type: "cosmos-sdk/MsgMultiSend", value: { inputs: [ { address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", coins: coins(1234, "ucosm") }, { address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", coins: coins(5678, "ucosm") }, ], outputs: [ { address: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", coins: coins(6000, "ucosm") }, { address: "cosmos142u9fgcjdlycfcez3lw8x6x5h7rfjlnfhpw2lx", coins: coins(912, "ucosm") }, ], }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgMultiSend = { inputs: [ { address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", coins: coins(1234, "ucosm") }, { address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", coins: coins(5678, "ucosm") }, ], outputs: [ { address: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", coins: coins(6000, "ucosm") }, { address: "cosmos142u9fgcjdlycfcez3lw8x6x5h7rfjlnfhpw2lx", coins: coins(912, "ucosm") }, ], }; expect(msg).toEqual({ typeUrl: "/cosmos.bank.v1beta1.MsgMultiSend", value: expectedValue, }); }); // gov it("works for MsgDeposit", () => { const aminoMsg: AminoMsgDeposit = { type: "cosmos-sdk/MsgDeposit", value: { amount: [{ amount: "12300000", denom: "ustake" }], depositor: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", proposal_id: "5", }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgDeposit = { amount: [{ amount: "12300000", denom: "ustake" }], depositor: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", proposalId: Long.fromNumber(5), }; expect(msg).toEqual({ typeUrl: "/cosmos.gov.v1beta1.MsgDeposit", value: expectedValue, }); }); it("works for MsgSubmitProposal", () => { const aminoMsg: AminoMsgSubmitProposal = { type: "cosmos-sdk/MsgSubmitProposal", value: { initial_deposit: [{ amount: "12300000", denom: "ustake" }], proposer: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", content: { type: "cosmos-sdk/TextProposal", value: { description: "This proposal proposes to test whether this proposal passes", title: "Test Proposal", }, }, }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgSubmitProposal = { initialDeposit: [{ amount: "12300000", denom: "ustake" }], proposer: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", content: { typeUrl: "/cosmos.gov.v1beta1.TextProposal", value: TextProposal.encode({ description: "This proposal proposes to test whether this proposal passes", title: "Test Proposal", }).finish(), }, }; expect(msg).toEqual({ typeUrl: "/cosmos.gov.v1beta1.MsgSubmitProposal", value: expectedValue, }); }); it("works for MsgVote", () => { const aminoMsg: AminoMsgVote = { type: "cosmos-sdk/MsgVote", value: { option: 4, proposal_id: "5", voter: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgVote = { option: VoteOption.VOTE_OPTION_NO_WITH_VETO, proposalId: Long.fromNumber(5), voter: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", }; expect(msg).toEqual({ typeUrl: "/cosmos.gov.v1beta1.MsgVote", value: expectedValue, }); }); // distribution // TODO: MsgFundCommunityPool // TODO: MsgSetWithdrawAddress // TODO: MsgWithdrawDelegatorReward // TODO: MsgWithdrawValidatorCommission // staking it("works for MsgBeginRedelegate", () => { const aminoMsg: AminoMsgBeginRedelegate = { type: "cosmos-sdk/MsgBeginRedelegate", value: { delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_src_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", validator_dst_address: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", amount: coin(1234, "ucosm"), }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgBeginRedelegate = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorSrcAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", validatorDstAddress: "cosmos1xy4yqngt0nlkdcenxymg8tenrghmek4nmqm28k", amount: coin(1234, "ucosm"), }; expect(msg).toEqual({ typeUrl: "/cosmos.staking.v1beta1.MsgBeginRedelegate", value: expectedValue, }); }); it("works for MsgCreateValidator", () => { const aminoMsg: AminoMsgCreateValidator = { type: "cosmos-sdk/MsgCreateValidator", value: { description: { moniker: "validator", identity: "me", website: "valid.com", security_contact: "Hamburglar", details: "...", }, commission: { rate: "0.2", max_rate: "0.3", max_change_rate: "0.1", }, min_self_delegation: "123", delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", pubkey: encodeBech32Pubkey( { type: "tendermint/PubKeySecp256k1", value: "A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ" }, "cosmos", ), value: coin(1234, "ucosm"), }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgCreateValidator = { description: { moniker: "validator", identity: "me", website: "valid.com", securityContact: "Hamburglar", details: "...", }, commission: { rate: "0.2", maxRate: "0.3", maxChangeRate: "0.1", }, minSelfDelegation: "123", delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", pubkey: { typeUrl: "/cosmos.crypto.secp256k1.PubKey", value: fromBase64("A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ"), }, value: coin(1234, "ucosm"), }; expect(msg).toEqual({ typeUrl: "/cosmos.staking.v1beta1.MsgCreateValidator", value: expectedValue, }); }); it("works for MsgDelegate", () => { const aminoMsg: AminoMsgDelegate = { type: "cosmos-sdk/MsgDelegate", value: { delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgDelegate = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }; expect(msg).toEqual({ typeUrl: "/cosmos.staking.v1beta1.MsgDelegate", value: expectedValue, }); }); it("works for MsgEditValidator", () => { const aminoMsg: AminoMsgEditValidator = { type: "cosmos-sdk/MsgEditValidator", value: { description: { moniker: "validator", identity: "me", website: "valid.com", security_contact: "Hamburglar", details: "...", }, commission_rate: "0.2", min_self_delegation: "123", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgEditValidator = { description: { moniker: "validator", identity: "me", website: "valid.com", securityContact: "Hamburglar", details: "...", }, commissionRate: "0.2", minSelfDelegation: "123", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", }; expect(msg).toEqual({ typeUrl: "/cosmos.staking.v1beta1.MsgEditValidator", value: expectedValue, }); }); it("works for MsgUndelegate", () => { const aminoMsg: AminoMsgUndelegate = { type: "cosmos-sdk/MsgUndelegate", value: { delegator_address: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validator_address: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgUndelegate = { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }; expect(msg).toEqual({ typeUrl: "/cosmos.staking.v1beta1.MsgUndelegate", value: expectedValue, }); }); // ibc it("works for MsgTransfer", () => { const aminoMsg: AminoMsgTransfer = { type: "cosmos-sdk/MsgTransfer", value: { source_port: "testport", source_channel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeout_height: { revision_height: "123", revision_number: "456", }, timeout_timestamp: "789", }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgTransfer = { sourcePort: "testport", sourceChannel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeoutHeight: { revisionHeight: Long.fromString("123", true), revisionNumber: Long.fromString("456", true), }, timeoutTimestamp: Long.fromString("789", true), }; expect(msg).toEqual({ typeUrl: "/ibc.applications.transfer.v1.MsgTransfer", value: expectedValue, }); }); it("works for MsgTransfer with default values", () => { const aminoMsg: AminoMsgTransfer = { type: "cosmos-sdk/MsgTransfer", value: { source_port: "testport", source_channel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeout_height: { // revision_height omitted // revision_number omitted }, // timeout_timestamp omitted }, }; const msg = new AminoTypes().fromAmino(aminoMsg); const expectedValue: MsgTransfer = { sourcePort: "testport", sourceChannel: "testchannel", token: coin(1234, "utest"), sender: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", receiver: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", timeoutHeight: { revisionHeight: Long.UZERO, revisionNumber: Long.UZERO, }, timeoutTimestamp: Long.UZERO, }; expect(msg).toEqual({ typeUrl: "/ibc.applications.transfer.v1.MsgTransfer", value: expectedValue, }); }); // other it("works for custom type url", () => { const aminoMsg = { type: "my-sdk/CustomType", value: { foo: "amino-prefix-bar", constant: "something-for-amino", }, }; const msg = new AminoTypes({ additions: { "/my.CustomType": { aminoType: "my-sdk/CustomType", toAmino: () => {}, fromAmino: ({ foo }: { readonly foo: string; readonly constant: string }): any => ({ foo: foo.slice(13), }), }, }, }).fromAmino(aminoMsg); const expectedValue = { foo: "bar", }; expect(msg).toEqual({ typeUrl: "/my.CustomType", value: expectedValue, }); }); it("works with overridden type url", () => { const msg = new AminoTypes({ additions: { "/my.OverrideType": { aminoType: "cosmos-sdk/MsgDelegate", toAmino: () => {}, fromAmino: ({ foo }: { readonly foo: string }): MsgDelegate => ({ delegatorAddress: foo, validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }), }, }, }).fromAmino({ type: "cosmos-sdk/MsgDelegate", value: { foo: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", }, }); const expected: { readonly typeUrl: "/my.OverrideType"; readonly value: MsgDelegate } = { typeUrl: "/my.OverrideType", value: { delegatorAddress: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6", validatorAddress: "cosmos10dyr9899g6t0pelew4nvf4j5c3jcgv0r73qga5", amount: coin(1234, "ucosm"), }, }; expect(msg).toEqual(expected); }); it("throws for unknown type url", () => { expect(() => new AminoTypes().fromAmino({ type: "cosmos-sdk/MsgUnknown", value: { foo: "bar" } }), ).toThrowError(/Type does not exist in the Amino message type register./i); }); }); });
the_stack
* ORY Oathkeeper * ORY Oathkeeper is a reverse proxy that checks the HTTP Authorization for validity against a set of rules. This service uses Hydra to validate access tokens and policies. * * The version of the OpenAPI document: v0.38.15-beta.1 * Contact: hi@ory.am * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Configuration } from './configuration'; import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; /** * * @export * @interface HealthNotReadyStatus */ export interface HealthNotReadyStatus { /** * Errors contains a list of errors that caused the not ready status. * @type {{ [key: string]: string; }} * @memberof HealthNotReadyStatus */ errors?: { [key: string]: string; }; } /** * * @export * @interface HealthStatus */ export interface HealthStatus { /** * Status always contains \"ok\". * @type {string} * @memberof HealthStatus */ status?: string; } /** * * @export * @interface InlineResponse500 */ export interface InlineResponse500 { /** * * @type {number} * @memberof InlineResponse500 */ code?: number; /** * * @type {Array<object>} * @memberof InlineResponse500 */ details?: Array<object>; /** * * @type {string} * @memberof InlineResponse500 */ message?: string; /** * * @type {string} * @memberof InlineResponse500 */ reason?: string; /** * * @type {string} * @memberof InlineResponse500 */ request?: string; /** * * @type {string} * @memberof InlineResponse500 */ status?: string; } /** * * @export * @interface JsonWebKey */ export interface JsonWebKey { /** * The \"alg\" (algorithm) parameter identifies the algorithm intended for use with the key. The values used should either be registered in the IANA \"JSON Web Signature and Encryption Algorithms\" registry established by [JWA] or be a value that contains a Collision- Resistant Name. * @type {string} * @memberof JsonWebKey */ alg?: string; /** * * @type {string} * @memberof JsonWebKey */ crv?: string; /** * * @type {string} * @memberof JsonWebKey */ d?: string; /** * * @type {string} * @memberof JsonWebKey */ dp?: string; /** * * @type {string} * @memberof JsonWebKey */ dq?: string; /** * * @type {string} * @memberof JsonWebKey */ e?: string; /** * * @type {string} * @memberof JsonWebKey */ k?: string; /** * The \"kid\" (key ID) parameter is used to match a specific key. This is used, for instance, to choose among a set of keys within a JWK Set during key rollover. The structure of the \"kid\" value is unspecified. When \"kid\" values are used within a JWK Set, different keys within the JWK Set SHOULD use distinct \"kid\" values. (One example in which different keys might use the same \"kid\" value is if they have different \"kty\" (key type) values but are considered to be equivalent alternatives by the application using them.) The \"kid\" value is a case-sensitive string. * @type {string} * @memberof JsonWebKey */ kid?: string; /** * The \"kty\" (key type) parameter identifies the cryptographic algorithm family used with the key, such as \"RSA\" or \"EC\". \"kty\" values should either be registered in the IANA \"JSON Web Key Types\" registry established by [JWA] or be a value that contains a Collision- Resistant Name. The \"kty\" value is a case-sensitive string. * @type {string} * @memberof JsonWebKey */ kty?: string; /** * * @type {string} * @memberof JsonWebKey */ n?: string; /** * * @type {string} * @memberof JsonWebKey */ p?: string; /** * * @type {string} * @memberof JsonWebKey */ q?: string; /** * * @type {string} * @memberof JsonWebKey */ qi?: string; /** * The \"use\" (public key use) parameter identifies the intended use of the public key. The \"use\" parameter is employed to indicate whether a public key is used for encrypting data or verifying the signature on data. Values are commonly \"sig\" (signature) or \"enc\" (encryption). * @type {string} * @memberof JsonWebKey */ use?: string; /** * * @type {string} * @memberof JsonWebKey */ x?: string; /** * The \"x5c\" (X.509 certificate chain) parameter contains a chain of one or more PKIX certificates [RFC5280]. The certificate chain is represented as a JSON array of certificate value strings. Each string in the array is a base64-encoded (Section 4 of [RFC4648] -- not base64url-encoded) DER [ITU.X690.1994] PKIX certificate value. The PKIX certificate containing the key value MUST be the first certificate. * @type {Array<string>} * @memberof JsonWebKey */ x5c?: Array<string>; /** * * @type {string} * @memberof JsonWebKey */ y?: string; } /** * * @export * @interface JsonWebKeySet */ export interface JsonWebKeySet { /** * The value of the \"keys\" parameter is an array of JWK values. By default, the order of the JWK values within the array does not imply an order of preference among them, although applications of JWK Sets can choose to assign a meaning to the order for their purposes, if desired. * @type {Array<JsonWebKey>} * @memberof JsonWebKeySet */ keys?: Array<JsonWebKey>; } /** * * @export * @interface Rule */ export interface Rule { /** * Authenticators is a list of authentication handlers that will try and authenticate the provided credentials. Authenticators are checked iteratively from index 0 to n and if the first authenticator to return a positive result will be the one used. If you want the rule to first check a specific authenticator before \"falling back\" to others, have that authenticator as the first item in the array. * @type {Array<RuleHandler>} * @memberof Rule */ authenticators?: Array<RuleHandler>; /** * * @type {RuleHandler} * @memberof Rule */ authorizer?: RuleHandler; /** * Description is a human readable description of this rule. * @type {string} * @memberof Rule */ description?: string; /** * ID is the unique id of the rule. It can be at most 190 characters long, but the layout of the ID is up to you. You will need this ID later on to update or delete the rule. * @type {string} * @memberof Rule */ id?: string; /** * * @type {RuleMatch} * @memberof Rule */ match?: RuleMatch; /** * Mutators is a list of mutation handlers that transform the HTTP request. A common use case is generating a new set of credentials (e.g. JWT) which then will be forwarded to the upstream server. Mutations are performed iteratively from index 0 to n and should all succeed in order for the HTTP request to be forwarded. * @type {Array<RuleHandler>} * @memberof Rule */ mutators?: Array<RuleHandler>; /** * * @type {Upstream} * @memberof Rule */ upstream?: Upstream; } /** * * @export * @interface RuleHandler */ export interface RuleHandler { /** * Config contains the configuration for the handler. Please read the user guide for a complete list of each handler\'s available settings. * @type {object} * @memberof RuleHandler */ config?: object; /** * Handler identifies the implementation which will be used to handle this specific request. Please read the user guide for a complete list of available handlers. * @type {string} * @memberof RuleHandler */ handler?: string; } /** * * @export * @interface RuleMatch */ export interface RuleMatch { /** * An array of HTTP methods (e.g. GET, POST, PUT, DELETE, ...). When ORY Oathkeeper searches for rules to decide what to do with an incoming request to the proxy server, it compares the HTTP method of the incoming request with the HTTP methods of each rules. If a match is found, the rule is considered a partial match. If the matchesUrl field is satisfied as well, the rule is considered a full match. * @type {Array<string>} * @memberof RuleMatch */ methods?: Array<string>; /** * This field represents the URL pattern this rule matches. When ORY Oathkeeper searches for rules to decide what to do with an incoming request to the proxy server, it compares the full request URL (e.g. https://mydomain.com/api/resource) without query parameters of the incoming request with this field. If a match is found, the rule is considered a partial match. If the matchesMethods field is satisfied as well, the rule is considered a full match. You can use regular expressions in this field to match more than one url. Regular expressions are encapsulated in brackets < and >. The following example matches all paths of the domain `mydomain.com`: `https://mydomain.com/<.*>`. * @type {string} * @memberof RuleMatch */ url?: string; } /** * * @export * @interface Upstream */ export interface Upstream { /** * PreserveHost, if false (the default), tells ORY Oathkeeper to set the upstream request\'s Host header to the hostname of the API\'s upstream\'s URL. Setting this flag to true instructs ORY Oathkeeper not to do so. * @type {boolean} * @memberof Upstream */ preserve_host?: boolean; /** * StripPath if set, replaces the provided path prefix when forwarding the requested URL to the upstream URL. * @type {string} * @memberof Upstream */ strip_path?: string; /** * URL is the URL the request will be proxied to. * @type {string} * @memberof Upstream */ url?: string; } /** * * @export * @interface Version */ export interface Version { /** * Version is the service\'s version. * @type {string} * @memberof Version */ version?: string; } /** * ApiApi - axios parameter creator * @export */ export const ApiApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * > This endpoint works with all HTTP Methods (GET, POST, PUT, ...) and matches every path prefixed with /decision. This endpoint mirrors the proxy capability of ORY Oathkeeper\'s proxy functionality but instead of forwarding the request to the upstream server, returns 200 (request should be allowed), 401 (unauthorized), or 403 (forbidden) status codes. This endpoint can be used to integrate with other API Proxies like Ambassador, Kong, Envoy, and many more. * @summary Access Control Decision API * @param {*} [options] Override http request option. * @throws {RequiredError} */ decisions: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/decisions`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Use this method to retrieve a rule from the storage. If it does not exist you will receive a 404 error. * @summary Retrieve a rule * @param {string} id * @param {*} [options] Override http request option. * @throws {RequiredError} */ getRule: async (id: string, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined assertParamExists('getRule', 'id', id) const localVarPath = `/rules/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * This endpoint returns the service version typically notated using semantic versioning. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Get service version * @param {*} [options] Override http request option. * @throws {RequiredError} */ getVersion: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/version`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * This endpoint returns cryptographic keys that are required to, for example, verify signatures of ID Tokens. * @summary Lists cryptographic keys * @param {*} [options] Override http request option. * @throws {RequiredError} */ getWellKnownJSONWebKeys: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/.well-known/jwks.json`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * This endpoint returns a 200 status code when the HTTP server is up running. This status does currently not include checks whether the database connection is working. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Check alive status * @param {*} [options] Override http request option. * @throws {RequiredError} */ isInstanceAlive: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/health/alive`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Check readiness status * @param {*} [options] Override http request option. * @throws {RequiredError} */ isInstanceReady: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/health/ready`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * This method returns an array of all rules that are stored in the backend. This is useful if you want to get a full view of what rules you have currently in place. * @summary List all rules * @param {number} [limit] The maximum amount of rules returned. * @param {number} [offset] The offset from where to start looking. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listRules: async (limit?: number, offset?: number, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/rules`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; if (limit !== undefined) { localVarQueryParameter['limit'] = limit; } if (offset !== undefined) { localVarQueryParameter['offset'] = offset; } setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * ApiApi - functional programming interface * @export */ export const ApiApiFp = function(configuration?: Configuration) { const localVarAxiosParamCreator = ApiApiAxiosParamCreator(configuration) return { /** * > This endpoint works with all HTTP Methods (GET, POST, PUT, ...) and matches every path prefixed with /decision. This endpoint mirrors the proxy capability of ORY Oathkeeper\'s proxy functionality but instead of forwarding the request to the upstream server, returns 200 (request should be allowed), 401 (unauthorized), or 403 (forbidden) status codes. This endpoint can be used to integrate with other API Proxies like Ambassador, Kong, Envoy, and many more. * @summary Access Control Decision API * @param {*} [options] Override http request option. * @throws {RequiredError} */ async decisions(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.decisions(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * Use this method to retrieve a rule from the storage. If it does not exist you will receive a 404 error. * @summary Retrieve a rule * @param {string} id * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getRule(id: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Rule>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getRule(id, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * This endpoint returns the service version typically notated using semantic versioning. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Get service version * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getVersion(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Version>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getVersion(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * This endpoint returns cryptographic keys that are required to, for example, verify signatures of ID Tokens. * @summary Lists cryptographic keys * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getWellKnownJSONWebKeys(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<JsonWebKeySet>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getWellKnownJSONWebKeys(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * This endpoint returns a 200 status code when the HTTP server is up running. This status does currently not include checks whether the database connection is working. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Check alive status * @param {*} [options] Override http request option. * @throws {RequiredError} */ async isInstanceAlive(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<HealthStatus>> { const localVarAxiosArgs = await localVarAxiosParamCreator.isInstanceAlive(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Check readiness status * @param {*} [options] Override http request option. * @throws {RequiredError} */ async isInstanceReady(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<HealthStatus>> { const localVarAxiosArgs = await localVarAxiosParamCreator.isInstanceReady(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * This method returns an array of all rules that are stored in the backend. This is useful if you want to get a full view of what rules you have currently in place. * @summary List all rules * @param {number} [limit] The maximum amount of rules returned. * @param {number} [offset] The offset from where to start looking. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async listRules(limit?: number, offset?: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<Rule>>> { const localVarAxiosArgs = await localVarAxiosParamCreator.listRules(limit, offset, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, } }; /** * ApiApi - factory interface * @export */ export const ApiApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { const localVarFp = ApiApiFp(configuration) return { /** * > This endpoint works with all HTTP Methods (GET, POST, PUT, ...) and matches every path prefixed with /decision. This endpoint mirrors the proxy capability of ORY Oathkeeper\'s proxy functionality but instead of forwarding the request to the upstream server, returns 200 (request should be allowed), 401 (unauthorized), or 403 (forbidden) status codes. This endpoint can be used to integrate with other API Proxies like Ambassador, Kong, Envoy, and many more. * @summary Access Control Decision API * @param {*} [options] Override http request option. * @throws {RequiredError} */ decisions(options?: any): AxiosPromise<void> { return localVarFp.decisions(options).then((request) => request(axios, basePath)); }, /** * Use this method to retrieve a rule from the storage. If it does not exist you will receive a 404 error. * @summary Retrieve a rule * @param {string} id * @param {*} [options] Override http request option. * @throws {RequiredError} */ getRule(id: string, options?: any): AxiosPromise<Rule> { return localVarFp.getRule(id, options).then((request) => request(axios, basePath)); }, /** * This endpoint returns the service version typically notated using semantic versioning. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Get service version * @param {*} [options] Override http request option. * @throws {RequiredError} */ getVersion(options?: any): AxiosPromise<Version> { return localVarFp.getVersion(options).then((request) => request(axios, basePath)); }, /** * This endpoint returns cryptographic keys that are required to, for example, verify signatures of ID Tokens. * @summary Lists cryptographic keys * @param {*} [options] Override http request option. * @throws {RequiredError} */ getWellKnownJSONWebKeys(options?: any): AxiosPromise<JsonWebKeySet> { return localVarFp.getWellKnownJSONWebKeys(options).then((request) => request(axios, basePath)); }, /** * This endpoint returns a 200 status code when the HTTP server is up running. This status does currently not include checks whether the database connection is working. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Check alive status * @param {*} [options] Override http request option. * @throws {RequiredError} */ isInstanceAlive(options?: any): AxiosPromise<HealthStatus> { return localVarFp.isInstanceAlive(options).then((request) => request(axios, basePath)); }, /** * This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Check readiness status * @param {*} [options] Override http request option. * @throws {RequiredError} */ isInstanceReady(options?: any): AxiosPromise<HealthStatus> { return localVarFp.isInstanceReady(options).then((request) => request(axios, basePath)); }, /** * This method returns an array of all rules that are stored in the backend. This is useful if you want to get a full view of what rules you have currently in place. * @summary List all rules * @param {number} [limit] The maximum amount of rules returned. * @param {number} [offset] The offset from where to start looking. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listRules(limit?: number, offset?: number, options?: any): AxiosPromise<Array<Rule>> { return localVarFp.listRules(limit, offset, options).then((request) => request(axios, basePath)); }, }; }; /** * ApiApi - object-oriented interface * @export * @class ApiApi * @extends {BaseAPI} */ export class ApiApi extends BaseAPI { /** * > This endpoint works with all HTTP Methods (GET, POST, PUT, ...) and matches every path prefixed with /decision. This endpoint mirrors the proxy capability of ORY Oathkeeper\'s proxy functionality but instead of forwarding the request to the upstream server, returns 200 (request should be allowed), 401 (unauthorized), or 403 (forbidden) status codes. This endpoint can be used to integrate with other API Proxies like Ambassador, Kong, Envoy, and many more. * @summary Access Control Decision API * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ApiApi */ public decisions(options?: any) { return ApiApiFp(this.configuration).decisions(options).then((request) => request(this.axios, this.basePath)); } /** * Use this method to retrieve a rule from the storage. If it does not exist you will receive a 404 error. * @summary Retrieve a rule * @param {string} id * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ApiApi */ public getRule(id: string, options?: any) { return ApiApiFp(this.configuration).getRule(id, options).then((request) => request(this.axios, this.basePath)); } /** * This endpoint returns the service version typically notated using semantic versioning. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Get service version * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ApiApi */ public getVersion(options?: any) { return ApiApiFp(this.configuration).getVersion(options).then((request) => request(this.axios, this.basePath)); } /** * This endpoint returns cryptographic keys that are required to, for example, verify signatures of ID Tokens. * @summary Lists cryptographic keys * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ApiApi */ public getWellKnownJSONWebKeys(options?: any) { return ApiApiFp(this.configuration).getWellKnownJSONWebKeys(options).then((request) => request(this.axios, this.basePath)); } /** * This endpoint returns a 200 status code when the HTTP server is up running. This status does currently not include checks whether the database connection is working. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Check alive status * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ApiApi */ public isInstanceAlive(options?: any) { return ApiApiFp(this.configuration).isInstanceAlive(options).then((request) => request(this.axios, this.basePath)); } /** * This endpoint returns a 200 status code when the HTTP server is up running and the environment dependencies (e.g. the database) are responsive as well. If the service supports TLS Edge Termination, this endpoint does not require the `X-Forwarded-Proto` header to be set. Be aware that if you are running multiple nodes of this service, the health status will never refer to the cluster state, only to a single instance. * @summary Check readiness status * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ApiApi */ public isInstanceReady(options?: any) { return ApiApiFp(this.configuration).isInstanceReady(options).then((request) => request(this.axios, this.basePath)); } /** * This method returns an array of all rules that are stored in the backend. This is useful if you want to get a full view of what rules you have currently in place. * @summary List all rules * @param {number} [limit] The maximum amount of rules returned. * @param {number} [offset] The offset from where to start looking. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ApiApi */ public listRules(limit?: number, offset?: number, options?: any) { return ApiApiFp(this.configuration).listRules(limit, offset, options).then((request) => request(this.axios, this.basePath)); } }
the_stack
import React = require('React'); // Before Each var container; var attachedListener = null; var renderedName = null; class Inner extends React.Component { getName() { return this.props.name; } render() { attachedListener = this.props.onClick; renderedName = this.props.name; return React.createElement('div', { className: this.props.name }); } }; function test(element, expectedTag, expectedClassName) { var instance = React.render(element, container); expect(container.firstChild).not.toBeNull(); expect(container.firstChild.tagName).toBe(expectedTag); expect(container.firstChild.className).toBe(expectedClassName); return instance; } // Classes need to be declared at the top level scope, so we declare all the // classes that will be used by the tests below, instead of inlining them. // TODO: Consider redesigning this using modules so that we can use non-unique // names of classes and bundle them with the test code. // it preserves the name of the class for use in error messages // it throws if no render function is defined class Empty extends React.Component { } // it renders a simple stateless component with prop class SimpleStateless { props : any; render() { return React.createElement(Inner, {name: this.props.bar}); } } // it renders based on state using initial values in this.props class InitialState extends React.Component { state = { bar: this.props.initialValue }; render() { return React.createElement('span', {className: this.state.bar}); } } // it renders based on state using props in the constructor class StateBasedOnProps extends React.Component { constructor(props) { super(props); this.state = { bar: props.initialValue }; } changeState() { this.setState({ bar: 'bar' }); } render() { if (this.state.bar === 'foo') { return React.createElement('div', {className: 'foo'}); } return React.createElement('span', {className: this.state.bar}); } } // it renders based on context in the constructor class StateBasedOnContext extends React.Component { static contextTypes = { tag: React.PropTypes.string, className: React.PropTypes.string } state = { tag: this.context.tag, className: this.context.className } render() { var Tag = this.state.tag; return React.createElement(Tag, {className: this.state.className}); } } class ProvideChildContextTypes extends React.Component { static childContextTypes = { tag: React.PropTypes.string, className: React.PropTypes.string } getChildContext() { return { tag: 'span', className: 'foo' }; } render() { return React.createElement(StateBasedOnContext); } } // it renders only once when setting state in componentWillMount var renderCount = 0; class RenderOnce extends React.Component { state = { bar: this.props.initialValue } componentWillMount() { this.setState({ bar: 'bar' }); } render() { renderCount++; return React.createElement('span', {className: this.state.bar}); } } // it should throw with non-object in the initial state property class ArrayState { state = ['an array'] render() { return React.createElement('span'); } } class StringState { state = 'a string' render() { return React.createElement('span'); } } class NumberState { state = 1234 render() { return React.createElement('span'); } } // it should render with null in the initial state property class NullState extends React.Component { state = null render() { return React.createElement('span'); } } // it setState through an event handler class BoundEventHandler extends React.Component { state = { bar: this.props.initialValue } handleClick = () => { this.setState({ bar: 'bar' }); } render() { return ( React.createElement(Inner, { name: this.state.bar, onClick: this.handleClick }) ); } } // it should not implicitly bind event handlers class UnboundEventHandler extends React.Component { state = { bar: this.props.initialValue } handleClick() { this.setState({ bar: 'bar' }); } render() { return React.createElement( Inner, { name: this.state.bar, onClick: this.handleClick } ); } } // it renders using forceUpdate even when there is no state class ForceUpdateWithNoState extends React.Component { mutativeValue : string = this.props.initialValue handleClick() { this.mutativeValue = 'bar'; this.forceUpdate(); } render() { return ( React.createElement(Inner, { name: this.mutativeValue, onClick: this.handleClick.bind(this)} ) ); } } // it will call all the normal life cycle methods var lifeCycles = []; class NormalLifeCycles { props : any state = {} componentWillMount() { lifeCycles.push('will-mount'); } componentDidMount() { lifeCycles.push('did-mount'); } componentWillReceiveProps(nextProps) { lifeCycles.push('receive-props', nextProps); } shouldComponentUpdate(nextProps, nextState) { lifeCycles.push('should-update', nextProps, nextState); return true; } componentWillUpdate(nextProps, nextState) { lifeCycles.push('will-update', nextProps, nextState); } componentDidUpdate(prevProps, prevState) { lifeCycles.push('did-update', prevProps, prevState); } componentWillUnmount() { lifeCycles.push('will-unmount'); } render() { return React.createElement('span', {className: this.props.value}); } } // warns when classic properties are defined on the instance, // but does not invoke them. var getInitialStateWasCalled = false; var getDefaultPropsWasCalled = false; class ClassicProperties extends React.Component { contextTypes = {}; propTypes = {}; getDefaultProps() { getDefaultPropsWasCalled = true; return {}; } getInitialState() { getInitialStateWasCalled = true; return {}; } render() { return React.createElement('span', {className: 'foo'}); } } // it should warn when mispelling shouldComponentUpdate class NamedComponent { componentShouldUpdate() { return false; } render() { return React.createElement('span', {className: 'foo'}); } } // it supports this.context passed via getChildContext class ReadContext extends React.Component { static contextTypes = { bar: React.PropTypes.string }; render() { return React.createElement('div', { className: this.context.bar }); } } class ProvideContext { static childContextTypes = { bar: React.PropTypes.string }; getChildContext() { return { bar: 'bar-through-context' }; } render() { return React.createElement(ReadContext); } } // it supports classic refs class ClassicRefs { render() { return React.createElement(Inner, {name: 'foo', ref: 'inner'}); } } // Describe the actual test cases. describe('ReactTypeScriptClass', function() { beforeEach(function() { container = document.createElement('div'); attachedListener = null; renderedName = null; }); it('preserves the name of the class for use in error messages', function() { expect(Empty.name).toBe('Empty'); }); it('throws if no render function is defined', function() { expect(() => React.render(React.createElement(Empty), container)).toThrow(); }); it('renders a simple stateless component with prop', function() { test(React.createElement(SimpleStateless, {bar: 'foo'}), 'DIV', 'foo'); test(React.createElement(SimpleStateless, {bar: 'bar'}), 'DIV', 'bar'); }); it('renders based on state using initial values in this.props', function() { test( React.createElement(InitialState, {initialValue: 'foo'}), 'SPAN', 'foo' ); }); it('renders based on state using props in the constructor', function() { var instance = test( React.createElement(StateBasedOnProps, {initialValue: 'foo'}), 'DIV', 'foo' ); instance.changeState(); test(React.createElement(StateBasedOnProps), 'SPAN', 'bar'); }); it('renders based on context in the constructor', function() { test(React.createElement(ProvideChildContextTypes), 'SPAN', 'foo'); }); it('renders only once when setting state in componentWillMount', function() { renderCount = 0; test(React.createElement(RenderOnce, {initialValue: 'foo'}), 'SPAN', 'bar'); expect(renderCount).toBe(1); }); it('should throw with non-object in the initial state property', function() { expect(() => test(React.createElement(ArrayState), 'span', '')) .toThrow( 'Invariant Violation: ArrayState.state: ' + 'must be set to an object or null' ); expect(() => test(React.createElement(StringState), 'span', '')) .toThrow( 'Invariant Violation: StringState.state: ' + 'must be set to an object or null' ); expect(() => test(React.createElement(NumberState), 'span', '')) .toThrow( 'Invariant Violation: NumberState.state: ' + 'must be set to an object or null' ); }); it('should render with null in the initial state property', function() { test(React.createElement(NullState), 'SPAN', ''); }); it('setState through an event handler', function() { test( React.createElement(BoundEventHandler, {initialValue: 'foo'}), 'DIV', 'foo' ); attachedListener(); expect(renderedName).toBe('bar'); }); it('should not implicitly bind event handlers', function() { test( React.createElement(UnboundEventHandler, {initialValue: 'foo'}), 'DIV', 'foo' ); expect(attachedListener).toThrow(); }); it('renders using forceUpdate even when there is no state', function() { test( React.createElement(ForceUpdateWithNoState, {initialValue: 'foo'}), 'DIV', 'foo' ); attachedListener(); expect(renderedName).toBe('bar'); }); it('will call all the normal life cycle methods', function() { lifeCycles = []; test(React.createElement(NormalLifeCycles, {value: 'foo'}), 'SPAN', 'foo'); expect(lifeCycles).toEqual([ 'will-mount', 'did-mount' ]); lifeCycles = []; // reset test(React.createElement(NormalLifeCycles, {value: 'bar'}), 'SPAN', 'bar'); expect(lifeCycles).toEqual([ 'receive-props', { value: 'bar' }, 'should-update', { value: 'bar' }, {}, 'will-update', { value: 'bar' }, {}, 'did-update', { value: 'foo' }, {} ]); lifeCycles = []; // reset React.unmountComponentAtNode(container); expect(lifeCycles).toEqual([ 'will-unmount' ]); }); it('warns when classic properties are defined on the instance, ' + 'but does not invoke them.', function() { var warn = jest.genMockFn(); console.warn = warn; getInitialStateWasCalled = false; getDefaultPropsWasCalled = false; test(React.createElement(ClassicProperties), 'SPAN', 'foo'); expect(getInitialStateWasCalled).toBe(false); expect(getDefaultPropsWasCalled).toBe(false); expect(warn.mock.calls.length).toBe(4); expect(warn.mock.calls[0][0]).toContain( 'getInitialState was defined on ClassicProperties, ' + 'a plain JavaScript class.' ); expect(warn.mock.calls[1][0]).toContain( 'getDefaultProps was defined on ClassicProperties, ' + 'a plain JavaScript class.' ); expect(warn.mock.calls[2][0]).toContain( 'propTypes was defined as an instance property on ClassicProperties.' ); expect(warn.mock.calls[3][0]).toContain( 'contextTypes was defined as an instance property on ClassicProperties.' ); }); it('should warn when mispelling shouldComponentUpdate', function() { var warn = jest.genMockFn(); console.warn = warn; test(React.createElement(NamedComponent), 'SPAN', 'foo'); expect(warn.mock.calls.length).toBe(1); expect(warn.mock.calls[0][0]).toBe( 'Warning: ' + 'NamedComponent has a method called componentShouldUpdate(). Did you ' + 'mean shouldComponentUpdate()? The name is phrased as a question ' + 'because the function is expected to return a value.' ); }); it('should throw AND warn when trying to access classic APIs', function() { var warn = jest.genMockFn(); console.warn = warn; var instance = test( React.createElement(Inner, {name: 'foo'}), 'DIV','foo' ); expect(() => instance.getDOMNode()).toThrow(); expect(() => instance.replaceState({})).toThrow(); expect(() => instance.isMounted()).toThrow(); expect(() => instance.setProps({ name: 'bar' })).toThrow(); expect(() => instance.replaceProps({ name: 'bar' })).toThrow(); expect(warn.mock.calls.length).toBe(5); expect(warn.mock.calls[0][0]).toContain( 'getDOMNode(...) is deprecated in plain JavaScript React classes' ); expect(warn.mock.calls[1][0]).toContain( 'replaceState(...) is deprecated in plain JavaScript React classes' ); expect(warn.mock.calls[2][0]).toContain( 'isMounted(...) is deprecated in plain JavaScript React classes' ); expect(warn.mock.calls[3][0]).toContain( 'setProps(...) is deprecated in plain JavaScript React classes' ); expect(warn.mock.calls[4][0]).toContain( 'replaceProps(...) is deprecated in plain JavaScript React classes' ); }); it('supports this.context passed via getChildContext', function() { test(React.createElement(ProvideContext), 'DIV', 'bar-through-context'); }); it('supports classic refs', function() { var instance = test(React.createElement(ClassicRefs), 'DIV', 'foo'); expect(instance.refs.inner.getName()).toBe('foo'); }); it('supports drilling through to the DOM using findDOMNode', function() { var instance = test( React.createElement(Inner, {name: 'foo'}), 'DIV', 'foo' ); var node = React.findDOMNode(instance); expect(node).toBe(container.firstChild); }); });
the_stack
import BytesList from 'goog:proto.tensorflow.BytesList'; import Example from 'goog:proto.tensorflow.Example'; import Feature from 'goog:proto.tensorflow.Feature'; import FeatureList from 'goog:proto.tensorflow.FeatureList'; import FeatureLists from 'goog:proto.tensorflow.FeatureLists'; import Features from 'goog:proto.tensorflow.Features'; import FloatList from 'goog:proto.tensorflow.FloatList'; import Int64List from 'goog:proto.tensorflow.Int64List'; import SequenceExample from 'goog:proto.tensorflow.SequenceExample'; namespace wit_example_viewer { // SaliencyMap is a map of feature names to saliency values for their feature // values. The saliency can be a single number for all values in a feature value // list, or a number per value. For sequence examples, there is saliency // information for each sequence number in the example. // TODO(jwexler): Strengthen the difference between array of SaliencyValues and // arrays of numbers in a SaliencyValue. export type SaliencyValue = number | number[]; export type SaliencyMap = { [feature: string]: SaliencyValue | SaliencyValue[]; }; // A helper interface that tracks a feature's values and its name. export interface NameAndFeature { name: string; feature: Feature | FeatureList; } export type OnloadFunction = (feat: string, image: HTMLImageElement) => void; // Information about a single image feature. interface ImageInformation { // image onload function, for re-calling when saliency setting changes. onload?: OnloadFunction; // Raw ImageData arrays for the image. One for the original image, one for the // grayscale image, to be overlaid with a saliency mask. imageData?: Uint8ClampedArray; imageGrayscaleData?: Uint8ClampedArray; // The image element that initially loads the image data for the feature. imageElement?: HTMLImageElement; // Currently applied transform to the image. transform?: d3.ZoomTransform; } // Information stored in data attributes of controls in the visualization. interface DataFromControl { // The feature being altered by this control. feature: string; // The index of the value in the value list being altered by this control. valueIndex: number; // The sequence number of the value list being altered by this control. seqNum: number; } // HTMLElement with bound data attributes to track feature value information. interface HTMLElementWithData extends HTMLElement { dataFeature: string; dataIndex: number; dataSeqNum: number; } export interface HTMLDialogElement extends HTMLElement { open: () => void; } const INT_FEATURE_NAME = 'int'; const FLOAT_FEATURE_NAME = 'float'; const BASE_64_IMAGE_ENCODING_PREFIX = 'base64,'; const CHANGE_CALLBACK_TIMER_DELAY_MS = 1000; const noAttributionColor = '#fff'; const defaultTextColor = '#3c4043'; // Regex to find bytes features that are encoded images. Follows the guide at // go/tf-example. const IMG_FEATURE_REGEX = /^image\/([^\/]+\/)*encoded$/; // Corresponds to a length of a Uint8Array of size 250MB. Above this size we // will not decode a bytes list into a string. const MAX_BYTES_LIST_LENGTH = (1024 * 1024 * 250) / 8; // The max ratio to blend saliency map colors with a grayscaled version of an // image feature, to create a visually-useful saliency mask on an image. const IMG_SALIENCY_MAX_COLOR_RATIO = 0.5; // String returned when a decoded string feature is too large to display. const MAX_STRING_INDICATION = 'String too large to display'; // D3 zoom extent range for image zooming. const ZOOM_EXTENT: [number, number] = [1, 20]; const DEFAULT_WINDOW_WIDTH = 256; const DEFAULT_WINDOW_CENTER = 128; Polymer({ is: 'wit-example-viewer', properties: { example: {type: Object}, serializedExample: {type: String, observer: 'updateExample'}, serializedSeqExample: {type: String, observer: 'updateSeqExample'}, json: {type: Object, observer: 'createExamplesFromJson'}, saliency: {type: Object, value: {}}, saliencyJsonString: {type: String, observer: 'haveSaliencyJson'}, readonly: {type: Boolean, value: false}, seqNumber: {type: Number, value: 0, observer: 'newSeqNum'}, isSequence: Boolean, changeCallbackTimer: Number, ignoreChange: Boolean, minSal: Number, maxSal: Number, showSaliency: {type: Boolean, value: true}, imageInfo: {type: Object, value: {}}, windowWidth: {type: Number, value: DEFAULT_WINDOW_WIDTH}, windowCenter: {type: Number, value: DEFAULT_WINDOW_CENTER}, saliencyCutoff: {type: Number, value: 0}, hasImage: {type: Boolean, value: true}, allowImageControls: {type: Boolean, value: false}, imageScalePercentage: {type: Number, value: 100}, features: {type: Object, computed: 'getFeatures(example)'}, featuresList: { type: Object, computed: 'getFeaturesList(features, compareFeatures)', }, seqFeatures: {type: Object, computed: 'getSeqFeatures(example)'}, seqFeaturesList: { type: Object, computed: 'getFeaturesList(seqFeatures, compareSeqFeatures)', }, maxSeqNumber: { type: Number, computed: 'getMaxSeqNumber(seqFeaturesList)', }, colors: Object, highlightDifferences: { type: Boolean, value: true, }, displayMode: {type: String, value: 'grid'}, featureSearchValue: {type: String, value: '', notify: true}, filteredFeaturesList: {type: Object}, filteredSeqFeaturesList: {type: Object}, focusedFeatureName: String, focusedFeatureValueIndex: Number, focusedSeqNumber: Number, showDeleteValueButton: {type: Boolean, value: false}, expandedFeatures: {type: Object, value: {}}, expandAllFeatures: {type: Boolean, value: false}, zeroIndex: {type: Number, value: 0}, compareJson: {type: Object, observer: 'createCompareExamplesFromJson'}, compareExample: {type: Object}, compareFeatures: { type: Object, computed: 'getFeatures(compareExample)', observer: 'updateCompareMode', }, compareSeqFeatures: { type: Object, computed: 'getSeqFeatures(compareExample)', observer: 'updateCompareMode', }, // The order to sort features. Can be 'attribution', // 'reverse-attribution', or 'alphabetical'. sortOrder: { type: String, value: 'attribution', }, compareMode: Boolean, compareImageInfo: {type: Object, value: {}}, compareTitle: String, textColorFunction: Object, }, observers: [ 'displaySaliency(saliency, example)', 'haveSaliency(filteredFeaturesList, saliency, colors, showSaliency, saliencyCutoff)', 'seqSaliency(seqNumber, seqFeaturesList, saliency, colors, showSaliency, saliencyCutoff)', 'setFilteredFeaturesList(featuresList, featureSearchValue, saliency, sortOrder)', 'setFilteredSeqFeaturesList(seqFeaturesList, featureSearchValue, saliency, sortOrder)', ], isExpanded: function(featName: string, expandAllFeatures: boolean) { return ( this.expandAllFeatures || this.sanitizeFeature(featName) in this.expandedFeatures ); }, updateExample: function() { this.deserializeExample( this.serializedExample, Example.deserializeBinary ); }, // tslint:disable-next-line:no-unused-variable called as observer updateSeqExample: function() { this.deserializeExample( this.serializedSeqExample, SequenceExample.deserializeBinary ); }, /* Helper method to encode a string into a typed array. */ stringToUint8Array: function(str: string) { return new (window as any).TextEncoder().encode(str); }, deserializeExample: function( serializedProto: string, deserializer: (arr: Uint8Array) => Example | SequenceExample ) { // If ignoreChange is set then do not deserialized a newly set serialized // example, which would cause the entire visualization to re-render. if (this.ignoreChange) { return; } const bytes = this.decodedStringToCharCodes(atob(serializedProto)); this.example = deserializer(bytes); }, /** A computed map of all standard features in an example. */ getFeatures: function(example: Example | SequenceExample) { // Reset our maps of image information when a new example is supplied. this.imageInfo = {}; this.hasImage = false; if (example == null) { return new Map<string, FeatureList>([]); } if (example instanceof Example) { this.isSequence = false; if (!example.hasFeatures()) { example.setFeatures(new Features()); } return example.getFeatures()!.getFeatureMap(); } else { this.isSequence = true; if (!example.hasContext()) { example.setContext(new Features()); } return example.getContext()!.getFeatureMap(); } }, /** * A computed list of all standard features in an example, for driving the * display. */ getFeaturesList: function(features: any, compareFeatures: any) { if (features == null) { return []; } const featuresList: NameAndFeature[] = []; const featureSet: {[key: string]: boolean} = {}; let it = features.keys(); if (it) { let next = it.next(); while (!next.done) { featuresList.push({ name: next.value, feature: features.get(next.value)!, }); featureSet[next.value] = true; next = it.next(); } } if (compareFeatures == null) { return featuresList; } it = compareFeatures.keys(); if (it) { let next = it.next(); while (!next.done) { if (next.value in featureSet) { next = it.next(); continue; } featuresList.push({ name: next.value, feature: compareFeatures.get(next.value)!, }); featureSet[next.value] = true; next = it.next(); } } return featuresList; }, /** A computed map of all sequence features in an example. */ getSeqFeatures: function(example: Example | SequenceExample) { if (example == null || example instanceof Example) { return new Map<string, FeatureList>([]); } return (this.example as SequenceExample) .getFeatureLists()! .getFeatureListMap(); }, setFilteredFeaturesList: function( featureList: NameAndFeature[], searchValue: string, saliency: SaliencyMap, sortOrder: string ) { this.filteredFeaturesList = []; this.filteredFeaturesList = this.getFilteredFeaturesList( featureList, searchValue, saliency, sortOrder ); }, setFilteredSeqFeaturesList: function( seqFeatureList: NameAndFeature[], searchValue: string, saliency: SaliencyMap, sortOrder: string ) { this.filteredSeqFeaturesList = []; this.filteredSeqFeaturesList = this.getFilteredFeaturesList( seqFeatureList, searchValue, saliency, sortOrder ); }, getFilteredFeaturesList: function( featureList: NameAndFeature[], searchValue: string, saliency: SaliencyMap, sortOrder: string ) { if (featureList == null) { return; } let filtered = featureList; const checkSal = saliency && Object.keys(saliency).length > 0 && sortOrder != 'alphabetical'; // Create a dict of feature names to the total saliency of all // its feature values, to sort salient features at the top. const saliencyTotals = checkSal ? Object.assign( {}, ...Object.keys(saliency).map((name) => ({ [name]: typeof saliency[name] == 'number' ? (saliency[name] as number) : (saliency[name] as Array<number>).reduce( (total, cur) => total + cur, 0 ), })) ) : {}; if (searchValue != '') { const re = new RegExp(searchValue, 'i'); filtered = featureList.filter((feature) => re.test(feature.name)); } const sorted = filtered.sort((a, b) => { if (this.isImage(a.name) && !this.isImage(b.name)) { return -1; } else if (this.isImage(b.name) && !this.isImage(a.name)) { return 1; } else { if (checkSal) { if (a.name in saliency && !(b.name in saliency)) { return -1; } else if (b.name in saliency && !(a.name in saliency)) { return 1; } else { const diff = sortOrder == 'attribution' ? saliencyTotals[b.name] - saliencyTotals[a.name] : sortOrder == 'reverse-attribution' ? saliencyTotals[a.name] - saliencyTotals[b.name] : Math.abs(saliencyTotals[b.name]) - Math.abs(saliencyTotals[a.name]); if (diff != 0) { return diff; } } } return a.name.localeCompare(b.name); } }); return sorted; }, /** * Returns the maximum sequence length in the sequence example, or -1 if * there are no sequences. */ getMaxSeqNumber: function() { let max = -1; for (const feat of this.seqFeaturesList) { const list = feat.feature as FeatureList; if (list && list.getFeatureList().length - 1 > max) { max = list.getFeatureList().length - 1; } } return max; }, haveSaliencyJson: function() { this.saliency = JSON.parse(this.saliencyJsonString); }, selectAll: function(query: string) { return d3.selectAll(Polymer.dom(this.root).querySelectorAll( query ) as any); }, displaySaliency: function(saliency: SaliencyMap) { const feats = Object.keys(saliency); const salJson: any = {}; // Create a tf.Example json containing the saliency for each feature. for (let i = 0; i < feats.length; i++) { const feat = feats[i]; let salValues = saliency[feat]; if (!Array.isArray(salValues)) { salValues = [salValues]; } salJson[feat] = { floatList: { value: (salValues as number[]).map((sal: number) => d3.format('.4f')(sal) ), }, }; } this.saliencyJson = {features: {feature: salJson}}; // Set the compareJson to this, for display beside the feature values. this.compareJson = this.saliencyJson; }, haveSaliency: function() { // Saliency-coloring waits until the display elements have been updated // to avoid coloring divs that are then re-ordered/re-used/re-named by // the dom-repeat of feature divs. requestAnimationFrame(() => this._haveSaliencyImpl()); }, _haveSaliencyImpl: function() { // TODO(jameswex): Color counterfactual column if using attribution-based // counterfactuals. // Reset all value pills to default settings. this.selectAll('.value-pill') .style('background', noAttributionColor) .attr('title', '') .style('color', defaultTextColor); if ( !this.filteredFeaturesList || !this.saliency || Object.keys(this.saliency).length === 0 || !this.colors ) { return; } // Color the text of each input element of each feature according to the // provided saliency information. for (const feat of this.filteredFeaturesList) { const val = this.saliency[feat.name] as SaliencyValue; // If there is no saliency information for the feature, do not color it. if (val == null) { continue; } // Set background color, tooltip, and text color, which are all based // on saliency score. const colorFn = Array.isArray(val) ? (d: {}, i: number) => this.getColorForSaliency(val[i]) : () => this.getColorForSaliency(val); this.selectAll(`.${this.sanitizeFeature(feat.name)}.value-pill`) .style( 'background', this.showSaliency ? colorFn : () => noAttributionColor ) .attr( 'title', (d: {}, i: number) => 'Attribution: ' + d3.format('.4f')(Array.isArray(val) ? val[i] : val) ) .style('color', (d: {}, i: number) => { const num = Array.isArray(val) ? val[i] : val; return this.textColorFunction(num, this.minSal, this.maxSal); }); // Color the "more feature values" button with the most extreme saliency // of any of the feature values hidden behind the button. if (Array.isArray(val)) { const valArray = val as Array<number>; const moreButton = this.selectAll( `paper-button.${this.sanitizeFeature(feat.name)}.value-pill` ); let mostExtremeSal = 0; for (let i = 1; i < valArray.length; i++) { if (Math.abs(valArray[i]) > Math.abs(mostExtremeSal)) { mostExtremeSal = valArray[i]; } } moreButton.style( 'background', this.showSaliency ? () => this.getColorForSaliency(mostExtremeSal) : () => noAttributionColor ); } } }, /** * Updates the saliency coloring of the sequential features when the current * sequence number changes. */ newSeqNum: function() { this.seqSaliency(); }, seqSaliency: function() { if ( !this.seqFeaturesList || !this.saliency || Object.keys(this.saliency).length === 0 || !this.colors ) { return; } // TODO(jwexler): Find a way to do this without requestAnimationFrame. // If the paper-inputs for the features have yet to be rendered, wait to // perform this processing. if (this.selectAll('.value input').size() < this.seqFeaturesList.length) { requestAnimationFrame(() => this.seqSaliency()); return; } // Color the text of each input element of each feature according to the // provided saliency information for the current sequence number. for (const feat of this.seqFeaturesList) { const vals: SaliencyValue[] = this.saliency[ feat.name ] as SaliencyValue[]; // If there is no saliency information for the feature, do not color it. if (!vals) { continue; } const val = vals[this.seqNumber]; const colorFn = Array.isArray(val) ? (d: {}, i: number) => this.getColorForSaliency(val[i]) : () => this.getColorForSaliency(val); this.selectAll(`.${this.sanitizeFeature(feat.name)} input`).style( 'color', this.showSaliency ? colorFn : () => 'black' ); } }, /** * Returns a list of the feature values for a feature. If keepBytes is true * then return the raw bytes. Otherwise convert them to a readable string. */ getFeatureValues: function( feature: string, keepBytes?: boolean, isImage?: boolean, compareValues?: boolean ): Array<string | number> { const feat = compareValues ? this.compareFeatures.get(feature) : this.features.get(feature); if (!feat) { return []; } if (feat.getBytesList()) { if (!keepBytes) { const vals = feat .getBytesList()! .getValueList_asU8() .map((u8array) => this.decodeBytesListString(u8array, isImage)); return vals; } return feat .getBytesList()! .getValueList() .slice(); } else if (feat.getInt64List()) { return feat .getInt64List()! .getValueList() .slice(); } else if (feat.getFloatList()) { return feat .getFloatList()! .getValueList() .slice(); } return []; }, /** * Returns a list of the feature values for a the compared example for * a feature. */ getCompareFeatureValues: function( feature: string, keepBytes?: boolean, isImage?: boolean ): Array<string | number> { return this.getFeatureValues(feature, keepBytes, isImage, true); }, /** Returns the first feature value for a feature. */ getFirstFeatureValue: function(feature: string) { return this.getFeatureValues(feature)[0]; }, /** Returns the first feature value for a compared example for a feature. */ getFirstCompareFeatureValue: function(feature: string) { return this.getCompareFeatureValues(feature)[0]; }, /** Returns if a feature has more than one feature value. */ featureHasMultipleValues: function(feature: string) { return this.getFeatureValues(feature).length > 1; }, /** * Returns if a feature has more than one feature value in the compared * example. */ compareFeatureHasMultipleValues: function(feature: string) { return this.getCompareFeatureValues(feature).length > 1; }, /** * Returns a list of the sequence feature values for a feature for a given * sequence number. If keepBytes is true then return the raw bytes. Otherwise * convert them to a readable string. */ getSeqFeatureValues: function( feature: string, seqNum: number, keepBytes?: boolean, isImage?: boolean, compareValues?: boolean ) { const featlistholder = compareValues ? this.compareSeqFeatures!.get(feature) : this.seqFeatures!.get(feature); if (!featlistholder) { return []; } const featlist = featlistholder.getFeatureList(); // It is possible that there are features that do not have sequence lengths // as long as the longest sequence length in the example. In this case, // show an empty feature value list for that feature. if (!featlist || featlist.length <= seqNum) { return []; } const feat = featlist[seqNum]; if (!feat) { return []; } if (feat.getBytesList()) { if (!keepBytes) { return feat .getBytesList()! .getValueList_asU8() .map((u8array) => this.decodeBytesListString(u8array, isImage)); } return feat.getBytesList()!.getValueList(); } else if (feat.getInt64List()) { return feat.getInt64List()!.getValueList(); } else if (feat.getFloatList()) { return feat.getFloatList()!.getValueList(); } return []; }, /** * Returns a list of the sequence feature values for a feature for a given * sequence number of the compared example. */ getCompareSeqFeatureValues: function( feature: string, seqNum: number, keepBytes?: boolean, isImage?: boolean ): Array<string | number> { return this.getSeqFeatureValues( feature, seqNum, keepBytes, isImage, true ); }, /** Returns the first feature value for a sequence feature. */ getFirstSeqFeatureValue: function(feature: string, seqNum: number) { return this.getSeqFeatureValues(feature, seqNum)[0]; }, /** Returns the first feature value for the compared example for a feature. */ getFirstSeqCompareFeatureValue: function(feature: string, seqNum: number) { return this.getCompareSeqFeatureValues(feature, seqNum)[0]; }, /** Returns if a sequence feature has more than one feature value. */ seqFeatureHasMultipleValues: function(feature: string, seqNum: number) { return this.getSeqFeatureValues(feature, seqNum).length > 1; }, /** * Returns if a sequence feature has more than one feature value in the * compared example. */ compareSeqFeatureHasMultipleValues: function( feature: string, seqNum: number ) { return this.getCompareSeqFeatureValues(feature, seqNum).length > 1; }, /** * Decodes a list of bytes into a readable string, treating the bytes as * unicode char codes. If singleByteChars is true, then treat each byte as its * own char, which is necessary for image strings and serialized protos. * Returns an empty string for arrays over 250MB in size, which should not * be an issue in practice with tf.Examples. */ decodeBytesListString: function( bytes: Uint8Array, singleByteChars?: boolean ) { if (bytes.length > MAX_BYTES_LIST_LENGTH) { return MAX_STRING_INDICATION; } return singleByteChars ? this.decodeBytesListToString(bytes) : new (window as any).TextDecoder().decode(bytes); }, isBytesFeature: function(feature: string) { const feat = this.features.get(feature); if (feat) { if (feat.hasBytesList()) { return true; } } const seqfeat = this.seqFeatures.get(feature); if (seqfeat) { if (seqfeat.getFeatureList()[0].hasBytesList()) { return true; } } return false; }, /** * Returns the feature object from the provided json attribute for a given * feature name. */ getJsonFeature: function(feat: string) { if (!this.json) { return null; } if (this.json.features && this.json.features.feature) { const jsonFeature = this.json.features.feature[feat]; if (jsonFeature) { return jsonFeature; } } if (this.json.context && this.json.context.feature) { const jsonFeature = this.json.context.feature[feat]; if (jsonFeature) { return jsonFeature; } } if (this.json.featureLists && this.json.featureLists.featureList) { return this.json.featureLists.featureList[feat]; } return null; }, /** * Returns the value list from the provided json attribute for a given * feature name and sequence number (when the feature is sequential). The * sequence number should be NaN for non-sequential features. */ getJsonValueList: function(feat: string, seqNum: number) { // Get the feature object for the feature name provided. let feature = this.getJsonFeature(feat); if (!feature) { return null; } // If a sequential feature, get the feature entry for the given sequence // number. if (!isNaN(seqNum)) { feature = feature.feature[seqNum]; } const valueList = feature.bytesList || feature.int64List || feature.floatList; return valueList ? valueList.value : null; }, /** * From an element, finds the feature, value list index and sequence number * that the element corresponds to. */ getDataFromElem: function(elem: HTMLElementWithData): DataFromControl { // Get the control that contains the target data. The control will have its // data-feature attribute set. while (elem.dataFeature == null) { if (!elem.parentElement) { throw new Error('Could not find ancestor control element'); } elem = elem.parentElement as HTMLElementWithData; } return { feature: elem.dataFeature, valueIndex: elem.dataIndex, seqNum: elem.dataSeqNum, }; }, /** * From an event, finds the feature, value list index and sequence number * that the event corresponds to. */ getDataFromEvent: function(event: Event): DataFromControl { return this.getDataFromElem(event.target); }, /** Gets the Feature object corresponding to the provided DataFromControl. */ getFeatureFromData: function(data: DataFromControl): Feature | undefined { // If there is no sequence number, then it is a standard feature, not a // sequential feature. if (isNaN(data.seqNum)) { return this.features.get(data.feature); } else { const featureLists = this.seqFeatures.get(data.feature); if (!featureLists) { return undefined; } const featureList = featureLists.getFeatureList(); if (!featureList) { return undefined; } return featureList[data.seqNum]; } }, /** Gets the value list corresponding to the provided DataFromControl. */ getValueListFromData: function( data: DataFromControl ): Array<string | number> { // If there is no sequence number, then it is a standard feature, not a // sequential feature. if (isNaN(data.seqNum)) { return this.getFeatureValues(data.feature, true); } else { return this.getSeqFeatureValues(data.feature, data.seqNum, true); } }, /** Sets the value list on the provided feature. */ setFeatureValues: function(feat: Feature, values: Array<string | number>) { const bytesList = feat.getBytesList(); const int64List = feat.getInt64List(); const floatList = feat.getFloatList(); if (bytesList) { bytesList.setValueList(values as string[]); } else if (int64List) { int64List.setValueList(values as number[]); } else if (floatList) { floatList.setValueList(values as number[]); } }, /** * When a feature value changes from a paper-input, updates the example proto * appropriately. */ onValueChanged: function(event: Event) { const inputControl = event.target as HTMLInputElement; const data = this.getDataFromEvent(event); const feat = this.getFeatureFromData(data); const values = this.getValueListFromData(data); if (feat) { if (this.isBytesFeature(data.feature)) { // For string features, convert the string into the char code array // for storage in the proto. const cc = this.stringToUint8Array(inputControl.value); // tslint:disable-next-line:no-any cast due to tf.Example typing. values[data.valueIndex] = cc as any; // If the example was provided as json, update the byteslist in the // json with the base64 encoded string. For non-bytes features we don't // need this separate json update as the proto value list is the same // as the json value list for that case (shallow copy). The byteslist // case is different as the json base64 encoded string is converted to // a list of bytes, one per character. const jsonList = this.getJsonValueList(data.feature, data.seqNum); if (jsonList) { jsonList[data.valueIndex] = btoa(inputControl.value); } } else { values[data.valueIndex] = +inputControl.value; const jsonList = this.getJsonValueList(data.feature, data.seqNum); if (jsonList) { jsonList[data.valueIndex] = +inputControl.value; } } this.setFeatureValues(feat, values); this.exampleChanged(); } }, onInputFocus: function(event: Event) { const inputControl = event.target as HTMLInputElement; const data = this.getDataFromEvent(event); this.focusedFeatureName = data.feature; this.focusedFeatureValueIndex = data.valueIndex; this.focusedSeqNumber = data.seqNum; this.$.deletevalue.style.top = inputControl.getBoundingClientRect().top - this.getBoundingClientRect().top - 25 + 'px'; this.$.deletevalue.style.right = this.getBoundingClientRect().right - inputControl.getBoundingClientRect().right + 30 + 'px'; this.showDeleteValueButton = true; }, onInputBlur: function(event: Event) { this.showDeleteValueButton = false; }, /** * When a feature is deleted, updates the example proto appropriately. */ deleteFeature: function(event: Event) { const data = this.getDataFromEvent(event); if (this.features.del) { this.features.del(data.feature); } if (this.seqFeatures.del) { this.seqFeatures.del(data.feature); } this.deleteJsonFeature(data.feature); this.exampleChanged(); this.refreshExampleViewer(); }, /** * Helper method to delete a feature from the JSON version of the example, * if the example was provided as JSON. */ deleteJsonFeature: function(feature: string) { if (this.json) { if (this.json.features && this.json.features.feature) { delete this.json.features.feature[feature]; } if (this.json.context && this.json.context.feature) { delete this.json.context.feature[feature]; } if (this.json.featureLists && this.json.featureLists.featureList) { delete this.json.featureLists.featureList[feature]; } } }, /** * When a feature value is deleted, updates the example proto appropriately. */ deleteValue: function(event: Event) { const data = this.getDataFromEvent(event); const feat = this.getFeatureFromData(data); const values = this.getValueListFromData(data); if (feat) { if (this.isBytesFeature(data.feature)) { // If the example was provided as json, update the byteslist in the // json. For non-bytes features we don't need this separate json update // as the proto value list is the same as the json value list for that // case (shallow copy). The byteslist case is different as the json // base64 encoded string is converted to a list of bytes, one per // character. const jsonList = this.getJsonValueList(data.feature, data.seqNum); if (jsonList) { jsonList.splice(data.valueIndex, 1); } } values.splice(data.valueIndex, 1); this.setFeatureValues(feat, values); this.exampleChanged(); this.refreshExampleViewer(); } }, openAddFeatureDialog: function() { this.$.addFeatureDialog.open(); }, /** * When a feature is added, updates the example proto appropriately. */ addFeature: function(event: Event) { if (!this.json) { return; } const feat = new Feature(); // tslint:disable-next-line:no-any Using arbitrary json. let jsonFeat: any; if (this.newFeatureType === INT_FEATURE_NAME) { const valueList: number[] = []; const ints = new Int64List(); ints.setValueList(valueList); feat.setInt64List(ints); jsonFeat = {int64List: {value: valueList}}; } else if (this.newFeatureType === FLOAT_FEATURE_NAME) { const valueList: number[] = []; const floats = new FloatList(); floats.setValueList(valueList); feat.setFloatList(floats); jsonFeat = {floatList: {value: valueList}}; } else { const valueList: string[] = []; const bytes = new BytesList(); bytes.setValueList(valueList); feat.setBytesList(bytes); jsonFeat = {bytesList: {value: valueList}}; } this.features.set(this.newFeatureName, feat); this.addJsonFeature(this.newFeatureName, jsonFeat); this.newFeatureName = ''; this.exampleChanged(); this.refreshExampleViewer(); }, /** * Helper method to add a feature to the JSON version of the example, * if the example was provided as JSON. */ // tslint:disable-next-line:no-any Using arbitrary json. addJsonFeature: function(feature: string, jsonFeat: any) { if (this.json && this.json.features && this.json.features.feature) { this.json.features.feature[feature] = jsonFeat; } else if (this.json && this.json.context && this.json.context.feature) { this.json.context.feature[feature] = jsonFeat; } }, /** * When a feature value is added, updates the example proto appropriately. */ addValue: function(event: Event) { const data = this.getDataFromEvent(event); const feat = this.getFeatureFromData(data); const values = this.getValueListFromData(data); if (feat) { if (this.isBytesFeature(data.feature)) { values.push(''); } else { values.push(0); } this.setFeatureValues(feat, values); this.exampleChanged(); this.refreshExampleViewer(); } }, /** * Refreshes the example viewer so that it correctly shows the updated * example. */ refreshExampleViewer: function() { // In order for iron-lists to be properly updated based on proto changes, // need to bind the example to another (blank) example, and then back the // the proper example after that change has been processed. // TODO(jwexler): Find better way to update the visuals on proto changes. const temp = this.example; this.ignoreChange = true; this.example = new Example(); this.ignoreChange = false; setTimeout(() => { this.example = temp; this.haveSaliency(); }, 0); }, exampleChanged: function() { // Fire example-change event. this.fire('example-change', {example: this.example}); // This change is performed after a delay in order to debounce rapid updates // to a text/number field, as serialization can take some time and freeze // the visualization temporarily. clearTimeout(this.changeCallbackTimer); this.changeCallbackTimer = setTimeout( this.changeCallback.bind(this), CHANGE_CALLBACK_TIMER_DELAY_MS ); }, changeCallback: function() { // To update the serialized example, we need to ensure we ignore parsing // of the updated serialized example back to an example object as they // already match and this would cause a lot of unnecessary processing, // leading to long freezes in the visualization. this.ignoreChange = true; if (this.isSequence && this.serializedSeqExample) { this.serializedSeqExample = btoa( this.decodeBytesListString(this.example.serializeBinary(), true) ); } else if (this.serializedExample) { this.serializedExample = btoa( this.decodeBytesListString(this.example.serializeBinary(), true) ); } this.ignoreChange = false; }, getInputPillClass: function(feat: string, displayMode: string) { return ( this.sanitizeFeature(feat) + ' value-pill' + (displayMode == 'grid' ? ' value-pill-grid' : ' value-pill-stacked') ); }, getCompareInputClass: function( feat: string, displayMode: string, index?: number ) { let str = 'value-compare' + (displayMode == 'grid' ? ' value-pill-grid' : ' value-pill-stacked'); if (index != null) { const values = this.getFeatureValues(feat, true); const compValues = this.getCompareFeatureValues(feat, true); if ( this.highlightDifferences && (index >= values.length || index >= compValues.length || values[index] != compValues[index]) ) { str += ' value-different'; } else { str += ' value-same'; } } return str; }, getSeqCompareInputClass: function( feat: string, displayMode: string, seqNumber: number, index?: number ) { let str = 'value-compare' + (displayMode == 'grid' ? ' value-pill-grid' : ' value-pill-stacked'); if (index != null) { const values = this.getSeqFeatureValues(feat, seqNumber, true); const compValues = this.getCompareSeqFeatureValues( feat, seqNumber, true ); if ( index >= values.length || index >= compValues.length || values[index] != compValues[index] ) { str += ' value-different'; } else { str += ' value-same'; } } return str; }, /** * Replaces non-standard chars in feature names with underscores so they can * be used in css classes/ids. */ sanitizeFeature: function(feat: string) { let sanitized = feat.trim(); if (!sanitized.match(/^[A-Za-z].*$/)) { sanitized = '_' + sanitized; } return sanitized.replace(/[\/\.\#\s]/g, '_'); }, isSeqExample: function(maxSeqNumber: number) { return maxSeqNumber >= 0; }, isImage: function(feat: string) { return IMG_FEATURE_REGEX.test(feat); }, /** * Returns the data URI src for a feature value that is an encoded image. */ getImageSrc: function(feat: string) { this.setupOnloadCallback(feat); return this.getImageSrcForData(feat, this.getFeatureValues( feat, false, true )[0] as string); }, /** * Returns the data URI src for a feature value that is an encoded image, for * the compared example. */ getCompareImageSrc: function(feat: string) { this.setupOnloadCallback(feat, true); return this.getImageSrcForData( feat, this.getCompareFeatureValues(feat, false, true)[0] as string, true ); }, /** * Returns the data URI src for a sequence feature value that is an encoded * image. */ getSeqImageSrc: function(feat: string, seqNum: number) { this.setupOnloadCallback(feat); return this.getImageSrcForData(feat, this.getSeqFeatureValues( feat, seqNum, false, true )[0] as string); }, /** * Returns the data URI src for a sequence feature value that is an encoded * image, for the compared example. */ getCompareSeqImageSrc: function(feat: string, seqNum: number) { this.setupOnloadCallback(feat, true); return this.getImageSrcForData( feat, this.getCompareSeqFeatureValues(feat, seqNum, false, true)[0] as string, true ); }, /** * On the next frame, sets the onload callback for the image for the given * feature. This is delayed until the next frame to ensure the img element * is rendered before setting up the onload function. */ setupOnloadCallback: function(feat: string, compare?: boolean) { requestAnimationFrame(() => { const img = this.$$( '#' + this.getImageId(feat, compare) ) as HTMLImageElement; img.onload = this.getOnLoadForImage(feat, img, compare); }); }, /** Helper method used by getImageSrc and getSeqImageSrc. */ getImageSrcForData: function( feat: string, imageData: string, compare?: boolean ) { // Get the format of the encoded image, according to the feature name // specified by go/tf-example. Defaults to jpeg as specified in the doc. const regExResult = IMG_FEATURE_REGEX.exec(feat); if (regExResult == null) { return null; } const featureMiddle = regExResult[1] || ''; const formatVals = compare ? this.getCompareFeatureValues( 'image' + featureMiddle + '/format', false ) : this.getFeatureValues('image' + featureMiddle + '/format', false); let format = 'jpeg'; if (formatVals.length > 0) { format = (formatVals[0] as string).toLowerCase(); } let src = 'data:image/' + format + ';base64,'; // Encode the image data in base64. src = src + btoa(decodeURIComponent(encodeURIComponent(imageData))); return src; }, /** Returns the length of an iterator. */ getIterLength: function(it: any) { let len = 0; if (it) { let next = it.next(); while (!next.done) { len++; next = it.next(); } } return len; }, /** * Updates the compare mode based off of the compared example. */ updateCompareMode: function() { let compareMode = false; if ( (this.compareFeatures && this.getIterLength(this.compareFeatures.keys()) > 0) || (this.compareSeqFeatures && this.getIterLength(this.compareSeqFeatures.keys()) > 0) ) { compareMode = true; } this.compareMode = compareMode; }, /** * Creates tf.Example or tf.SequenceExample jspb object from json. Useful when * this is embedded into a OnePlatform app that sends protos as json. */ createExamplesFromJson: function(json: string) { this.example = this.createExamplesFromJsonHelper(json); this.compareJson = {}; }, /** * Creates compared tf.Example or tf.SequenceExample jspb object from json. * Useful when this is embedded into a OnePlatform app that sends protos as * json. */ createCompareExamplesFromJson: function(json: string) { // If setting the compare example back to empty, and there is saliency // information, then set the compare info to the saliency so that it // is displayed instead of nothing. if (!json || !Object.keys(json).length) { if (this.saliencyJson) { json = this.saliencyJson; } else { this.compareExample = null; return; } } this.compareExample = this.createExamplesFromJsonHelper(json); }, createExamplesFromJsonHelper: function(json: any) { if (!json) { return null; } // If the provided json is a json string, parse it into an object. if (typeof this.json === 'string') { json = JSON.parse(this.json); } if (json.features) { const ex = new Example(); ex.setFeatures(this.parseFeatures(json.features)); return ex; } else if (json.context || json.featureLists) { const seqex = new SequenceExample(); if (json.context) { seqex.setContext(this.parseFeatures(json.context)); } if (json.featureLists) { seqex.setFeatureLists(this.parseFeatureLists(json.featureLists)); } return seqex; } else { return new Example(); } }, // tslint:disable-next-line:no-any Parsing arbitrary json. parseFeatures: function(features: any) { const feats = new Features(); for (const fname in features.feature) { if (features.feature.hasOwnProperty(fname)) { const featentry = features.feature[fname]; feats .getFeatureMap() .set(fname, this.parseFeature(featentry, this.isImage(fname))); } } return feats; }, // tslint:disable-next-line:no-any Parsing arbitrary json. parseFeatureLists: function(features: any) { const feats = new FeatureLists(); for (const fname in features.featureList) { if (features.featureList.hasOwnProperty(fname)) { const featlistentry = features.featureList[fname]; const featList = new FeatureList(); const featureList: Feature[] = []; for (const featentry in featlistentry.feature) { if (featlistentry.feature.hasOwnProperty(featentry)) { const feat = featlistentry.feature[featentry]; featureList.push(this.parseFeature(feat, this.isImage(fname))); } } featList.setFeatureList(featureList); feats.getFeatureListMap().set(fname, featList); } } return feats; }, // tslint:disable-next-line:no-any Parsing arbitrary json. parseFeature: function(featentry: any, isImage: boolean) { const feat = new Feature(); if (featentry.floatList) { const floats = new FloatList(); floats.setValueList(featentry.floatList.value); feat.setFloatList(floats); } else if (featentry.bytesList) { // Json byteslist entries are base64. The JSPB generated Feature class // will marshall this to U8 automatically. const bytes = new BytesList(); if (featentry.bytesList.value) { bytes.setValueList(featentry.bytesList.value); } feat.setBytesList(bytes); } else if (featentry.int64List) { const ints = new Int64List(); ints.setValueList(featentry.int64List.value); feat.setInt64List(ints); } return feat; }, getImageId: function(feat: string, compare?: boolean) { if (compare) { return this.getCompareImageId(feat); } return this.sanitizeFeature(feat) + '_image'; }, getCanvasId: function(feat: string, compare?: boolean) { if (compare) { return this.getCompareCanvasId(feat); } return this.sanitizeFeature(feat) + '_canvas'; }, getImageCardId: function(feat: string, compare?: boolean) { if (compare) { return this.getCompareImageCardId(feat); } return this.sanitizeFeature(feat) + '_card'; }, getCompareImageId: function(feat: string) { return this.sanitizeFeature(feat) + '_image_compare'; }, getCompareCanvasId: function(feat: string) { return this.sanitizeFeature(feat) + '_canvas_compare'; }, getCompareImageCardId: function(feat: string) { return this.sanitizeFeature(feat) + '_card_compare'; }, getFeatureDialogId: function(feat: string) { return this.sanitizeFeature(feat) + '_dialog'; }, featureMoreClicked: function(event: Event) { const button = event.srcElement; const feature = (button as any).dataFeature; const dialog = this.$$('#' + this.sanitizeFeature(feature) + '_dialog'); dialog.positionTarget = button; dialog.open(); }, expandFeature: function(event: Event) { const feature = (event.srcElement as any).dataFeature; this.set('expandedFeatures.' + this.sanitizeFeature(feature), true); this.refreshExampleViewer(); }, decodedStringToCharCodes: function(str: string): Uint8Array { const cc = new Uint8Array(str.length); for (let i = 0; i < str.length; ++i) { cc[i] = str.charCodeAt(i); } return cc; }, handleImageUpload: function(event: Event) { this.handleFileSelect(event, this); }, // Handle upload image paper button click by delegating to appropriate // paper-input file chooser. uploadImageClicked: function(event: Event) { const data = this.getDataFromEvent(event); const inputs = Polymer.dom(this.root).querySelectorAll('paper-input'); let inputElem = null; for (let i = 0; i < inputs.length; i++) { if ((inputs[i] as any).dataFeature == data.feature) { inputElem = inputs[i]; break; } } if (inputElem) { inputElem.shadowRoot.querySelector('input').click(); } }, // Handle file select for image replacement. handleFileSelect: function(event: Event, self: any) { event.stopPropagation(); event.preventDefault(); const target = event.target; const reader = new FileReader(); const eventAny = event as any; const files = eventAny.dataTransfer ? eventAny.dataTransfer.files : eventAny.target.inputElement.inputElement.files; if (files.length === 0) { return; } reader.addEventListener( 'load', () => { // Get the image data from the loaded image and convert to a char // code array for use in the features value list. const index = +reader.result.indexOf(BASE_64_IMAGE_ENCODING_PREFIX) + BASE_64_IMAGE_ENCODING_PREFIX.length; const encodedImageData = reader.result.substring(index); const cc = self.decodedStringToCharCodes(atob(encodedImageData)); const data = self.getDataFromElem(target); const feat = self.getFeatureFromData(data); const values = self.getValueListFromData(data); if (feat) { // Replace the old image data in the feature value list with the new // image data. // tslint:disable-next-line:no-any cast due to tf.Example typing. values[0] = cc as any; feat.getBytesList()!.setValueList(values as string[]); // If the example was provided as json, update the byteslist in the // json with the base64 encoded string. const jsonList = self.getJsonValueList(data.feature, data.seqNum); if (jsonList) { jsonList[0] = encodedImageData; } // Load the image data into an image element to begin the process // of rendering that image to a canvas for display. const img = new Image(); self.addImageElement(data.feature, img); img.addEventListener('load', () => { // Runs the apppriate onload processing for the new image. self.getOnLoadForImage(data.feature, img); // If the example contains appropriately-named features describing // the image width and height then update those feature values for // the new image width and height. const featureMiddle = IMG_FEATURE_REGEX.exec(data.feature)![1] || ''; const widthFeature = 'image' + featureMiddle + '/width'; const heightFeature = 'image' + featureMiddle + '/height'; const widths = self.getFeatureValues(widthFeature, false); const heights = self.getFeatureValues(heightFeature, false); if (widths.length > 0) { widths[0] = +img.width; self.features .get(widthFeature)! .getInt64List()! .setValueList(widths as number[]); } if (heights.length > 0) { heights[0] = +img.height; self.features .get(heightFeature)! .getInt64List()! .setValueList(heights as number[]); } self.exampleChanged(); }); img.src = reader.result; } }, false ); // Read the image file as a data URL. reader.readAsDataURL(files[0]); }, // Add drag-and-drop image replacement behavior to the canvas. addDragDropBehaviorToCanvas: function(canvas: HTMLElement) { const self = this; // Handle drag event for drag-and-drop image replacement. function handleDragOver(event: DragEvent) { event.stopPropagation(); event.preventDefault(); event.dataTransfer.dropEffect = 'copy'; } function handleFileSelect(event: DragEvent) { self.handleFileSelect(event, self); } if (!this.readonly && canvas) { canvas.addEventListener('dragover', handleDragOver, false); canvas.addEventListener('drop', handleFileSelect, false); } }, /** * Returns an onload function for an img element. The function draws the image * to the appropriate canvas element and adds the saliency information to the * canvas if it exists. */ getOnLoadForImage: function( feat: string, image: HTMLImageElement, compare?: boolean ) { const f = (feat: string, image: HTMLImageElement, compare?: boolean) => { const canvas = this.$$( '#' + this.getCanvasId(feat, compare) ) as HTMLCanvasElement; if (!compare) { this.addDragDropBehaviorToCanvas(canvas); } if (image && canvas) { // Draw the image to the canvas and size the canvas. // Set d3.zoom on the canvas to enable zooming and scaling interactions. const context = canvas.getContext('2d')!; let imageScaleFactor = this.imageScalePercentage / 100; // If not using image controls then scale the image to match the // available width in the container, considering padding. if (!this.allowImageControls) { const holder = this.$$('#' + this.getImageCardId(feat, compare)) .parentElement as HTMLElement; let cardWidthForScaling = holder.getBoundingClientRect().width / 2; if (cardWidthForScaling > 16) { cardWidthForScaling -= 16; } if (cardWidthForScaling < image.width) { imageScaleFactor = cardWidthForScaling / image.width; } } canvas.width = image.width * imageScaleFactor; canvas.height = image.height * imageScaleFactor; const transformFn = (transform: d3.ZoomTransform) => { context.save(); context.clearRect(0, 0, canvas.width, canvas.height); context.translate(transform.x, transform.y); context.scale(transform.k, transform.k); this.renderImageOnCanvas( context, canvas.width, canvas.height, feat, compare ); context.restore(); }; const zoom = () => { const transform = d3.event.transform; this.addImageTransform(feat, transform, compare); transformFn(d3.event.transform); }; const d3zoom = d3 .zoom() .scaleExtent(ZOOM_EXTENT) .on('zoom', zoom); d3.select(canvas) .call(d3zoom) .on('dblclick.zoom', () => d3.select(canvas).call(d3zoom.transform, d3.zoomIdentity) ); context.save(); context.scale(imageScaleFactor, imageScaleFactor); context.drawImage(image, 0, 0); context.restore(); this.setImageDatum( context, canvas.width, canvas.height, feat, compare ); this.renderImageOnCanvas( context, canvas.width, canvas.height, feat, compare ); if (compare) { if (this.compareImageInfo[feat].transform) { transformFn(this.compareImageInfo[feat].transform!); } } else { if (this.imageInfo[feat].transform) { transformFn(this.imageInfo[feat].transform!); } } } else { // If the image and canvas are not yet rendered, wait to perform this // processing. requestAnimationFrame(() => f(feat, image, compare)); } }; this.addImageElement(feat, image, compare); this.addImageOnLoad(feat, f, compare); return f.apply(this, [feat, image, compare]); }, addImageOnLoad: function( feat: string, onload: OnloadFunction, compare?: boolean ) { this.hasImage = true; if (compare) { if (!this.compareImageInfo[feat]) { this.compareImageInfo[feat] = {}; } this.compareImageInfo[feat].onload = onload; } else { if (!this.imageInfo[feat]) { this.imageInfo[feat] = {}; } this.imageInfo[feat].onload = onload; } }, addImageData: function( feat: string, imageData: Uint8ClampedArray, compare?: boolean ) { if (compare) { if (!this.compareImageInfo[feat]) { this.compareImageInfo[feat] = {}; } this.compareImageInfo[feat].imageData = imageData; } else { if (!this.imageInfo[feat]) { this.imageInfo[feat] = {}; } this.imageInfo[feat].imageData = imageData; } }, addImageElement: function( feat: string, image: HTMLImageElement, compare?: boolean ) { if (compare) { if (!this.compareImageInfo[feat]) { this.compareImageInfo[feat] = {}; } this.compareImageInfo[feat].imageElement = image; } else { if (!this.imageInfo[feat]) { this.imageInfo[feat] = {}; } this.imageInfo[feat].imageElement = image; } }, addImageGrayscaleData: function( feat: string, imageGrayscaleData: Uint8ClampedArray ) { if (!this.imageInfo[feat]) { this.imageInfo[feat] = {}; } this.imageInfo[feat].imageGrayscaleData = imageGrayscaleData; }, addImageTransform: function( feat: string, transform: d3.ZoomTransform, compare?: boolean ) { if (compare) { if (!this.compareImageInfo[feat]) { this.compareImageInfo[feat] = {}; } this.compareImageInfo[feat].transform = transform; } else { if (!this.imageInfo[feat]) { this.imageInfo[feat] = {}; } this.imageInfo[feat].transform = transform; } }, /** * Saves the Uint8ClampedArray image data for an image feature, both for the * raw image, and for the image with an applied saliency mask if there is * saliency information for the image feature. */ setImageDatum: function( context: CanvasRenderingContext2D, width: number, height: number, feat: string, compare?: boolean ) { if (!width || !height) { return; } const contextData = context.getImageData(0, 0, width, height); const imageData = Uint8ClampedArray.from(contextData.data); this.addImageData(feat, imageData, compare); if ( !this.saliency || !this.showSaliency || !this.saliency[feat] || compare ) { return; } // Grayscale the image for later use with a saliency mask. const salData = Uint8ClampedArray.from(imageData); for (let i = 0; i < imageData.length; i += 4) { // Average pixel color value for grayscaling the pixel. const avg = (imageData[i] + imageData[i + 1] + imageData[i + 2]) / 3; salData[i] = avg; salData[i + 1] = avg; salData[i + 2] = avg; } this.addImageGrayscaleData(feat, salData); }, /** Updates image data pixels based on windowing parameters. */ contrastImage: function( d: Uint8ClampedArray, windowWidth: number, windowCenter: number ) { // See https://www.dabsoft.ch/dicom/3/C.11.2.1.2/ for algorithm description. const contrastScale = d3 .scaleLinear<number>() .domain([ windowCenter - 0.5 - windowWidth / 2, windowCenter - 0.5 + (windowWidth - 1) / 2, ]) .clamp(true) .range([0, 255]); for (let i = 0; i < d.length; i++) { // Skip alpha channel. if (i % 4 !== 3) { d[i] = contrastScale(d[i]); } } }, /** * Returns true if the saliency value provided is higher than the * saliency cutoff, under which saliency values aren't displayed. */ showSaliencyForValue: function(salVal: number) { const salExtremeToCompare = salVal >= 0 ? this.maxSal : this.minSal; return ( Math.abs(salVal) >= (Math.abs(salExtremeToCompare) * this.saliencyCutoff) / 100 ); }, /** Returns the color to display for a given saliency value. */ getColorForSaliency: function(salVal: number) { if (!this.showSaliencyForValue(salVal)) { return noAttributionColor; } else { return this.colors(salVal); } }, /** Adjusts image data pixels to overlay the saliency mask. */ addSaliencyToImage: function( d: Uint8ClampedArray, sal: SaliencyValue | SaliencyValue[] ) { // If provided an array of SaliencyValue then get the correct saliency map // for the currently selected sequence number. if (Array.isArray(sal) && sal.length > 0 && Array.isArray(sal[0])) { sal = sal[this.seqNumber]; } // Grayscale the image and combine the colored pixels based on saliency at // that pixel. This loop examines each pixel, each of which consists of 4 // values (r, g, b, a) in the data array. // Calculate the adjustment factor in order to index into the correct // saliency value for each pixel given that the image may have been scaled, // meaning that the canvas image data array would not have a one-to-one // correspondence with the per-original-image-pixel saliency data. const salScaleAdjustment = 1 / Math.pow(this.imageScalePercentage / 100, 2); for (let i = 0; i < d.length; i += 4) { // Get the saliency value for the pixel. If the saliency map contains only // a single value for the image, use it for all pixels. let salVal = 0; const salIndex = Math.floor((i / 4) * salScaleAdjustment); if (Array.isArray(sal)) { if (sal.length > salIndex) { salVal = sal[salIndex] as number; } else { salVal = 0; } } else { salVal = sal as number; } // Blend the grayscale pixel with the saliency mask color for the pixel // to get the final r, g, b values for the pixel. const ratioToSaliencyExtreme = this.showSaliencyForValue(salVal) ? salVal >= 0 ? this.maxSal === 0 ? 0 : salVal / this.maxSal : salVal / this.minSal : 0; const blendRatio = IMG_SALIENCY_MAX_COLOR_RATIO * ratioToSaliencyExtreme; const {r, g, b} = d3.rgb( salVal > 0 ? this.colors(this.maxSal) : this.colors(this.minSal) ); d[i] = d[i] * (1 - blendRatio) + r * blendRatio; d[i + 1] = d[i + 1] * (1 - blendRatio) + g * blendRatio; d[i + 2] = d[i + 2] * (1 - blendRatio) + b * blendRatio; } }, renderImageOnCanvas: function( context: CanvasRenderingContext2D, width: number, height: number, feat: string, compare?: boolean ) { if (!width || !height) { return; } // Set the correct image data array. const id = context.getImageData(0, 0, width, height); if (compare) { id.data.set(this.compareImageInfo[feat].imageData!); } else { id.data.set( this.saliency && this.showSaliency && this.saliency[feat] ? this.imageInfo[feat].imageGrayscaleData! : this.imageInfo[feat].imageData! ); } // Adjust the contrast and add saliency mask if neccessary. if ( this.windowWidth !== DEFAULT_WINDOW_WIDTH || this.windowCenter !== DEFAULT_WINDOW_CENTER ) { this.contrastImage(id.data, this.windowWidth, this.windowCenter); } if ( !compare && this.saliency && this.showSaliency && this.saliency[feat] ) { this.addSaliencyToImage(id.data, this.saliency[feat]); } // Draw the image data to an in-memory canvas and then draw that to the // on-screen canvas as an image. This allows for the zoom/translate logic // to function correctly. If the image data is directly applied to the // on-screen canvas then the zoom/translate does not apply correctly. const inMemoryCanvas = document.createElement('canvas'); inMemoryCanvas.width = width; inMemoryCanvas.height = height; const inMemoryContext = inMemoryCanvas.getContext('2d')!; inMemoryContext.putImageData(id, 0, 0); context.clearRect(0, 0, width, height); context.drawImage(inMemoryCanvas, 0, 0); }, showSalCheckboxChange: function() { this.showSaliency = this.$.salCheckbox.checked; }, /** * If any image settings changes then call onload for each image to redraw the * image on the canvas. */ updateImages: function() { for (const feat in this.imageInfo) { if (this.imageInfo.hasOwnProperty(feat)) { this.imageInfo[feat].onload!( feat, this.imageInfo[feat].imageElement! ); } } }, shouldShowImageControls: function( hasImage: boolean, allowImageControls: boolean ) { return hasImage && allowImageControls; }, /** * Only enable the add feature button when a name has been specified. */ shouldEnableAddFeature: function(featureName: string) { return featureName.length > 0; }, getDeleteValueButtonClass: function( readonly: boolean, showDeleteValueButton: boolean ) { return readonly || !showDeleteValueButton ? 'delete-value-button delete-value-button-hidden' : 'delete-value-button'; }, getDeleteFeatureButtonClass: function(readonly: boolean) { return readonly ? 'hide-controls' : 'delete-feature-button'; }, getAddValueButtonClass: function(readonly: boolean) { return readonly ? 'hide-controls' : 'add-value-button'; }, getAddFeatureButtonClass: function(readonly: boolean) { return readonly ? 'hide-controls' : 'add-feature-button'; }, getUploadImageClass: function(readonly: boolean) { return readonly ? 'hide-controls' : 'upload-image-button'; }, getCompareHeaderClass: function(highlightDifferences: boolean) { return highlightDifferences ? 'compare-value-text' : 'no-compare-value-text'; }, /** * Decodes a list of bytes into a readable string, treating the bytes as * unicode char codes. */ decodeBytesListToString: function(bytes: Uint8Array) { // Decode strings in 16K chunks to avoid stack error with use of // fromCharCode.apply. const decodeChunkBytes = 16 * 1024; let res = ''; let i = 0; // Decode in chunks to avoid stack error with use of fromCharCode.apply. for (i = 0; i < bytes.length / decodeChunkBytes; i++) { res += String.fromCharCode.apply( null, bytes.slice(i * decodeChunkBytes, (i + 1) * decodeChunkBytes) ); } res += String.fromCharCode.apply(null, bytes.slice(i * decodeChunkBytes)); return res; }, }); }
the_stack
import { expect, preferencesTestSet, loadBackground, nextTick, Background, } from './setup'; preferencesTestSet.map(preferences => { describe(`preferences: ${JSON.stringify(preferences)}`, () => { describe('addons that do redirects in automatic mode', () => { if (!preferences.automaticMode.active) { return; } let bg: Background; beforeEach(async () => { bg = await loadBackground({ preferences }); }); describe('https everywhere', () => { it('should not open two tabs if redirects happen', async () => { // we get a http request, cancel it and create a new tab with id 2 (the http version) // but https everywhere saw it and redirects the request instantly // we see the new request, cancel that and create a new tab 3 (the https version) bg.helper.request({ requestId: 1, tabId: 1, createsTabId: 2, createsContainer: 'firefox-tmp1', url: 'http://example.com', }); await bg.helper.request({ requestId: 1, tabId: 1, createsTabId: 3, createsContainer: 'firefox-tmp2', url: 'https://example.com', }); await nextTick(); bg.browser.tabs.remove.should.have.been.calledOnce; bg.browser.tabs.remove.should.have.been.calledWith(1); bg.browser.tabs.create.should.have.been.calledOnce; }); describe('opening new tmptab and left clicking link with global always setting', () => { beforeEach(async () => { bg.tmp.storage.local.preferences.isolation.global.mouseClick.left.action = 'always'; await bg.helper.openNewTmpTab({ tabId: 1, createsTabId: 2, }); await bg.helper.mouseClickOnLink({ senderUrl: 'http://example.com', targetUrl: 'http://notexample.com', }); await nextTick(); }); it('should not keep loading the link in the same tab if redirects happen', async () => { const initialClickRequestPromise = bg.helper.request({ requestId: 1, tabId: 1, createsTabId: 2, createsContainer: 'firefox-tmp1', url: 'http://notexample.com', }); const redirectRequest = await bg.helper.request({ requestId: 1, tabId: 1, createsTabId: 3, createsContainer: 'firefox-tmp2', url: 'https://notexample.com', resetHistory: true, }); await nextTick(); expect(redirectRequest).to.deep.equal({ cancel: true }); bg.browser.contextualIdentities.create.should.have.been.calledOnce; bg.browser.tabs.create.should.have.been.calledOnce; bg.browser.tabs.remove.should.not.have.been.called; const initialClickRequest = await initialClickRequestPromise; expect(initialClickRequest).to.deep.equal({ cancel: true }); }); it('should not keep loading the link in the same tab if redirects happen even when in temporary container', async () => { const initialClickRequestPromise = bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-tmp123', createsTabId: 2, createsContainer: 'firefox-tmp1', url: 'http://notexample.com', }); const redirectRequest = await bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-tmp123', createsTabId: 3, createsContainer: 'firefox-tmp2', url: 'https://notexample.com', resetHistory: true, }); await nextTick(); expect(redirectRequest).to.deep.equal({ cancel: true }); bg.browser.contextualIdentities.create.should.have.been.calledOnce; bg.browser.tabs.create.should.have.been.calledOnce; bg.browser.tabs.remove.should.not.have.been.called; const initialClickRequest = await initialClickRequestPromise; expect(initialClickRequest).to.deep.equal({ cancel: true }); }); }); }); describe('link cleaner', () => { describe('opening new tmptab and left clicking link with global always setting', () => { beforeEach(async () => { bg.tmp.storage.local.preferences.isolation.global.mouseClick.left.action = 'always'; await bg.helper.openNewTmpTab({ tabId: 1, createsTabId: 2, }); await bg.helper.mouseClickOnLink({ senderUrl: 'http://example.com', targetUrl: 'http://notexample.com', }); await nextTick(); }); it('should not keep loading the link in the same tab if redirects happen', async () => { const initialClickRequestPromise = bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-tmp123', createsTabId: 2, createsContainer: 'firefox-tmp1', url: 'http://notexample.com', }); const redirectRequest = await bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-tmp123', createsTabId: 3, createsContainer: 'firefox-tmp2', url: 'https://somethingcompletelydifferent.com', resetHistory: true, }); await nextTick(); expect(redirectRequest).to.deep.equal({ cancel: true }); bg.browser.contextualIdentities.create.should.have.been.calledOnce; bg.browser.tabs.create.should.have.been.calledOnce; bg.browser.tabs.remove.should.not.have.been.called; const initialClickRequest = await initialClickRequestPromise; expect(initialClickRequest).to.deep.equal({ cancel: true }); }); }); }); }); describe('native firefox redirects with global left click always setting', () => { let bg: Background; beforeEach(async () => { bg = await loadBackground({ preferences }); }); describe('opening new tmptab and left clicking link with global always setting', () => { beforeEach(async () => { bg.tmp.storage.local.preferences.isolation.global.mouseClick.left.action = 'always'; await bg.helper.openNewTmpTab({ tabId: 1, createsTabId: 2, }); await bg.helper.mouseClickOnLink({ senderUrl: 'http://example.com', targetUrl: 'https://notexample.com', }); await nextTick(); }); it('should not open two tabs even when requestId changes midflight', async () => { // https://bugzilla.mozilla.org/show_bug.cgi?id=1437748 const request1 = bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-default', createsTabId: 2, createsContainer: 'firefox-tmp1', url: 'https://notexample.com', resetHistory: true, }); const request2 = bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-default', createsTabId: 2, createsContainer: 'firefox-tmp1', url: 'https://www.notexample.com', }); const request3 = bg.helper.request({ requestId: 2, tabId: 1, originContainer: 'firefox-default', createsTabId: 3, createsContainer: 'firefox-tmp2', url: 'https://www.notexample.com', }); await nextTick(); bg.browser.tabs.create.should.have.been.calledOnce; bg.browser.contextualIdentities.create.should.have.been.calledOnce; bg.browser.tabs.remove.should.not.have.been.called; expect(await request1).to.deep.equal({ cancel: true }); expect(await request2).to.deep.equal({ cancel: true }); expect(await request3).to.deep.equal({ cancel: true }); }); }); }); describe('native firefox redirects with global left click never setting', () => { let bg: Background; beforeEach(async () => { bg = await loadBackground({ preferences }); }); describe('opening new tmptab and left clicking link', () => { beforeEach(async () => { bg.tmp.storage.local.preferences.isolation.global.mouseClick.left.action = 'never'; await bg.helper.openNewTmpTab({ tabId: 1, createsTabId: 2, }); await bg.helper.mouseClickOnLink({ senderUrl: 'http://example.com', targetUrl: 'http://notexample.com', }); await nextTick(); }); it('should not cancel the requests and redirects', async () => { const request1 = await bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-tmp123', url: 'http://notexample.com', resetHistory: true, }); const request2 = await bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-tmp123', url: 'https://notexample.com', }); const request3 = await bg.helper.request({ requestId: 1, tabId: 1, originContainer: 'firefox-tmp123', url: 'https://reallynotexample.com', }); expect(request1).to.be.undefined; expect(request2).to.be.undefined; expect(request3).to.be.undefined; bg.browser.tabs.create.should.not.have.been.calledOnce; bg.browser.contextualIdentities.create.should.not.have.been .calledOnce; bg.browser.tabs.remove.should.not.have.been.called; }); }); }); }); });
the_stack
import * as Fs from 'fs' import * as Path from 'path' import { Emitter, Disposable } from 'event-kit' import { Repository } from '../../models/repository' import { WorkingDirectoryFileChange, AppFileStatus } from '../../models/status' import { Branch, BranchType } from '../../models/branch' import { Tip, TipState } from '../../models/tip' import { Commit } from '../../models/commit' import { IRemote } from '../../models/remote' import { IFetchProgress } from '../app-state' import { IAppShell } from '../app-shell' import { ErrorWithMetadata, IErrorMetadata } from '../error-with-metadata' import { structuralEquals } from '../../lib/equality' import { compare } from '../../lib/compare' import { queueWorkHigh } from '../../lib/queue-work' import { reset, GitResetMode, getDefaultRemote, getRemotes, fetch as fetchRepo, fetchRefspec, getRecentBranches, getBranches, deleteRef, IAheadBehind, getBranchAheadBehind, getCommits, merge, setRemoteURL, getStatus, IStatusResult, getCommit, IndexStatus, getIndexChanges, checkoutIndex, checkoutPaths, resetPaths, getConfigValue, revertCommit, unstageAllFiles, openMergeTool, } from '../git' import { IGitAccount } from '../git/authentication' import { RetryAction, RetryActionType } from '../retry-actions' /** The number of commits to load from history per batch. */ const CommitBatchSize = 100 const LoadingHistoryRequestKey = 'history' /** The max number of recent branches to find. */ const RecentBranchesLimit = 5 /** A commit message summary and description. */ export interface ICommitMessage { readonly summary: string readonly description: string | null } /** The store for a repository's git data. */ export class GitStore { private readonly emitter = new Emitter() private readonly shell: IAppShell /** The commits keyed by their SHA. */ public readonly commits = new Map<string, Commit>() private _history: ReadonlyArray<string> = new Array() private readonly requestsInFight = new Set<string>() private readonly repository: Repository private _tip: Tip = { kind: TipState.Unknown } private _defaultBranch: Branch | null = null private _allBranches: ReadonlyArray<Branch> = [] private _recentBranches: ReadonlyArray<Branch> = [] private _localCommitSHAs: ReadonlyArray<string> = [] private _commitMessage: ICommitMessage | null private _contextualCommitMessage: ICommitMessage | null private _aheadBehind: IAheadBehind | null = null private _remote: IRemote | null = null private _lastFetched: Date | null = null public constructor(repository: Repository, shell: IAppShell) { this.repository = repository this.shell = shell } private emitUpdate() { this.emitter.emit('did-update', {}) } private emitNewCommitsLoaded(commits: ReadonlyArray<Commit>) { this.emitter.emit('did-load-new-commits', commits) } private emitError(error: Error) { this.emitter.emit('did-error', error) } /** Register a function to be called when the store updates. */ public onDidUpdate(fn: () => void): Disposable { return this.emitter.on('did-update', fn) } /** Register a function to be called when the store loads new commits. */ public onDidLoadNewCommits( fn: (commits: ReadonlyArray<Commit>) => void ): Disposable { return this.emitter.on('did-load-new-commits', fn) } /** Register a function to be called when an error occurs. */ public onDidError(fn: (error: Error) => void): Disposable { return this.emitter.on('did-error', fn) } /** Load history from HEAD. */ public async loadHistory() { if (this.requestsInFight.has(LoadingHistoryRequestKey)) { return } this.requestsInFight.add(LoadingHistoryRequestKey) let commits = await this.performFailableOperation(() => getCommits(this.repository, 'HEAD', CommitBatchSize) ) if (!commits) { return } let existingHistory = this._history if (existingHistory.length > 0) { const mostRecent = existingHistory[0] const index = commits.findIndex(c => c.sha === mostRecent) // If we found the old HEAD, then we can just splice the new commits into // the history we already loaded. // // But if we didn't, it means the history we had and the history we just // loaded have diverged significantly or in some non-trivial way // (e.g., HEAD reset). So just throw it out and we'll start over fresh. if (index > -1) { commits = commits.slice(0, index) } else { existingHistory = [] } } this._history = [...commits.map(c => c.sha), ...existingHistory] this.storeCommits(commits) this.requestsInFight.delete(LoadingHistoryRequestKey) this.emitNewCommitsLoaded(commits) this.emitUpdate() } /** Load the next batch of history, starting from the last loaded commit. */ public async loadNextHistoryBatch() { if (this.requestsInFight.has(LoadingHistoryRequestKey)) { return } if (!this.history.length) { return } const lastSHA = this.history[this.history.length - 1] const requestKey = `history/${lastSHA}` if (this.requestsInFight.has(requestKey)) { return } this.requestsInFight.add(requestKey) const commits = await this.performFailableOperation(() => getCommits(this.repository, `${lastSHA}^`, CommitBatchSize) ) if (!commits) { return } this._history = this._history.concat(commits.map(c => c.sha)) this.storeCommits(commits) this.requestsInFight.delete(requestKey) this.emitNewCommitsLoaded(commits) this.emitUpdate() } /** The list of ordered SHAs. */ public get history(): ReadonlyArray<string> { return this._history } /** Load all the branches. */ public async loadBranches() { const [localAndRemoteBranches, recentBranchNames] = await Promise.all([ this.performFailableOperation(() => getBranches(this.repository)) || [], this.performFailableOperation(() => getRecentBranches(this.repository, RecentBranchesLimit) ), ]) if (!localAndRemoteBranches) { return } this._allBranches = this.mergeRemoteAndLocalBranches(localAndRemoteBranches) this.refreshDefaultBranch() this.refreshRecentBranches(recentBranchNames) const commits = this._allBranches.map(b => b.tip) for (const commit of commits) { this.commits.set(commit.sha, commit) } this.emitNewCommitsLoaded(commits) this.emitUpdate() } /** * Takes a list of local and remote branches and filters out "duplicate" * remote branches, i.e. remote branches that we already have a local * branch tracking. */ private mergeRemoteAndLocalBranches( branches: ReadonlyArray<Branch> ): ReadonlyArray<Branch> { const localBranches = new Array<Branch>() const remoteBranches = new Array<Branch>() for (const branch of branches) { if (branch.type === BranchType.Local) { localBranches.push(branch) } else if (branch.type === BranchType.Remote) { remoteBranches.push(branch) } } const upstreamBranchesAdded = new Set<string>() const allBranchesWithUpstream = new Array<Branch>() for (const branch of localBranches) { allBranchesWithUpstream.push(branch) if (branch.upstream) { upstreamBranchesAdded.add(branch.upstream) } } for (const branch of remoteBranches) { // This means we already added the local branch of this remote branch, so // we don't need to add it again. if (upstreamBranchesAdded.has(branch.name)) { continue } allBranchesWithUpstream.push(branch) } return allBranchesWithUpstream } private refreshDefaultBranch() { let defaultBranchName: string | null = 'master' const gitHubRepository = this.repository.gitHubRepository if (gitHubRepository && gitHubRepository.defaultBranch) { defaultBranchName = gitHubRepository.defaultBranch } if (defaultBranchName) { // Find the default branch among all of our branches, giving // priority to local branches by sorting them before remotes this._defaultBranch = this._allBranches .filter(b => b.name === defaultBranchName) .sort((x, y) => compare(x.type, y.type)) .shift() || null } else { this._defaultBranch = null } } private refreshRecentBranches( recentBranchNames: ReadonlyArray<string> | undefined ) { if (!recentBranchNames || !recentBranchNames.length) { this._recentBranches = [] return } const branchesByName = this._allBranches.reduce( (map, branch) => map.set(branch.name, branch), new Map<string, Branch>() ) const recentBranches = new Array<Branch>() for (const name of recentBranchNames) { const branch = branchesByName.get(name) if (!branch) { // This means the recent branch has been deleted. That's fine. continue } recentBranches.push(branch) } this._recentBranches = recentBranches } /** The current branch. */ public get tip(): Tip { return this._tip } /** The default branch, or `master` if there is no default. */ public get defaultBranch(): Branch | null { return this._defaultBranch } /** All branches, including the current branch and the default branch. */ public get allBranches(): ReadonlyArray<Branch> { return this._allBranches } /** The most recently checked out branches. */ public get recentBranches(): ReadonlyArray<Branch> { return this._recentBranches } /** * Load local commits into memory for the current repository. * * @param branch The branch to query for unpublished commits. * * If the tip of the repository does not have commits (i.e. is unborn), this * should be invoked with `null`, which clears any existing commits from the * store. */ public async loadLocalCommits(branch: Branch | null): Promise<void> { if (branch === null) { this._localCommitSHAs = [] return } let localCommits: ReadonlyArray<Commit> | undefined if (branch.upstream) { const revRange = `${branch.upstream}..${branch.name}` localCommits = await this.performFailableOperation(() => getCommits(this.repository, revRange, CommitBatchSize) ) } else { localCommits = await this.performFailableOperation(() => getCommits(this.repository, 'HEAD', CommitBatchSize, [ '--not', '--remotes', ]) ) } if (!localCommits) { return } this.storeCommits(localCommits) this._localCommitSHAs = localCommits.map(c => c.sha) this.emitUpdate() } /** * The ordered array of local commit SHAs. The commits themselves can be * looked up in `commits`. */ public get localCommitSHAs(): ReadonlyArray<string> { return this._localCommitSHAs } /** Store the given commits. */ private storeCommits(commits: ReadonlyArray<Commit>) { for (const commit of commits) { this.commits.set(commit.sha, commit) } } private async undoFirstCommit( repository: Repository ): Promise<true | undefined> { // What are we doing here? // The state of the working directory here is rather important, because we // want to ensure that any deleted files are restored to your working // directory for the next stage. Doing doing a `git checkout -- .` here // isn't suitable because we should preserve the other working directory // changes. const status = await getStatus(repository) const paths = status.workingDirectory.files const deletedFiles = paths.filter(p => p.status === AppFileStatus.Deleted) const deletedFilePaths = deletedFiles.map(d => d.path) await checkoutPaths(repository, deletedFilePaths) // Now that we have the working directory changes, as well the restored // deleted files, we can remove the HEAD ref to make the current branch // disappear await deleteRef(repository, 'HEAD', 'Reverting first commit') // Finally, ensure any changes in the index are unstaged. This ensures all // files in the repository will be untracked. await unstageAllFiles(repository) return true } /** * Undo a specific commit for the current repository. * * @param commit - The commit to remove - should be the tip of the current branch. */ public async undoCommit(commit: Commit): Promise<void> { // For an initial commit, just delete the reference but leave HEAD. This // will make the branch unborn again. let success: true | undefined = undefined if (commit.parentSHAs.length === 0) { success = await this.performFailableOperation(() => this.undoFirstCommit(this.repository) ) } else { success = await this.performFailableOperation(() => reset(this.repository, GitResetMode.Mixed, commit.parentSHAs[0]) ) } if (success) { this._contextualCommitMessage = { summary: commit.summary, description: commit.body, } } this.emitUpdate() } /** * Perform an operation that may fail by throwing an error. If an error is * thrown, catch it and emit it, and return `undefined`. * * @param errorMetadata - The metadata which should be attached to any errors * that are thrown. */ public async performFailableOperation<T>( fn: () => Promise<T>, errorMetadata?: IErrorMetadata ): Promise<T | undefined> { try { const result = await fn() return result } catch (e) { e = new ErrorWithMetadata(e, { repository: this.repository, ...errorMetadata, }) this.emitError(e) return undefined } } /** The commit message for a work-in-progress commit in the changes view. */ public get commitMessage(): ICommitMessage | null { return this._commitMessage } /** * The commit message to use based on the contex of the repository, e.g., the * message from a recently undone commit. */ public get contextualCommitMessage(): ICommitMessage | null { return this._contextualCommitMessage } /** * Fetch the default remote, using the given account for authentication. * * @param account - The account to use for authentication if needed. * @param backgroundTask - Was the fetch done as part of a background task? * @param progressCallback - A function that's called with information about * the overall fetch progress. */ public async fetch( account: IGitAccount | null, backgroundTask: boolean, progressCallback?: (fetchProgress: IFetchProgress) => void ): Promise<void> { const remote = this.remote if (!remote) { return Promise.resolve() } return this.fetchRemotes( account, [remote], backgroundTask, progressCallback ) } /** * Fetch the specified remotes, using the given account for authentication. * * @param account - The account to use for authentication if needed. * @param remotes - The remotes to fetch from. * @param backgroundTask - Was the fetch done as part of a background task? * @param progressCallback - A function that's called with information about * the overall fetch progress. */ public async fetchRemotes( account: IGitAccount | null, remotes: ReadonlyArray<IRemote>, backgroundTask: boolean, progressCallback?: (fetchProgress: IFetchProgress) => void ): Promise<void> { if (!remotes.length) { return } const weight = 1 / remotes.length for (let i = 0; i < remotes.length; i++) { const remote = remotes[i] const startProgressValue = i * weight await this.fetchRemote(account, remote.name, backgroundTask, progress => { if (progress && progressCallback) { progressCallback({ ...progress, value: startProgressValue + progress.value * weight, }) } }) } } /** * Fetch a remote, using the given account for authentication. * * @param account - The account to use for authentication if needed. * @param remote - The name of the remote to fetch from. * @param backgroundTask - Was the fetch done as part of a background task? * @param progressCallback - A function that's called with information about * the overall fetch progress. */ public async fetchRemote( account: IGitAccount | null, remote: string, backgroundTask: boolean, progressCallback?: (fetchProgress: IFetchProgress) => void ): Promise<void> { const retryAction: RetryAction = { type: RetryActionType.Fetch, repository: this.repository, } await this.performFailableOperation( () => { return fetchRepo(this.repository, account, remote, progressCallback) }, { backgroundTask, retryAction } ) } /** * Fetch a given refspec, using the given account for authentication. * * @param user - The user to use for authentication if needed. * @param refspec - The association between a remote and local ref to use as * part of this action. Refer to git-scm for more * information on refspecs: https://www.git-scm.com/book/tr/v2/Git-Internals-The-Refspec * */ public async fetchRefspec( account: IGitAccount | null, refspec: string ): Promise<void> { // TODO: we should favour origin here const remotes = await getRemotes(this.repository) for (const remote of remotes) { await this.performFailableOperation(() => fetchRefspec(this.repository, account, remote.name, refspec) ) } } /** Calculate the ahead/behind for the current branch. */ public async calculateAheadBehindForCurrentBranch(): Promise<void> { if (this.tip.kind === TipState.Valid) { const branch = this.tip.branch this._aheadBehind = await getBranchAheadBehind(this.repository, branch) } this.emitUpdate() } public async loadStatus(): Promise<IStatusResult | null> { const status = await this.performFailableOperation(() => getStatus(this.repository) ) if (!status) { return null } this._aheadBehind = status.branchAheadBehind || null const { currentBranch, currentTip } = status if (currentBranch || currentTip) { if (currentTip && currentBranch) { const cachedCommit = this.commits.get(currentTip) const branchTipCommit = cachedCommit || (await this.performFailableOperation(() => getCommit(this.repository, currentTip) )) if (!branchTipCommit) { throw new Error(`Could not load commit ${currentTip}`) } const branch = new Branch( currentBranch, status.currentUpstreamBranch || null, branchTipCommit, BranchType.Local ) this._tip = { kind: TipState.Valid, branch } } else if (currentTip) { this._tip = { kind: TipState.Detached, currentSha: currentTip } } else if (currentBranch) { this._tip = { kind: TipState.Unborn, ref: currentBranch } } } else { this._tip = { kind: TipState.Unknown } } this.emitUpdate() return status } /** * Load the remote for the current branch, or the default remote if no * tracking information found. */ public async loadCurrentRemote(): Promise<void> { const tip = this.tip if (tip.kind === TipState.Valid) { const branch = tip.branch if (branch.remote) { const allRemotes = await getRemotes(this.repository) const foundRemote = allRemotes.find(r => r.name === branch.remote) if (foundRemote) { this._remote = foundRemote } } } if (!this._remote) { this._remote = await getDefaultRemote(this.repository) } this.emitUpdate() } /** * The number of commits the current branch is ahead and behind, relative to * its upstream. * * It will be `null` if ahead/behind hasn't been calculated yet, or if the * branch doesn't have an upstream. */ public get aheadBehind(): IAheadBehind | null { return this._aheadBehind } /** Get the remote we're working with. */ public get remote(): IRemote | null { return this._remote } public setCommitMessage(message: ICommitMessage | null): Promise<void> { this._commitMessage = message this.emitUpdate() return Promise.resolve() } /** The date the repository was last fetched. */ public get lastFetched(): Date | null { return this._lastFetched } /** Update the last fetched date. */ public updateLastFetched(): Promise<void> { const path = Path.join(this.repository.path, '.git', 'FETCH_HEAD') return new Promise<void>((resolve, reject) => { Fs.stat(path, (err, stats) => { if (err) { // An error most likely means the repository's never been published. this._lastFetched = null } else if (stats.size > 0) { // If the file's empty then it _probably_ means the fetch failed and we // shouldn't update the last fetched date. this._lastFetched = stats.mtime } resolve() this.emitUpdate() }) }) } /** Merge the named branch into the current branch. */ public merge(branch: string): Promise<void> { return this.performFailableOperation(() => merge(this.repository, branch)) } /** Changes the URL for the remote that matches the given name */ public async setRemoteURL(name: string, url: string): Promise<void> { await this.performFailableOperation(() => setRemoteURL(this.repository, name, url) ) await this.loadCurrentRemote() this.emitUpdate() } /** * Read the contents of the repository .gitignore. * * Returns a promise which will either be rejected or resolved * with the contents of the file. If there's no .gitignore file * in the repository root the promise will resolve with null. */ public async readGitIgnore(): Promise<string | null> { const repository = this.repository const ignorePath = Path.join(repository.path, '.gitignore') return new Promise<string | null>((resolve, reject) => { Fs.readFile(ignorePath, 'utf8', (err, data) => { if (err) { if (err.code === 'ENOENT') { resolve(null) } else { reject(err) } } else { resolve(data) } }) }) } /** * Persist the given content to the repository root .gitignore. * * If the repository root doesn't contain a .gitignore file one * will be created, otherwise the current file will be overwritten. */ public async saveGitIgnore(text: string): Promise<void> { const repository = this.repository const ignorePath = Path.join(repository.path, '.gitignore') const fileContents = await formatGitIgnoreContents(text, repository) return new Promise<void>((resolve, reject) => { Fs.writeFile(ignorePath, fileContents, err => { if (err) { reject(err) } else { resolve() } }) }) } /** Ignore the given path or pattern. */ public async ignore(pattern: string): Promise<void> { const text = (await this.readGitIgnore()) || '' const repository = this.repository const currentContents = await formatGitIgnoreContents(text, repository) const newText = await formatGitIgnoreContents( `${currentContents}${pattern}`, repository ) await this.saveGitIgnore(newText) } public async discardChanges( files: ReadonlyArray<WorkingDirectoryFileChange> ): Promise<void> { const pathsToCheckout = new Array<string>() const pathsToReset = new Array<string>() await queueWorkHigh(files, async file => { if (file.status !== AppFileStatus.Deleted) { // N.B. moveItemToTrash is synchronous can take a fair bit of time // which is why we're running it inside this work queue that spreads // out the calls across as many animation frames as it needs to. this.shell.moveItemToTrash( Path.resolve(this.repository.path, file.path) ) } if ( file.status === AppFileStatus.Copied || file.status === AppFileStatus.Renamed ) { // file.path is the "destination" or "new" file in a copy or rename. // we've already deleted it so all we need to do is make sure the // index forgets about it. pathsToReset.push(file.path) // Checkout the old path though if (file.oldPath) { pathsToCheckout.push(file.oldPath) pathsToReset.push(file.oldPath) } } else { pathsToCheckout.push(file.path) pathsToReset.push(file.path) } }) // Check the index to see which files actually have changes there as compared to HEAD const changedFilesInIndex = await getIndexChanges(this.repository) // Only reset paths if they have changes in the index const necessaryPathsToReset = pathsToReset.filter(x => changedFilesInIndex.has(x) ) // Don't attempt to checkout files that doesn't exist in the index after our reset. const necessaryPathsToCheckout = pathsToCheckout.filter( x => changedFilesInIndex.get(x) !== IndexStatus.Added ) // We're trying to not invoke git linearly with the number of files to discard // so we're doing our discards in three conceptual steps. // // 1. Figure out what the index thinks has changed as compared to the previous // commit. For users who exclusive interact with Git using Desktop this will // almost always empty which, as it turns out, is great for us. // // 2. Figure out if any of the files that we've been asked to discard are changed // in the index and if so, reset them such that the index is set up just as // the previous commit for the paths we're discarding. // // 3. Checkout all the files that we've discarded that existed in the previous // commit from the index. await this.performFailableOperation(async () => { await resetPaths( this.repository, GitResetMode.Mixed, 'HEAD', necessaryPathsToReset ) await checkoutIndex(this.repository, necessaryPathsToCheckout) }) } /** Load the contextual commit message if there is one. */ public async loadContextualCommitMessage(): Promise<void> { const message = await this.getMergeMessage() const existingMessage = this._contextualCommitMessage // In the case where we're in the middle of a merge, we're gonna keep // finding the same merge message over and over. We don't need to keep // telling the world. if ( existingMessage && message && structuralEquals(existingMessage, message) ) { return } this._contextualCommitMessage = message this.emitUpdate() } /** Reverts the commit with the given SHA */ public async revertCommit( repository: Repository, commit: Commit ): Promise<void> { await this.performFailableOperation(() => revertCommit(repository, commit)) this.emitUpdate() } /** * Get the merge message in the repository. This will resolve to null if the * repository isn't in the middle of a merge. */ private async getMergeMessage(): Promise<ICommitMessage | null> { const messagePath = Path.join(this.repository.path, '.git', 'MERGE_MSG') return new Promise<ICommitMessage | null>((resolve, reject) => { Fs.readFile(messagePath, 'utf8', (err, data) => { if (err || !data.length) { resolve(null) } else { const pieces = data.match(/(.*)\n\n([\S\s]*)/m) if (!pieces || pieces.length < 3) { resolve(null) return } // exclude any commented-out lines from the MERGE_MSG body let description: string | null = pieces[2] .split('\n') .filter(line => line[0] !== '#') .join('\n') // join with no elements will return an empty string if (description.length === 0) { description = null } resolve({ summary: pieces[1], description, }) } }) }) } public async openMergeTool(path: string): Promise<void> { await this.performFailableOperation(() => openMergeTool(this.repository, path) ) } } /** * Format the gitignore text based on the current config settings. * * This setting looks at core.autocrlf to decide which line endings to use * when updating the .gitignore file. * * If core.safecrlf is also set, adding this file to the index may cause * Git to return a non-zero exit code, leaving the working directory in a * confusing state for the user. So we should reformat the file in that * case. * * @param text The text to format. * @param repository The repository associated with the gitignore file. */ async function formatGitIgnoreContents( text: string, repository: Repository ): Promise<string> { const autocrlf = await getConfigValue(repository, 'core.autocrlf') const safecrlf = await getConfigValue(repository, 'core.safecrlf') return new Promise<string>((resolve, reject) => { if (autocrlf === 'true' && safecrlf === 'true') { // based off https://stackoverflow.com/a/141069/1363815 const normalizedText = text.replace(/\r\n|\n\r|\n|\r/g, '\r\n') resolve(normalizedText) return } if (text.endsWith('\n')) { resolve(text) return } const linesEndInCRLF = autocrlf === 'true' if (linesEndInCRLF) { resolve(`${text}\n`) } else { resolve(`${text}\r\n`) } }) }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/modelMappers"; import * as Parameters from "../models/parameters"; import { LuisAuthoringContext } from "../luisAuthoringContext"; /** Class representing a Model. */ export class Model { private readonly client: LuisAuthoringContext; /** * Create a Model. * @param {LuisAuthoringContext} client Reference to the service client. */ constructor(client: LuisAuthoringContext) { this.client = client; } /** * Adds an intent to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param intentCreateObject A model object containing the name of the new intent. * @param [options] The optional parameters * @returns Promise<Models.ModelAddIntentResponse> */ addIntent(appId: string, versionId: string, intentCreateObject: Models.ModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddIntentResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param intentCreateObject A model object containing the name of the new intent. * @param callback The callback */ addIntent(appId: string, versionId: string, intentCreateObject: Models.ModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param intentCreateObject A model object containing the name of the new intent. * @param options The optional parameters * @param callback The callback */ addIntent(appId: string, versionId: string, intentCreateObject: Models.ModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addIntent(appId: string, versionId: string, intentCreateObject: Models.ModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddIntentResponse> { return this.client.sendOperationRequest( { appId, versionId, intentCreateObject, options }, addIntentOperationSpec, callback) as Promise<Models.ModelAddIntentResponse>; } /** * Gets information about the intent models in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListIntentsResponse> */ listIntents(appId: string, versionId: string, options?: Models.ModelListIntentsOptionalParams): Promise<Models.ModelListIntentsResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listIntents(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.IntentClassifier[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listIntents(appId: string, versionId: string, options: Models.ModelListIntentsOptionalParams, callback: msRest.ServiceCallback<Models.IntentClassifier[]>): void; listIntents(appId: string, versionId: string, options?: Models.ModelListIntentsOptionalParams | msRest.ServiceCallback<Models.IntentClassifier[]>, callback?: msRest.ServiceCallback<Models.IntentClassifier[]>): Promise<Models.ModelListIntentsResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listIntentsOperationSpec, callback) as Promise<Models.ModelListIntentsResponse>; } /** * Adds a simple entity extractor to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param modelCreateObject A model object containing the name for the new simple entity extractor. * @param [options] The optional parameters * @returns Promise<Models.ModelAddEntityResponse> */ addEntity(appId: string, versionId: string, modelCreateObject: Models.ModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param modelCreateObject A model object containing the name for the new simple entity extractor. * @param callback The callback */ addEntity(appId: string, versionId: string, modelCreateObject: Models.ModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param modelCreateObject A model object containing the name for the new simple entity extractor. * @param options The optional parameters * @param callback The callback */ addEntity(appId: string, versionId: string, modelCreateObject: Models.ModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addEntity(appId: string, versionId: string, modelCreateObject: Models.ModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, modelCreateObject, options }, addEntityOperationSpec, callback) as Promise<Models.ModelAddEntityResponse>; } /** * Gets information about all the simple entity models in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListEntitiesResponse> */ listEntities(appId: string, versionId: string, options?: Models.ModelListEntitiesOptionalParams): Promise<Models.ModelListEntitiesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listEntities(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.EntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listEntities(appId: string, versionId: string, options: Models.ModelListEntitiesOptionalParams, callback: msRest.ServiceCallback<Models.EntityExtractor[]>): void; listEntities(appId: string, versionId: string, options?: Models.ModelListEntitiesOptionalParams | msRest.ServiceCallback<Models.EntityExtractor[]>, callback?: msRest.ServiceCallback<Models.EntityExtractor[]>): Promise<Models.ModelListEntitiesResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listEntitiesOperationSpec, callback) as Promise<Models.ModelListEntitiesResponse>; } /** * Adds a hierarchical entity extractor to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hierarchicalModelCreateObject A model containing the name and children of the new entity * extractor. * @param [options] The optional parameters * @returns Promise<Models.ModelAddHierarchicalEntityResponse> */ addHierarchicalEntity(appId: string, versionId: string, hierarchicalModelCreateObject: Models.HierarchicalEntityModel, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddHierarchicalEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hierarchicalModelCreateObject A model containing the name and children of the new entity * extractor. * @param callback The callback */ addHierarchicalEntity(appId: string, versionId: string, hierarchicalModelCreateObject: Models.HierarchicalEntityModel, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hierarchicalModelCreateObject A model containing the name and children of the new entity * extractor. * @param options The optional parameters * @param callback The callback */ addHierarchicalEntity(appId: string, versionId: string, hierarchicalModelCreateObject: Models.HierarchicalEntityModel, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addHierarchicalEntity(appId: string, versionId: string, hierarchicalModelCreateObject: Models.HierarchicalEntityModel, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddHierarchicalEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, hierarchicalModelCreateObject, options }, addHierarchicalEntityOperationSpec, callback) as Promise<Models.ModelAddHierarchicalEntityResponse>; } /** * Gets information about all the hierarchical entity models in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListHierarchicalEntitiesResponse> */ listHierarchicalEntities(appId: string, versionId: string, options?: Models.ModelListHierarchicalEntitiesOptionalParams): Promise<Models.ModelListHierarchicalEntitiesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listHierarchicalEntities(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.HierarchicalEntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listHierarchicalEntities(appId: string, versionId: string, options: Models.ModelListHierarchicalEntitiesOptionalParams, callback: msRest.ServiceCallback<Models.HierarchicalEntityExtractor[]>): void; listHierarchicalEntities(appId: string, versionId: string, options?: Models.ModelListHierarchicalEntitiesOptionalParams | msRest.ServiceCallback<Models.HierarchicalEntityExtractor[]>, callback?: msRest.ServiceCallback<Models.HierarchicalEntityExtractor[]>): Promise<Models.ModelListHierarchicalEntitiesResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listHierarchicalEntitiesOperationSpec, callback) as Promise<Models.ModelListHierarchicalEntitiesResponse>; } /** * Adds a composite entity extractor to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param compositeModelCreateObject A model containing the name and children of the new entity * extractor. * @param [options] The optional parameters * @returns Promise<Models.ModelAddCompositeEntityResponse> */ addCompositeEntity(appId: string, versionId: string, compositeModelCreateObject: Models.CompositeEntityModel, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddCompositeEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param compositeModelCreateObject A model containing the name and children of the new entity * extractor. * @param callback The callback */ addCompositeEntity(appId: string, versionId: string, compositeModelCreateObject: Models.CompositeEntityModel, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param compositeModelCreateObject A model containing the name and children of the new entity * extractor. * @param options The optional parameters * @param callback The callback */ addCompositeEntity(appId: string, versionId: string, compositeModelCreateObject: Models.CompositeEntityModel, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addCompositeEntity(appId: string, versionId: string, compositeModelCreateObject: Models.CompositeEntityModel, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddCompositeEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, compositeModelCreateObject, options }, addCompositeEntityOperationSpec, callback) as Promise<Models.ModelAddCompositeEntityResponse>; } /** * Gets information about all the composite entity models in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListCompositeEntitiesResponse> */ listCompositeEntities(appId: string, versionId: string, options?: Models.ModelListCompositeEntitiesOptionalParams): Promise<Models.ModelListCompositeEntitiesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listCompositeEntities(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.CompositeEntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listCompositeEntities(appId: string, versionId: string, options: Models.ModelListCompositeEntitiesOptionalParams, callback: msRest.ServiceCallback<Models.CompositeEntityExtractor[]>): void; listCompositeEntities(appId: string, versionId: string, options?: Models.ModelListCompositeEntitiesOptionalParams | msRest.ServiceCallback<Models.CompositeEntityExtractor[]>, callback?: msRest.ServiceCallback<Models.CompositeEntityExtractor[]>): Promise<Models.ModelListCompositeEntitiesResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listCompositeEntitiesOperationSpec, callback) as Promise<Models.ModelListCompositeEntitiesResponse>; } /** * Gets information about all the list entity models in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListClosedListsResponse> */ listClosedLists(appId: string, versionId: string, options?: Models.ModelListClosedListsOptionalParams): Promise<Models.ModelListClosedListsResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listClosedLists(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.ClosedListEntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listClosedLists(appId: string, versionId: string, options: Models.ModelListClosedListsOptionalParams, callback: msRest.ServiceCallback<Models.ClosedListEntityExtractor[]>): void; listClosedLists(appId: string, versionId: string, options?: Models.ModelListClosedListsOptionalParams | msRest.ServiceCallback<Models.ClosedListEntityExtractor[]>, callback?: msRest.ServiceCallback<Models.ClosedListEntityExtractor[]>): Promise<Models.ModelListClosedListsResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listClosedListsOperationSpec, callback) as Promise<Models.ModelListClosedListsResponse>; } /** * Adds a list entity model to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param closedListModelCreateObject A model containing the name and words for the new list entity * extractor. * @param [options] The optional parameters * @returns Promise<Models.ModelAddClosedListResponse> */ addClosedList(appId: string, versionId: string, closedListModelCreateObject: Models.ClosedListModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddClosedListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param closedListModelCreateObject A model containing the name and words for the new list entity * extractor. * @param callback The callback */ addClosedList(appId: string, versionId: string, closedListModelCreateObject: Models.ClosedListModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param closedListModelCreateObject A model containing the name and words for the new list entity * extractor. * @param options The optional parameters * @param callback The callback */ addClosedList(appId: string, versionId: string, closedListModelCreateObject: Models.ClosedListModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addClosedList(appId: string, versionId: string, closedListModelCreateObject: Models.ClosedListModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddClosedListResponse> { return this.client.sendOperationRequest( { appId, versionId, closedListModelCreateObject, options }, addClosedListOperationSpec, callback) as Promise<Models.ModelAddClosedListResponse>; } /** * Adds a list of prebuilt entities to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param prebuiltExtractorNames An array of prebuilt entity extractor names. * @param [options] The optional parameters * @returns Promise<Models.ModelAddPrebuiltResponse> */ addPrebuilt(appId: string, versionId: string, prebuiltExtractorNames: string[], options?: msRest.RequestOptionsBase): Promise<Models.ModelAddPrebuiltResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltExtractorNames An array of prebuilt entity extractor names. * @param callback The callback */ addPrebuilt(appId: string, versionId: string, prebuiltExtractorNames: string[], callback: msRest.ServiceCallback<Models.PrebuiltEntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltExtractorNames An array of prebuilt entity extractor names. * @param options The optional parameters * @param callback The callback */ addPrebuilt(appId: string, versionId: string, prebuiltExtractorNames: string[], options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PrebuiltEntityExtractor[]>): void; addPrebuilt(appId: string, versionId: string, prebuiltExtractorNames: string[], options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PrebuiltEntityExtractor[]>, callback?: msRest.ServiceCallback<Models.PrebuiltEntityExtractor[]>): Promise<Models.ModelAddPrebuiltResponse> { return this.client.sendOperationRequest( { appId, versionId, prebuiltExtractorNames, options }, addPrebuiltOperationSpec, callback) as Promise<Models.ModelAddPrebuiltResponse>; } /** * Gets information about all the prebuilt entities in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListPrebuiltsResponse> */ listPrebuilts(appId: string, versionId: string, options?: Models.ModelListPrebuiltsOptionalParams): Promise<Models.ModelListPrebuiltsResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listPrebuilts(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.PrebuiltEntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listPrebuilts(appId: string, versionId: string, options: Models.ModelListPrebuiltsOptionalParams, callback: msRest.ServiceCallback<Models.PrebuiltEntityExtractor[]>): void; listPrebuilts(appId: string, versionId: string, options?: Models.ModelListPrebuiltsOptionalParams | msRest.ServiceCallback<Models.PrebuiltEntityExtractor[]>, callback?: msRest.ServiceCallback<Models.PrebuiltEntityExtractor[]>): Promise<Models.ModelListPrebuiltsResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listPrebuiltsOperationSpec, callback) as Promise<Models.ModelListPrebuiltsResponse>; } /** * Gets all the available prebuilt entities in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListPrebuiltEntitiesResponse> */ listPrebuiltEntities(appId: string, versionId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListPrebuiltEntitiesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listPrebuiltEntities(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.AvailablePrebuiltEntityModel[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listPrebuiltEntities(appId: string, versionId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AvailablePrebuiltEntityModel[]>): void; listPrebuiltEntities(appId: string, versionId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AvailablePrebuiltEntityModel[]>, callback?: msRest.ServiceCallback<Models.AvailablePrebuiltEntityModel[]>): Promise<Models.ModelListPrebuiltEntitiesResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listPrebuiltEntitiesOperationSpec, callback) as Promise<Models.ModelListPrebuiltEntitiesResponse>; } /** * Gets information about all the intent and entity models in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListModelsResponse> */ listModels(appId: string, versionId: string, options?: Models.ModelListModelsOptionalParams): Promise<Models.ModelListModelsResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listModels(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.ModelInfoResponse[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listModels(appId: string, versionId: string, options: Models.ModelListModelsOptionalParams, callback: msRest.ServiceCallback<Models.ModelInfoResponse[]>): void; listModels(appId: string, versionId: string, options?: Models.ModelListModelsOptionalParams | msRest.ServiceCallback<Models.ModelInfoResponse[]>, callback?: msRest.ServiceCallback<Models.ModelInfoResponse[]>): Promise<Models.ModelListModelsResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listModelsOperationSpec, callback) as Promise<Models.ModelListModelsResponse>; } /** * Gets the example utterances for the given intent or entity model in a version of the * application. * @param appId The application ID. * @param versionId The version ID. * @param modelId The ID (GUID) of the model. * @param [options] The optional parameters * @returns Promise<Models.ModelExamplesMethodResponse> */ examplesMethod(appId: string, versionId: string, modelId: string, options?: Models.ModelExamplesMethodOptionalParams): Promise<Models.ModelExamplesMethodResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param modelId The ID (GUID) of the model. * @param callback The callback */ examplesMethod(appId: string, versionId: string, modelId: string, callback: msRest.ServiceCallback<Models.LabelTextObject[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param modelId The ID (GUID) of the model. * @param options The optional parameters * @param callback The callback */ examplesMethod(appId: string, versionId: string, modelId: string, options: Models.ModelExamplesMethodOptionalParams, callback: msRest.ServiceCallback<Models.LabelTextObject[]>): void; examplesMethod(appId: string, versionId: string, modelId: string, options?: Models.ModelExamplesMethodOptionalParams | msRest.ServiceCallback<Models.LabelTextObject[]>, callback?: msRest.ServiceCallback<Models.LabelTextObject[]>): Promise<Models.ModelExamplesMethodResponse> { return this.client.sendOperationRequest( { appId, versionId, modelId, options }, examplesMethodOperationSpec, callback) as Promise<Models.ModelExamplesMethodResponse>; } /** * Gets information about the intent model in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetIntentResponse> */ getIntent(appId: string, versionId: string, intentId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetIntentResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param callback The callback */ getIntent(appId: string, versionId: string, intentId: string, callback: msRest.ServiceCallback<Models.IntentClassifier>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param options The optional parameters * @param callback The callback */ getIntent(appId: string, versionId: string, intentId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IntentClassifier>): void; getIntent(appId: string, versionId: string, intentId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IntentClassifier>, callback?: msRest.ServiceCallback<Models.IntentClassifier>): Promise<Models.ModelGetIntentResponse> { return this.client.sendOperationRequest( { appId, versionId, intentId, options }, getIntentOperationSpec, callback) as Promise<Models.ModelGetIntentResponse>; } /** * Updates the name of an intent in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param modelUpdateObject A model object containing the new intent name. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateIntentResponse> */ updateIntent(appId: string, versionId: string, intentId: string, modelUpdateObject: Models.ModelUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateIntentResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param modelUpdateObject A model object containing the new intent name. * @param callback The callback */ updateIntent(appId: string, versionId: string, intentId: string, modelUpdateObject: Models.ModelUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param modelUpdateObject A model object containing the new intent name. * @param options The optional parameters * @param callback The callback */ updateIntent(appId: string, versionId: string, intentId: string, modelUpdateObject: Models.ModelUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateIntent(appId: string, versionId: string, intentId: string, modelUpdateObject: Models.ModelUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateIntentResponse> { return this.client.sendOperationRequest( { appId, versionId, intentId, modelUpdateObject, options }, updateIntentOperationSpec, callback) as Promise<Models.ModelUpdateIntentResponse>; } /** * Deletes an intent from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteIntentResponse> */ deleteIntent(appId: string, versionId: string, intentId: string, options?: Models.ModelDeleteIntentOptionalParams): Promise<Models.ModelDeleteIntentResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param callback The callback */ deleteIntent(appId: string, versionId: string, intentId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param options The optional parameters * @param callback The callback */ deleteIntent(appId: string, versionId: string, intentId: string, options: Models.ModelDeleteIntentOptionalParams, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteIntent(appId: string, versionId: string, intentId: string, options?: Models.ModelDeleteIntentOptionalParams | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteIntentResponse> { return this.client.sendOperationRequest( { appId, versionId, intentId, options }, deleteIntentOperationSpec, callback) as Promise<Models.ModelDeleteIntentResponse>; } /** * Gets information about an entity model in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetEntityResponse> */ getEntity(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param callback The callback */ getEntity(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.EntityExtractor>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param options The optional parameters * @param callback The callback */ getEntity(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityExtractor>): void; getEntity(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityExtractor>, callback?: msRest.ServiceCallback<Models.EntityExtractor>): Promise<Models.ModelGetEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, getEntityOperationSpec, callback) as Promise<Models.ModelGetEntityResponse>; } /** * Updates the name of an entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param modelUpdateObject A model object containing the new entity extractor name. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateEntityResponse> */ updateEntity(appId: string, versionId: string, entityId: string, modelUpdateObject: Models.ModelUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param modelUpdateObject A model object containing the new entity extractor name. * @param callback The callback */ updateEntity(appId: string, versionId: string, entityId: string, modelUpdateObject: Models.ModelUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param modelUpdateObject A model object containing the new entity extractor name. * @param options The optional parameters * @param callback The callback */ updateEntity(appId: string, versionId: string, entityId: string, modelUpdateObject: Models.ModelUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateEntity(appId: string, versionId: string, entityId: string, modelUpdateObject: Models.ModelUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, modelUpdateObject, options }, updateEntityOperationSpec, callback) as Promise<Models.ModelUpdateEntityResponse>; } /** * Deletes an entity from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteEntityResponse> */ deleteEntity(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param callback The callback */ deleteEntity(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param options The optional parameters * @param callback The callback */ deleteEntity(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteEntity(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, deleteEntityOperationSpec, callback) as Promise<Models.ModelDeleteEntityResponse>; } /** * Gets information about a hierarchical entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetHierarchicalEntityResponse> */ getHierarchicalEntity(appId: string, versionId: string, hEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetHierarchicalEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param callback The callback */ getHierarchicalEntity(appId: string, versionId: string, hEntityId: string, callback: msRest.ServiceCallback<Models.HierarchicalEntityExtractor>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param options The optional parameters * @param callback The callback */ getHierarchicalEntity(appId: string, versionId: string, hEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.HierarchicalEntityExtractor>): void; getHierarchicalEntity(appId: string, versionId: string, hEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.HierarchicalEntityExtractor>, callback?: msRest.ServiceCallback<Models.HierarchicalEntityExtractor>): Promise<Models.ModelGetHierarchicalEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, options }, getHierarchicalEntityOperationSpec, callback) as Promise<Models.ModelGetHierarchicalEntityResponse>; } /** * Updates the name and children of a hierarchical entity model in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hierarchicalModelUpdateObject Model containing names of the children of the hierarchical * entity. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateHierarchicalEntityResponse> */ updateHierarchicalEntity(appId: string, versionId: string, hEntityId: string, hierarchicalModelUpdateObject: Models.HierarchicalEntityModel, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateHierarchicalEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hierarchicalModelUpdateObject Model containing names of the children of the hierarchical * entity. * @param callback The callback */ updateHierarchicalEntity(appId: string, versionId: string, hEntityId: string, hierarchicalModelUpdateObject: Models.HierarchicalEntityModel, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hierarchicalModelUpdateObject Model containing names of the children of the hierarchical * entity. * @param options The optional parameters * @param callback The callback */ updateHierarchicalEntity(appId: string, versionId: string, hEntityId: string, hierarchicalModelUpdateObject: Models.HierarchicalEntityModel, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateHierarchicalEntity(appId: string, versionId: string, hEntityId: string, hierarchicalModelUpdateObject: Models.HierarchicalEntityModel, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateHierarchicalEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, hierarchicalModelUpdateObject, options }, updateHierarchicalEntityOperationSpec, callback) as Promise<Models.ModelUpdateHierarchicalEntityResponse>; } /** * Deletes a hierarchical entity from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteHierarchicalEntityResponse> */ deleteHierarchicalEntity(appId: string, versionId: string, hEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteHierarchicalEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param callback The callback */ deleteHierarchicalEntity(appId: string, versionId: string, hEntityId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param options The optional parameters * @param callback The callback */ deleteHierarchicalEntity(appId: string, versionId: string, hEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteHierarchicalEntity(appId: string, versionId: string, hEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteHierarchicalEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, options }, deleteHierarchicalEntityOperationSpec, callback) as Promise<Models.ModelDeleteHierarchicalEntityResponse>; } /** * Gets information about a composite entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetCompositeEntityResponse> */ getCompositeEntity(appId: string, versionId: string, cEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetCompositeEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param callback The callback */ getCompositeEntity(appId: string, versionId: string, cEntityId: string, callback: msRest.ServiceCallback<Models.CompositeEntityExtractor>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param options The optional parameters * @param callback The callback */ getCompositeEntity(appId: string, versionId: string, cEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CompositeEntityExtractor>): void; getCompositeEntity(appId: string, versionId: string, cEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CompositeEntityExtractor>, callback?: msRest.ServiceCallback<Models.CompositeEntityExtractor>): Promise<Models.ModelGetCompositeEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, options }, getCompositeEntityOperationSpec, callback) as Promise<Models.ModelGetCompositeEntityResponse>; } /** * Updates a composite entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param compositeModelUpdateObject A model object containing the new entity extractor name and * children. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateCompositeEntityResponse> */ updateCompositeEntity(appId: string, versionId: string, cEntityId: string, compositeModelUpdateObject: Models.CompositeEntityModel, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateCompositeEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param compositeModelUpdateObject A model object containing the new entity extractor name and * children. * @param callback The callback */ updateCompositeEntity(appId: string, versionId: string, cEntityId: string, compositeModelUpdateObject: Models.CompositeEntityModel, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param compositeModelUpdateObject A model object containing the new entity extractor name and * children. * @param options The optional parameters * @param callback The callback */ updateCompositeEntity(appId: string, versionId: string, cEntityId: string, compositeModelUpdateObject: Models.CompositeEntityModel, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateCompositeEntity(appId: string, versionId: string, cEntityId: string, compositeModelUpdateObject: Models.CompositeEntityModel, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateCompositeEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, compositeModelUpdateObject, options }, updateCompositeEntityOperationSpec, callback) as Promise<Models.ModelUpdateCompositeEntityResponse>; } /** * Deletes a composite entity from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteCompositeEntityResponse> */ deleteCompositeEntity(appId: string, versionId: string, cEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteCompositeEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param callback The callback */ deleteCompositeEntity(appId: string, versionId: string, cEntityId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param options The optional parameters * @param callback The callback */ deleteCompositeEntity(appId: string, versionId: string, cEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteCompositeEntity(appId: string, versionId: string, cEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteCompositeEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, options }, deleteCompositeEntityOperationSpec, callback) as Promise<Models.ModelDeleteCompositeEntityResponse>; } /** * Gets information about a list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list model ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetClosedListResponse> */ getClosedList(appId: string, versionId: string, clEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetClosedListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list model ID. * @param callback The callback */ getClosedList(appId: string, versionId: string, clEntityId: string, callback: msRest.ServiceCallback<Models.ClosedListEntityExtractor>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list model ID. * @param options The optional parameters * @param callback The callback */ getClosedList(appId: string, versionId: string, clEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ClosedListEntityExtractor>): void; getClosedList(appId: string, versionId: string, clEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ClosedListEntityExtractor>, callback?: msRest.ServiceCallback<Models.ClosedListEntityExtractor>): Promise<Models.ModelGetClosedListResponse> { return this.client.sendOperationRequest( { appId, versionId, clEntityId, options }, getClosedListOperationSpec, callback) as Promise<Models.ModelGetClosedListResponse>; } /** * Updates the list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list model ID. * @param closedListModelUpdateObject The new list entity name and words list. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateClosedListResponse> */ updateClosedList(appId: string, versionId: string, clEntityId: string, closedListModelUpdateObject: Models.ClosedListModelUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateClosedListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list model ID. * @param closedListModelUpdateObject The new list entity name and words list. * @param callback The callback */ updateClosedList(appId: string, versionId: string, clEntityId: string, closedListModelUpdateObject: Models.ClosedListModelUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list model ID. * @param closedListModelUpdateObject The new list entity name and words list. * @param options The optional parameters * @param callback The callback */ updateClosedList(appId: string, versionId: string, clEntityId: string, closedListModelUpdateObject: Models.ClosedListModelUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateClosedList(appId: string, versionId: string, clEntityId: string, closedListModelUpdateObject: Models.ClosedListModelUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateClosedListResponse> { return this.client.sendOperationRequest( { appId, versionId, clEntityId, closedListModelUpdateObject, options }, updateClosedListOperationSpec, callback) as Promise<Models.ModelUpdateClosedListResponse>; } /** * Adds a batch of sublists to an existing list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity model ID. * @param closedListModelPatchObject A words list batch. * @param [options] The optional parameters * @returns Promise<Models.ModelPatchClosedListResponse> */ patchClosedList(appId: string, versionId: string, clEntityId: string, closedListModelPatchObject: Models.ClosedListModelPatchObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelPatchClosedListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity model ID. * @param closedListModelPatchObject A words list batch. * @param callback The callback */ patchClosedList(appId: string, versionId: string, clEntityId: string, closedListModelPatchObject: Models.ClosedListModelPatchObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity model ID. * @param closedListModelPatchObject A words list batch. * @param options The optional parameters * @param callback The callback */ patchClosedList(appId: string, versionId: string, clEntityId: string, closedListModelPatchObject: Models.ClosedListModelPatchObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; patchClosedList(appId: string, versionId: string, clEntityId: string, closedListModelPatchObject: Models.ClosedListModelPatchObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelPatchClosedListResponse> { return this.client.sendOperationRequest( { appId, versionId, clEntityId, closedListModelPatchObject, options }, patchClosedListOperationSpec, callback) as Promise<Models.ModelPatchClosedListResponse>; } /** * Deletes a list entity model from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity model ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteClosedListResponse> */ deleteClosedList(appId: string, versionId: string, clEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteClosedListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity model ID. * @param callback The callback */ deleteClosedList(appId: string, versionId: string, clEntityId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity model ID. * @param options The optional parameters * @param callback The callback */ deleteClosedList(appId: string, versionId: string, clEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteClosedList(appId: string, versionId: string, clEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteClosedListResponse> { return this.client.sendOperationRequest( { appId, versionId, clEntityId, options }, deleteClosedListOperationSpec, callback) as Promise<Models.ModelDeleteClosedListResponse>; } /** * Gets information about a prebuilt entity model in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param prebuiltId The prebuilt entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetPrebuiltResponse> */ getPrebuilt(appId: string, versionId: string, prebuiltId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetPrebuiltResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltId The prebuilt entity extractor ID. * @param callback The callback */ getPrebuilt(appId: string, versionId: string, prebuiltId: string, callback: msRest.ServiceCallback<Models.PrebuiltEntityExtractor>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltId The prebuilt entity extractor ID. * @param options The optional parameters * @param callback The callback */ getPrebuilt(appId: string, versionId: string, prebuiltId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PrebuiltEntityExtractor>): void; getPrebuilt(appId: string, versionId: string, prebuiltId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PrebuiltEntityExtractor>, callback?: msRest.ServiceCallback<Models.PrebuiltEntityExtractor>): Promise<Models.ModelGetPrebuiltResponse> { return this.client.sendOperationRequest( { appId, versionId, prebuiltId, options }, getPrebuiltOperationSpec, callback) as Promise<Models.ModelGetPrebuiltResponse>; } /** * Deletes a prebuilt entity extractor from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param prebuiltId The prebuilt entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeletePrebuiltResponse> */ deletePrebuilt(appId: string, versionId: string, prebuiltId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeletePrebuiltResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltId The prebuilt entity extractor ID. * @param callback The callback */ deletePrebuilt(appId: string, versionId: string, prebuiltId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltId The prebuilt entity extractor ID. * @param options The optional parameters * @param callback The callback */ deletePrebuilt(appId: string, versionId: string, prebuiltId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deletePrebuilt(appId: string, versionId: string, prebuiltId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeletePrebuiltResponse> { return this.client.sendOperationRequest( { appId, versionId, prebuiltId, options }, deletePrebuiltOperationSpec, callback) as Promise<Models.ModelDeletePrebuiltResponse>; } /** * Deletes a sublist of a specific list entity model from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param subListId The sublist ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteSubListResponse> */ deleteSubList(appId: string, versionId: string, clEntityId: string, subListId: number, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteSubListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param subListId The sublist ID. * @param callback The callback */ deleteSubList(appId: string, versionId: string, clEntityId: string, subListId: number, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param subListId The sublist ID. * @param options The optional parameters * @param callback The callback */ deleteSubList(appId: string, versionId: string, clEntityId: string, subListId: number, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteSubList(appId: string, versionId: string, clEntityId: string, subListId: number, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteSubListResponse> { return this.client.sendOperationRequest( { appId, versionId, clEntityId, subListId, options }, deleteSubListOperationSpec, callback) as Promise<Models.ModelDeleteSubListResponse>; } /** * Updates one of the list entity's sublists in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param subListId The sublist ID. * @param wordListBaseUpdateObject A sublist update object containing the new canonical form and * the list of words. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateSubListResponse> */ updateSubList(appId: string, versionId: string, clEntityId: string, subListId: number, wordListBaseUpdateObject: Models.WordListBaseUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateSubListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param subListId The sublist ID. * @param wordListBaseUpdateObject A sublist update object containing the new canonical form and * the list of words. * @param callback The callback */ updateSubList(appId: string, versionId: string, clEntityId: string, subListId: number, wordListBaseUpdateObject: Models.WordListBaseUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param subListId The sublist ID. * @param wordListBaseUpdateObject A sublist update object containing the new canonical form and * the list of words. * @param options The optional parameters * @param callback The callback */ updateSubList(appId: string, versionId: string, clEntityId: string, subListId: number, wordListBaseUpdateObject: Models.WordListBaseUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateSubList(appId: string, versionId: string, clEntityId: string, subListId: number, wordListBaseUpdateObject: Models.WordListBaseUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateSubListResponse> { return this.client.sendOperationRequest( { appId, versionId, clEntityId, subListId, wordListBaseUpdateObject, options }, updateSubListOperationSpec, callback) as Promise<Models.ModelUpdateSubListResponse>; } /** * Suggests example utterances that would improve the accuracy of the intent model in a version of * the application. * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListIntentSuggestionsResponse> */ listIntentSuggestions(appId: string, versionId: string, intentId: string, options?: Models.ModelListIntentSuggestionsOptionalParams): Promise<Models.ModelListIntentSuggestionsResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param callback The callback */ listIntentSuggestions(appId: string, versionId: string, intentId: string, callback: msRest.ServiceCallback<Models.IntentsSuggestionExample[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param intentId The intent classifier ID. * @param options The optional parameters * @param callback The callback */ listIntentSuggestions(appId: string, versionId: string, intentId: string, options: Models.ModelListIntentSuggestionsOptionalParams, callback: msRest.ServiceCallback<Models.IntentsSuggestionExample[]>): void; listIntentSuggestions(appId: string, versionId: string, intentId: string, options?: Models.ModelListIntentSuggestionsOptionalParams | msRest.ServiceCallback<Models.IntentsSuggestionExample[]>, callback?: msRest.ServiceCallback<Models.IntentsSuggestionExample[]>): Promise<Models.ModelListIntentSuggestionsResponse> { return this.client.sendOperationRequest( { appId, versionId, intentId, options }, listIntentSuggestionsOperationSpec, callback) as Promise<Models.ModelListIntentSuggestionsResponse>; } /** * Get suggested example utterances that would improve the accuracy of the entity model in a * version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The target entity extractor model to enhance. * @param [options] The optional parameters * @returns Promise<Models.ModelListEntitySuggestionsResponse> */ listEntitySuggestions(appId: string, versionId: string, entityId: string, options?: Models.ModelListEntitySuggestionsOptionalParams): Promise<Models.ModelListEntitySuggestionsResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The target entity extractor model to enhance. * @param callback The callback */ listEntitySuggestions(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.EntitiesSuggestionExample[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The target entity extractor model to enhance. * @param options The optional parameters * @param callback The callback */ listEntitySuggestions(appId: string, versionId: string, entityId: string, options: Models.ModelListEntitySuggestionsOptionalParams, callback: msRest.ServiceCallback<Models.EntitiesSuggestionExample[]>): void; listEntitySuggestions(appId: string, versionId: string, entityId: string, options?: Models.ModelListEntitySuggestionsOptionalParams | msRest.ServiceCallback<Models.EntitiesSuggestionExample[]>, callback?: msRest.ServiceCallback<Models.EntitiesSuggestionExample[]>): Promise<Models.ModelListEntitySuggestionsResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, listEntitySuggestionsOperationSpec, callback) as Promise<Models.ModelListEntitySuggestionsResponse>; } /** * Adds a sublist to an existing list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param wordListCreateObject Words list. * @param [options] The optional parameters * @returns Promise<Models.ModelAddSubListResponse> */ addSubList(appId: string, versionId: string, clEntityId: string, wordListCreateObject: Models.WordListObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddSubListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param wordListCreateObject Words list. * @param callback The callback */ addSubList(appId: string, versionId: string, clEntityId: string, wordListCreateObject: Models.WordListObject, callback: msRest.ServiceCallback<number>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param clEntityId The list entity extractor ID. * @param wordListCreateObject Words list. * @param options The optional parameters * @param callback The callback */ addSubList(appId: string, versionId: string, clEntityId: string, wordListCreateObject: Models.WordListObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<number>): void; addSubList(appId: string, versionId: string, clEntityId: string, wordListCreateObject: Models.WordListObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<number>, callback?: msRest.ServiceCallback<number>): Promise<Models.ModelAddSubListResponse> { return this.client.sendOperationRequest( { appId, versionId, clEntityId, wordListCreateObject, options }, addSubListOperationSpec, callback) as Promise<Models.ModelAddSubListResponse>; } /** * Adds a customizable prebuilt domain along with all of its intent and entity models in a version * of the application. * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainObject A prebuilt domain create object containing the name of the domain. * @param [options] The optional parameters * @returns Promise<Models.ModelAddCustomPrebuiltDomainResponse> */ addCustomPrebuiltDomain(appId: string, versionId: string, prebuiltDomainObject: Models.PrebuiltDomainCreateBaseObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddCustomPrebuiltDomainResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainObject A prebuilt domain create object containing the name of the domain. * @param callback The callback */ addCustomPrebuiltDomain(appId: string, versionId: string, prebuiltDomainObject: Models.PrebuiltDomainCreateBaseObject, callback: msRest.ServiceCallback<string[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainObject A prebuilt domain create object containing the name of the domain. * @param options The optional parameters * @param callback The callback */ addCustomPrebuiltDomain(appId: string, versionId: string, prebuiltDomainObject: Models.PrebuiltDomainCreateBaseObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string[]>): void; addCustomPrebuiltDomain(appId: string, versionId: string, prebuiltDomainObject: Models.PrebuiltDomainCreateBaseObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string[]>, callback?: msRest.ServiceCallback<string[]>): Promise<Models.ModelAddCustomPrebuiltDomainResponse> { return this.client.sendOperationRequest( { appId, versionId, prebuiltDomainObject, options }, addCustomPrebuiltDomainOperationSpec, callback) as Promise<Models.ModelAddCustomPrebuiltDomainResponse>; } /** * Adds a customizable prebuilt intent model to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainModelCreateObject A model object containing the name of the customizable * prebuilt intent and the name of the domain to which this model belongs. * @param [options] The optional parameters * @returns Promise<Models.ModelAddCustomPrebuiltIntentResponse> */ addCustomPrebuiltIntent(appId: string, versionId: string, prebuiltDomainModelCreateObject: Models.PrebuiltDomainModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddCustomPrebuiltIntentResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainModelCreateObject A model object containing the name of the customizable * prebuilt intent and the name of the domain to which this model belongs. * @param callback The callback */ addCustomPrebuiltIntent(appId: string, versionId: string, prebuiltDomainModelCreateObject: Models.PrebuiltDomainModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainModelCreateObject A model object containing the name of the customizable * prebuilt intent and the name of the domain to which this model belongs. * @param options The optional parameters * @param callback The callback */ addCustomPrebuiltIntent(appId: string, versionId: string, prebuiltDomainModelCreateObject: Models.PrebuiltDomainModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addCustomPrebuiltIntent(appId: string, versionId: string, prebuiltDomainModelCreateObject: Models.PrebuiltDomainModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddCustomPrebuiltIntentResponse> { return this.client.sendOperationRequest( { appId, versionId, prebuiltDomainModelCreateObject, options }, addCustomPrebuiltIntentOperationSpec, callback) as Promise<Models.ModelAddCustomPrebuiltIntentResponse>; } /** * Gets information about customizable prebuilt intents added to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListCustomPrebuiltIntentsResponse> */ listCustomPrebuiltIntents(appId: string, versionId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListCustomPrebuiltIntentsResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listCustomPrebuiltIntents(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.IntentClassifier[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listCustomPrebuiltIntents(appId: string, versionId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IntentClassifier[]>): void; listCustomPrebuiltIntents(appId: string, versionId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IntentClassifier[]>, callback?: msRest.ServiceCallback<Models.IntentClassifier[]>): Promise<Models.ModelListCustomPrebuiltIntentsResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listCustomPrebuiltIntentsOperationSpec, callback) as Promise<Models.ModelListCustomPrebuiltIntentsResponse>; } /** * Adds a prebuilt entity model to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainModelCreateObject A model object containing the name of the prebuilt entity * and the name of the domain to which this model belongs. * @param [options] The optional parameters * @returns Promise<Models.ModelAddCustomPrebuiltEntityResponse> */ addCustomPrebuiltEntity(appId: string, versionId: string, prebuiltDomainModelCreateObject: Models.PrebuiltDomainModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddCustomPrebuiltEntityResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainModelCreateObject A model object containing the name of the prebuilt entity * and the name of the domain to which this model belongs. * @param callback The callback */ addCustomPrebuiltEntity(appId: string, versionId: string, prebuiltDomainModelCreateObject: Models.PrebuiltDomainModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param prebuiltDomainModelCreateObject A model object containing the name of the prebuilt entity * and the name of the domain to which this model belongs. * @param options The optional parameters * @param callback The callback */ addCustomPrebuiltEntity(appId: string, versionId: string, prebuiltDomainModelCreateObject: Models.PrebuiltDomainModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addCustomPrebuiltEntity(appId: string, versionId: string, prebuiltDomainModelCreateObject: Models.PrebuiltDomainModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddCustomPrebuiltEntityResponse> { return this.client.sendOperationRequest( { appId, versionId, prebuiltDomainModelCreateObject, options }, addCustomPrebuiltEntityOperationSpec, callback) as Promise<Models.ModelAddCustomPrebuiltEntityResponse>; } /** * Gets all prebuilt entities used in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListCustomPrebuiltEntitiesResponse> */ listCustomPrebuiltEntities(appId: string, versionId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListCustomPrebuiltEntitiesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listCustomPrebuiltEntities(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.EntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listCustomPrebuiltEntities(appId: string, versionId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityExtractor[]>): void; listCustomPrebuiltEntities(appId: string, versionId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityExtractor[]>, callback?: msRest.ServiceCallback<Models.EntityExtractor[]>): Promise<Models.ModelListCustomPrebuiltEntitiesResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listCustomPrebuiltEntitiesOperationSpec, callback) as Promise<Models.ModelListCustomPrebuiltEntitiesResponse>; } /** * Gets all prebuilt intent and entity model information used in a version of this application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListCustomPrebuiltModelsResponse> */ listCustomPrebuiltModels(appId: string, versionId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListCustomPrebuiltModelsResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listCustomPrebuiltModels(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.CustomPrebuiltModel[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listCustomPrebuiltModels(appId: string, versionId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CustomPrebuiltModel[]>): void; listCustomPrebuiltModels(appId: string, versionId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CustomPrebuiltModel[]>, callback?: msRest.ServiceCallback<Models.CustomPrebuiltModel[]>): Promise<Models.ModelListCustomPrebuiltModelsResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listCustomPrebuiltModelsOperationSpec, callback) as Promise<Models.ModelListCustomPrebuiltModelsResponse>; } /** * Deletes a prebuilt domain's models in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param domainName Domain name. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteCustomPrebuiltDomainResponse> */ deleteCustomPrebuiltDomain(appId: string, versionId: string, domainName: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteCustomPrebuiltDomainResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param domainName Domain name. * @param callback The callback */ deleteCustomPrebuiltDomain(appId: string, versionId: string, domainName: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param domainName Domain name. * @param options The optional parameters * @param callback The callback */ deleteCustomPrebuiltDomain(appId: string, versionId: string, domainName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteCustomPrebuiltDomain(appId: string, versionId: string, domainName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteCustomPrebuiltDomainResponse> { return this.client.sendOperationRequest( { appId, versionId, domainName, options }, deleteCustomPrebuiltDomainOperationSpec, callback) as Promise<Models.ModelDeleteCustomPrebuiltDomainResponse>; } /** * Gets information about the child's model contained in an hierarchical entity child model in a * version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetHierarchicalEntityChildResponse> */ getHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetHierarchicalEntityChildResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param callback The callback */ getHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, callback: msRest.ServiceCallback<Models.HierarchicalChildEntity>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param options The optional parameters * @param callback The callback */ getHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.HierarchicalChildEntity>): void; getHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.HierarchicalChildEntity>, callback?: msRest.ServiceCallback<Models.HierarchicalChildEntity>): Promise<Models.ModelGetHierarchicalEntityChildResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, hChildId, options }, getHierarchicalEntityChildOperationSpec, callback) as Promise<Models.ModelGetHierarchicalEntityChildResponse>; } /** * Renames a single child in an existing hierarchical entity model in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param hierarchicalChildModelUpdateObject Model object containing new name of the hierarchical * entity child. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateHierarchicalEntityChildResponse> */ updateHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, hierarchicalChildModelUpdateObject: Models.HierarchicalChildModelUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateHierarchicalEntityChildResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param hierarchicalChildModelUpdateObject Model object containing new name of the hierarchical * entity child. * @param callback The callback */ updateHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, hierarchicalChildModelUpdateObject: Models.HierarchicalChildModelUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param hierarchicalChildModelUpdateObject Model object containing new name of the hierarchical * entity child. * @param options The optional parameters * @param callback The callback */ updateHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, hierarchicalChildModelUpdateObject: Models.HierarchicalChildModelUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, hierarchicalChildModelUpdateObject: Models.HierarchicalChildModelUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateHierarchicalEntityChildResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, hChildId, hierarchicalChildModelUpdateObject, options }, updateHierarchicalEntityChildOperationSpec, callback) as Promise<Models.ModelUpdateHierarchicalEntityChildResponse>; } /** * Deletes a hierarchical entity extractor child in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteHierarchicalEntityChildResponse> */ deleteHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteHierarchicalEntityChildResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param callback The callback */ deleteHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hChildId The hierarchical entity extractor child ID. * @param options The optional parameters * @param callback The callback */ deleteHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hChildId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteHierarchicalEntityChildResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, hChildId, options }, deleteHierarchicalEntityChildOperationSpec, callback) as Promise<Models.ModelDeleteHierarchicalEntityChildResponse>; } /** * Creates a single child in an existing hierarchical entity model in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hierarchicalChildModelCreateObject A model object containing the name of the new * hierarchical child model. * @param [options] The optional parameters * @returns Promise<Models.ModelAddHierarchicalEntityChildResponse> */ addHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hierarchicalChildModelCreateObject: Models.HierarchicalChildModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddHierarchicalEntityChildResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hierarchicalChildModelCreateObject A model object containing the name of the new * hierarchical child model. * @param callback The callback */ addHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hierarchicalChildModelCreateObject: Models.HierarchicalChildModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param hierarchicalChildModelCreateObject A model object containing the name of the new * hierarchical child model. * @param options The optional parameters * @param callback The callback */ addHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hierarchicalChildModelCreateObject: Models.HierarchicalChildModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addHierarchicalEntityChild(appId: string, versionId: string, hEntityId: string, hierarchicalChildModelCreateObject: Models.HierarchicalChildModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddHierarchicalEntityChildResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, hierarchicalChildModelCreateObject, options }, addHierarchicalEntityChildOperationSpec, callback) as Promise<Models.ModelAddHierarchicalEntityChildResponse>; } /** * Creates a single child in an existing composite entity model in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param compositeChildModelCreateObject A model object containing the name of the new composite * child model. * @param [options] The optional parameters * @returns Promise<Models.ModelAddCompositeEntityChildResponse> */ addCompositeEntityChild(appId: string, versionId: string, cEntityId: string, compositeChildModelCreateObject: Models.CompositeChildModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddCompositeEntityChildResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param compositeChildModelCreateObject A model object containing the name of the new composite * child model. * @param callback The callback */ addCompositeEntityChild(appId: string, versionId: string, cEntityId: string, compositeChildModelCreateObject: Models.CompositeChildModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param compositeChildModelCreateObject A model object containing the name of the new composite * child model. * @param options The optional parameters * @param callback The callback */ addCompositeEntityChild(appId: string, versionId: string, cEntityId: string, compositeChildModelCreateObject: Models.CompositeChildModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; addCompositeEntityChild(appId: string, versionId: string, cEntityId: string, compositeChildModelCreateObject: Models.CompositeChildModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelAddCompositeEntityChildResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, compositeChildModelCreateObject, options }, addCompositeEntityChildOperationSpec, callback) as Promise<Models.ModelAddCompositeEntityChildResponse>; } /** * Deletes a composite entity extractor child from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param cChildId The hierarchical entity extractor child ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteCompositeEntityChildResponse> */ deleteCompositeEntityChild(appId: string, versionId: string, cEntityId: string, cChildId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteCompositeEntityChildResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param cChildId The hierarchical entity extractor child ID. * @param callback The callback */ deleteCompositeEntityChild(appId: string, versionId: string, cEntityId: string, cChildId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param cChildId The hierarchical entity extractor child ID. * @param options The optional parameters * @param callback The callback */ deleteCompositeEntityChild(appId: string, versionId: string, cEntityId: string, cChildId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteCompositeEntityChild(appId: string, versionId: string, cEntityId: string, cChildId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteCompositeEntityChildResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, cChildId, options }, deleteCompositeEntityChildOperationSpec, callback) as Promise<Models.ModelDeleteCompositeEntityChildResponse>; } /** * @summary Gets information about the regular expression entity models in a version of the * application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListRegexEntityInfosResponse> */ listRegexEntityInfos(appId: string, versionId: string, options?: Models.ModelListRegexEntityInfosOptionalParams): Promise<Models.ModelListRegexEntityInfosResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listRegexEntityInfos(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.RegexEntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listRegexEntityInfos(appId: string, versionId: string, options: Models.ModelListRegexEntityInfosOptionalParams, callback: msRest.ServiceCallback<Models.RegexEntityExtractor[]>): void; listRegexEntityInfos(appId: string, versionId: string, options?: Models.ModelListRegexEntityInfosOptionalParams | msRest.ServiceCallback<Models.RegexEntityExtractor[]>, callback?: msRest.ServiceCallback<Models.RegexEntityExtractor[]>): Promise<Models.ModelListRegexEntityInfosResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listRegexEntityInfosOperationSpec, callback) as Promise<Models.ModelListRegexEntityInfosResponse>; } /** * @summary Adds a regular expression entity model to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param regexEntityExtractorCreateObj A model object containing the name and regex pattern for * the new regular expression entity extractor. * @param [options] The optional parameters * @returns Promise<Models.ModelCreateRegexEntityModelResponse> */ createRegexEntityModel(appId: string, versionId: string, regexEntityExtractorCreateObj: Models.RegexModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreateRegexEntityModelResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param regexEntityExtractorCreateObj A model object containing the name and regex pattern for * the new regular expression entity extractor. * @param callback The callback */ createRegexEntityModel(appId: string, versionId: string, regexEntityExtractorCreateObj: Models.RegexModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param regexEntityExtractorCreateObj A model object containing the name and regex pattern for * the new regular expression entity extractor. * @param options The optional parameters * @param callback The callback */ createRegexEntityModel(appId: string, versionId: string, regexEntityExtractorCreateObj: Models.RegexModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createRegexEntityModel(appId: string, versionId: string, regexEntityExtractorCreateObj: Models.RegexModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreateRegexEntityModelResponse> { return this.client.sendOperationRequest( { appId, versionId, regexEntityExtractorCreateObj, options }, createRegexEntityModelOperationSpec, callback) as Promise<Models.ModelCreateRegexEntityModelResponse>; } /** * @summary Get information about the Pattern.Any entity models in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListPatternAnyEntityInfosResponse> */ listPatternAnyEntityInfos(appId: string, versionId: string, options?: Models.ModelListPatternAnyEntityInfosOptionalParams): Promise<Models.ModelListPatternAnyEntityInfosResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param callback The callback */ listPatternAnyEntityInfos(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.PatternAnyEntityExtractor[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param options The optional parameters * @param callback The callback */ listPatternAnyEntityInfos(appId: string, versionId: string, options: Models.ModelListPatternAnyEntityInfosOptionalParams, callback: msRest.ServiceCallback<Models.PatternAnyEntityExtractor[]>): void; listPatternAnyEntityInfos(appId: string, versionId: string, options?: Models.ModelListPatternAnyEntityInfosOptionalParams | msRest.ServiceCallback<Models.PatternAnyEntityExtractor[]>, callback?: msRest.ServiceCallback<Models.PatternAnyEntityExtractor[]>): Promise<Models.ModelListPatternAnyEntityInfosResponse> { return this.client.sendOperationRequest( { appId, versionId, options }, listPatternAnyEntityInfosOperationSpec, callback) as Promise<Models.ModelListPatternAnyEntityInfosResponse>; } /** * @summary Adds a pattern.any entity extractor to a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param extractorCreateObject A model object containing the name and explicit list for the new * Pattern.Any entity extractor. * @param [options] The optional parameters * @returns Promise<Models.ModelCreatePatternAnyEntityModelResponse> */ createPatternAnyEntityModel(appId: string, versionId: string, extractorCreateObject: Models.PatternAnyModelCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreatePatternAnyEntityModelResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param extractorCreateObject A model object containing the name and explicit list for the new * Pattern.Any entity extractor. * @param callback The callback */ createPatternAnyEntityModel(appId: string, versionId: string, extractorCreateObject: Models.PatternAnyModelCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param extractorCreateObject A model object containing the name and explicit list for the new * Pattern.Any entity extractor. * @param options The optional parameters * @param callback The callback */ createPatternAnyEntityModel(appId: string, versionId: string, extractorCreateObject: Models.PatternAnyModelCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createPatternAnyEntityModel(appId: string, versionId: string, extractorCreateObject: Models.PatternAnyModelCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreatePatternAnyEntityModelResponse> { return this.client.sendOperationRequest( { appId, versionId, extractorCreateObject, options }, createPatternAnyEntityModelOperationSpec, callback) as Promise<Models.ModelCreatePatternAnyEntityModelResponse>; } /** * @summary Get all roles for an entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param [options] The optional parameters * @returns Promise<Models.ModelListEntityRolesResponse> */ listEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListEntityRolesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param callback The callback */ listEntityRoles(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param options The optional parameters * @param callback The callback */ listEntityRoles(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; listEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole[]>, callback?: msRest.ServiceCallback<Models.EntityRole[]>): Promise<Models.ModelListEntityRolesResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, listEntityRolesOperationSpec, callback) as Promise<Models.ModelListEntityRolesResponse>; } /** * @summary Create an entity role in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param [options] The optional parameters * @returns Promise<Models.ModelCreateEntityRoleResponse> */ createEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreateEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param callback The callback */ createEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param options The optional parameters * @param callback The callback */ createEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreateEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, entityRoleCreateObject, options }, createEntityRoleOperationSpec, callback) as Promise<Models.ModelCreateEntityRoleResponse>; } /** * @summary Get a prebuilt entity's roles in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param [options] The optional parameters * @returns Promise<Models.ModelListPrebuiltEntityRolesResponse> */ listPrebuiltEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListPrebuiltEntityRolesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param callback The callback */ listPrebuiltEntityRoles(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param options The optional parameters * @param callback The callback */ listPrebuiltEntityRoles(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; listPrebuiltEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole[]>, callback?: msRest.ServiceCallback<Models.EntityRole[]>): Promise<Models.ModelListPrebuiltEntityRolesResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, listPrebuiltEntityRolesOperationSpec, callback) as Promise<Models.ModelListPrebuiltEntityRolesResponse>; } /** * @summary Create a role for a prebuilt entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param [options] The optional parameters * @returns Promise<Models.ModelCreatePrebuiltEntityRoleResponse> */ createPrebuiltEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreatePrebuiltEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param callback The callback */ createPrebuiltEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param options The optional parameters * @param callback The callback */ createPrebuiltEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createPrebuiltEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreatePrebuiltEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, entityRoleCreateObject, options }, createPrebuiltEntityRoleOperationSpec, callback) as Promise<Models.ModelCreatePrebuiltEntityRoleResponse>; } /** * @summary Get all roles for a list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param [options] The optional parameters * @returns Promise<Models.ModelListClosedListEntityRolesResponse> */ listClosedListEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListClosedListEntityRolesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param callback The callback */ listClosedListEntityRoles(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param options The optional parameters * @param callback The callback */ listClosedListEntityRoles(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; listClosedListEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole[]>, callback?: msRest.ServiceCallback<Models.EntityRole[]>): Promise<Models.ModelListClosedListEntityRolesResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, listClosedListEntityRolesOperationSpec, callback) as Promise<Models.ModelListClosedListEntityRolesResponse>; } /** * @summary Create a role for a list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param [options] The optional parameters * @returns Promise<Models.ModelCreateClosedListEntityRoleResponse> */ createClosedListEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreateClosedListEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param callback The callback */ createClosedListEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param options The optional parameters * @param callback The callback */ createClosedListEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createClosedListEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreateClosedListEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, entityRoleCreateObject, options }, createClosedListEntityRoleOperationSpec, callback) as Promise<Models.ModelCreateClosedListEntityRoleResponse>; } /** * @summary Get all roles for a regular expression entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param [options] The optional parameters * @returns Promise<Models.ModelListRegexEntityRolesResponse> */ listRegexEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListRegexEntityRolesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param callback The callback */ listRegexEntityRoles(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param options The optional parameters * @param callback The callback */ listRegexEntityRoles(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; listRegexEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole[]>, callback?: msRest.ServiceCallback<Models.EntityRole[]>): Promise<Models.ModelListRegexEntityRolesResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, listRegexEntityRolesOperationSpec, callback) as Promise<Models.ModelListRegexEntityRolesResponse>; } /** * @summary Create a role for an regular expression entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param [options] The optional parameters * @returns Promise<Models.ModelCreateRegexEntityRoleResponse> */ createRegexEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreateRegexEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param callback The callback */ createRegexEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param options The optional parameters * @param callback The callback */ createRegexEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createRegexEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreateRegexEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, entityRoleCreateObject, options }, createRegexEntityRoleOperationSpec, callback) as Promise<Models.ModelCreateRegexEntityRoleResponse>; } /** * @summary Get all roles for a composite entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListCompositeEntityRolesResponse> */ listCompositeEntityRoles(appId: string, versionId: string, cEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListCompositeEntityRolesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param callback The callback */ listCompositeEntityRoles(appId: string, versionId: string, cEntityId: string, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param options The optional parameters * @param callback The callback */ listCompositeEntityRoles(appId: string, versionId: string, cEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; listCompositeEntityRoles(appId: string, versionId: string, cEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole[]>, callback?: msRest.ServiceCallback<Models.EntityRole[]>): Promise<Models.ModelListCompositeEntityRolesResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, options }, listCompositeEntityRolesOperationSpec, callback) as Promise<Models.ModelListCompositeEntityRolesResponse>; } /** * @summary Create a role for a composite entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param [options] The optional parameters * @returns Promise<Models.ModelCreateCompositeEntityRoleResponse> */ createCompositeEntityRole(appId: string, versionId: string, cEntityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreateCompositeEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param callback The callback */ createCompositeEntityRole(appId: string, versionId: string, cEntityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param options The optional parameters * @param callback The callback */ createCompositeEntityRole(appId: string, versionId: string, cEntityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createCompositeEntityRole(appId: string, versionId: string, cEntityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreateCompositeEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, entityRoleCreateObject, options }, createCompositeEntityRoleOperationSpec, callback) as Promise<Models.ModelCreateCompositeEntityRoleResponse>; } /** * @summary Get all roles for a Pattern.any entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param [options] The optional parameters * @returns Promise<Models.ModelListPatternAnyEntityRolesResponse> */ listPatternAnyEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListPatternAnyEntityRolesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param callback The callback */ listPatternAnyEntityRoles(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param options The optional parameters * @param callback The callback */ listPatternAnyEntityRoles(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; listPatternAnyEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole[]>, callback?: msRest.ServiceCallback<Models.EntityRole[]>): Promise<Models.ModelListPatternAnyEntityRolesResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, listPatternAnyEntityRolesOperationSpec, callback) as Promise<Models.ModelListPatternAnyEntityRolesResponse>; } /** * @summary Create a role for an Pattern.any entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param [options] The optional parameters * @returns Promise<Models.ModelCreatePatternAnyEntityRoleResponse> */ createPatternAnyEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreatePatternAnyEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param callback The callback */ createPatternAnyEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param options The optional parameters * @param callback The callback */ createPatternAnyEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createPatternAnyEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreatePatternAnyEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, entityRoleCreateObject, options }, createPatternAnyEntityRoleOperationSpec, callback) as Promise<Models.ModelCreatePatternAnyEntityRoleResponse>; } /** * @summary Get all roles for a hierarchical entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelListHierarchicalEntityRolesResponse> */ listHierarchicalEntityRoles(appId: string, versionId: string, hEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListHierarchicalEntityRolesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param callback The callback */ listHierarchicalEntityRoles(appId: string, versionId: string, hEntityId: string, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param options The optional parameters * @param callback The callback */ listHierarchicalEntityRoles(appId: string, versionId: string, hEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; listHierarchicalEntityRoles(appId: string, versionId: string, hEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole[]>, callback?: msRest.ServiceCallback<Models.EntityRole[]>): Promise<Models.ModelListHierarchicalEntityRolesResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, options }, listHierarchicalEntityRolesOperationSpec, callback) as Promise<Models.ModelListHierarchicalEntityRolesResponse>; } /** * @summary Create a role for an hierarchical entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param [options] The optional parameters * @returns Promise<Models.ModelCreateHierarchicalEntityRoleResponse> */ createHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreateHierarchicalEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param callback The callback */ createHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param options The optional parameters * @param callback The callback */ createHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreateHierarchicalEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, entityRoleCreateObject, options }, createHierarchicalEntityRoleOperationSpec, callback) as Promise<Models.ModelCreateHierarchicalEntityRoleResponse>; } /** * @summary Get all roles for a prebuilt entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param [options] The optional parameters * @returns Promise<Models.ModelListCustomPrebuiltEntityRolesResponse> */ listCustomPrebuiltEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelListCustomPrebuiltEntityRolesResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param callback The callback */ listCustomPrebuiltEntityRoles(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity Id * @param options The optional parameters * @param callback The callback */ listCustomPrebuiltEntityRoles(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole[]>): void; listCustomPrebuiltEntityRoles(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole[]>, callback?: msRest.ServiceCallback<Models.EntityRole[]>): Promise<Models.ModelListCustomPrebuiltEntityRolesResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, listCustomPrebuiltEntityRolesOperationSpec, callback) as Promise<Models.ModelListCustomPrebuiltEntityRolesResponse>; } /** * @summary Create a role for a prebuilt entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param [options] The optional parameters * @returns Promise<Models.ModelCreateCustomPrebuiltEntityRoleResponse> */ createCustomPrebuiltEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelCreateCustomPrebuiltEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param callback The callback */ createCustomPrebuiltEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, callback: msRest.ServiceCallback<string>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity model ID. * @param entityRoleCreateObject An entity role object containing the name of role. * @param options The optional parameters * @param callback The callback */ createCustomPrebuiltEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; createCustomPrebuiltEntityRole(appId: string, versionId: string, entityId: string, entityRoleCreateObject: Models.EntityRoleCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ModelCreateCustomPrebuiltEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, entityRoleCreateObject, options }, createCustomPrebuiltEntityRoleOperationSpec, callback) as Promise<Models.ModelCreateCustomPrebuiltEntityRoleResponse>; } /** * @summary Get the explicit (exception) list of the pattern.any entity in a version of the * application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity id. * @param [options] The optional parameters * @returns Promise<Models.ModelGetExplicitListResponse> */ getExplicitList(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetExplicitListResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity id. * @param callback The callback */ getExplicitList(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.ExplicitListItem[]>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity id. * @param options The optional parameters * @param callback The callback */ getExplicitList(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ExplicitListItem[]>): void; getExplicitList(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ExplicitListItem[]>, callback?: msRest.ServiceCallback<Models.ExplicitListItem[]>): Promise<Models.ModelGetExplicitListResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, getExplicitListOperationSpec, callback) as Promise<Models.ModelGetExplicitListResponse>; } /** * @summary Add a new exception to the explicit list for the Pattern.Any entity in a version of the * application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param item The new explicit list item. * @param [options] The optional parameters * @returns Promise<Models.ModelAddExplicitListItemResponse> */ addExplicitListItem(appId: string, versionId: string, entityId: string, item: Models.ExplicitListItemCreateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelAddExplicitListItemResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param item The new explicit list item. * @param callback The callback */ addExplicitListItem(appId: string, versionId: string, entityId: string, item: Models.ExplicitListItemCreateObject, callback: msRest.ServiceCallback<number>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param item The new explicit list item. * @param options The optional parameters * @param callback The callback */ addExplicitListItem(appId: string, versionId: string, entityId: string, item: Models.ExplicitListItemCreateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<number>): void; addExplicitListItem(appId: string, versionId: string, entityId: string, item: Models.ExplicitListItemCreateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<number>, callback?: msRest.ServiceCallback<number>): Promise<Models.ModelAddExplicitListItemResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, item, options }, addExplicitListItemOperationSpec, callback) as Promise<Models.ModelAddExplicitListItemResponse>; } /** * @summary Gets information about a regular expression entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity model ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetRegexEntityEntityInfoResponse> */ getRegexEntityEntityInfo(appId: string, versionId: string, regexEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetRegexEntityEntityInfoResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity model ID. * @param callback The callback */ getRegexEntityEntityInfo(appId: string, versionId: string, regexEntityId: string, callback: msRest.ServiceCallback<Models.RegexEntityExtractor>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity model ID. * @param options The optional parameters * @param callback The callback */ getRegexEntityEntityInfo(appId: string, versionId: string, regexEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RegexEntityExtractor>): void; getRegexEntityEntityInfo(appId: string, versionId: string, regexEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RegexEntityExtractor>, callback?: msRest.ServiceCallback<Models.RegexEntityExtractor>): Promise<Models.ModelGetRegexEntityEntityInfoResponse> { return this.client.sendOperationRequest( { appId, versionId, regexEntityId, options }, getRegexEntityEntityInfoOperationSpec, callback) as Promise<Models.ModelGetRegexEntityEntityInfoResponse>; } /** * @summary Updates the regular expression entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity extractor ID. * @param regexEntityUpdateObject An object containing the new entity name and regex pattern. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateRegexEntityModelResponse> */ updateRegexEntityModel(appId: string, versionId: string, regexEntityId: string, regexEntityUpdateObject: Models.RegexModelUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateRegexEntityModelResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity extractor ID. * @param regexEntityUpdateObject An object containing the new entity name and regex pattern. * @param callback The callback */ updateRegexEntityModel(appId: string, versionId: string, regexEntityId: string, regexEntityUpdateObject: Models.RegexModelUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity extractor ID. * @param regexEntityUpdateObject An object containing the new entity name and regex pattern. * @param options The optional parameters * @param callback The callback */ updateRegexEntityModel(appId: string, versionId: string, regexEntityId: string, regexEntityUpdateObject: Models.RegexModelUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateRegexEntityModel(appId: string, versionId: string, regexEntityId: string, regexEntityUpdateObject: Models.RegexModelUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateRegexEntityModelResponse> { return this.client.sendOperationRequest( { appId, versionId, regexEntityId, regexEntityUpdateObject, options }, updateRegexEntityModelOperationSpec, callback) as Promise<Models.ModelUpdateRegexEntityModelResponse>; } /** * @summary Deletes a regular expression entity from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteRegexEntityModelResponse> */ deleteRegexEntityModel(appId: string, versionId: string, regexEntityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteRegexEntityModelResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity extractor ID. * @param callback The callback */ deleteRegexEntityModel(appId: string, versionId: string, regexEntityId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param regexEntityId The regular expression entity extractor ID. * @param options The optional parameters * @param callback The callback */ deleteRegexEntityModel(appId: string, versionId: string, regexEntityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteRegexEntityModel(appId: string, versionId: string, regexEntityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteRegexEntityModelResponse> { return this.client.sendOperationRequest( { appId, versionId, regexEntityId, options }, deleteRegexEntityModelOperationSpec, callback) as Promise<Models.ModelDeleteRegexEntityModelResponse>; } /** * @summary Gets information about the Pattern.Any model in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetPatternAnyEntityInfoResponse> */ getPatternAnyEntityInfo(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetPatternAnyEntityInfoResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param callback The callback */ getPatternAnyEntityInfo(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.PatternAnyEntityExtractor>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity extractor ID. * @param options The optional parameters * @param callback The callback */ getPatternAnyEntityInfo(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PatternAnyEntityExtractor>): void; getPatternAnyEntityInfo(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PatternAnyEntityExtractor>, callback?: msRest.ServiceCallback<Models.PatternAnyEntityExtractor>): Promise<Models.ModelGetPatternAnyEntityInfoResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, getPatternAnyEntityInfoOperationSpec, callback) as Promise<Models.ModelGetPatternAnyEntityInfoResponse>; } /** * @summary Updates the name and explicit (exception) list of a Pattern.Any entity model in a * version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param patternAnyUpdateObject An object containing the explicit list of the Pattern.Any entity. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdatePatternAnyEntityModelResponse> */ updatePatternAnyEntityModel(appId: string, versionId: string, entityId: string, patternAnyUpdateObject: Models.PatternAnyModelUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdatePatternAnyEntityModelResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param patternAnyUpdateObject An object containing the explicit list of the Pattern.Any entity. * @param callback The callback */ updatePatternAnyEntityModel(appId: string, versionId: string, entityId: string, patternAnyUpdateObject: Models.PatternAnyModelUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param patternAnyUpdateObject An object containing the explicit list of the Pattern.Any entity. * @param options The optional parameters * @param callback The callback */ updatePatternAnyEntityModel(appId: string, versionId: string, entityId: string, patternAnyUpdateObject: Models.PatternAnyModelUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updatePatternAnyEntityModel(appId: string, versionId: string, entityId: string, patternAnyUpdateObject: Models.PatternAnyModelUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdatePatternAnyEntityModelResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, patternAnyUpdateObject, options }, updatePatternAnyEntityModelOperationSpec, callback) as Promise<Models.ModelUpdatePatternAnyEntityModelResponse>; } /** * @summary Deletes a Pattern.Any entity extractor from a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param [options] The optional parameters * @returns Promise<Models.ModelDeletePatternAnyEntityModelResponse> */ deletePatternAnyEntityModel(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeletePatternAnyEntityModelResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param callback The callback */ deletePatternAnyEntityModel(appId: string, versionId: string, entityId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param options The optional parameters * @param callback The callback */ deletePatternAnyEntityModel(appId: string, versionId: string, entityId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deletePatternAnyEntityModel(appId: string, versionId: string, entityId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeletePatternAnyEntityModelResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, options }, deletePatternAnyEntityModelOperationSpec, callback) as Promise<Models.ModelDeletePatternAnyEntityModelResponse>; } /** * @summary Get one role for a given entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetEntityRoleResponse> */ getEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param callback The callback */ getEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.EntityRole>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param options The optional parameters * @param callback The callback */ getEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole>): void; getEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole>, callback?: msRest.ServiceCallback<Models.EntityRole>): Promise<Models.ModelGetEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, getEntityRoleOperationSpec, callback) as Promise<Models.ModelGetEntityRoleResponse>; } /** * @summary Update a role for a given entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateEntityRoleResponse> */ updateEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param callback The callback */ updateEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param options The optional parameters * @param callback The callback */ updateEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, entityRoleUpdateObject, options }, updateEntityRoleOperationSpec, callback) as Promise<Models.ModelUpdateEntityRoleResponse>; } /** * @summary Delete an entity role in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteEntityRoleResponse> */ deleteEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param callback The callback */ deleteEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param options The optional parameters * @param callback The callback */ deleteEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, deleteEntityRoleOperationSpec, callback) as Promise<Models.ModelDeleteEntityRoleResponse>; } /** * @summary Get one role for a given prebuilt entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetPrebuiltEntityRoleResponse> */ getPrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetPrebuiltEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param callback The callback */ getPrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.EntityRole>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param options The optional parameters * @param callback The callback */ getPrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole>): void; getPrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole>, callback?: msRest.ServiceCallback<Models.EntityRole>): Promise<Models.ModelGetPrebuiltEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, getPrebuiltEntityRoleOperationSpec, callback) as Promise<Models.ModelGetPrebuiltEntityRoleResponse>; } /** * @summary Update a role for a given prebuilt entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdatePrebuiltEntityRoleResponse> */ updatePrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdatePrebuiltEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param callback The callback */ updatePrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param options The optional parameters * @param callback The callback */ updatePrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updatePrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdatePrebuiltEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, entityRoleUpdateObject, options }, updatePrebuiltEntityRoleOperationSpec, callback) as Promise<Models.ModelUpdatePrebuiltEntityRoleResponse>; } /** * @summary Delete a role in a prebuilt entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param [options] The optional parameters * @returns Promise<Models.ModelDeletePrebuiltEntityRoleResponse> */ deletePrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeletePrebuiltEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param callback The callback */ deletePrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param options The optional parameters * @param callback The callback */ deletePrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deletePrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeletePrebuiltEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, deletePrebuiltEntityRoleOperationSpec, callback) as Promise<Models.ModelDeletePrebuiltEntityRoleResponse>; } /** * @summary Get one role for a given list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetClosedListEntityRoleResponse> */ getClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetClosedListEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param callback The callback */ getClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.EntityRole>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param options The optional parameters * @param callback The callback */ getClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole>): void; getClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole>, callback?: msRest.ServiceCallback<Models.EntityRole>): Promise<Models.ModelGetClosedListEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, getClosedListEntityRoleOperationSpec, callback) as Promise<Models.ModelGetClosedListEntityRoleResponse>; } /** * @summary Update a role for a given list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateClosedListEntityRoleResponse> */ updateClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateClosedListEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param callback The callback */ updateClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param options The optional parameters * @param callback The callback */ updateClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateClosedListEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, entityRoleUpdateObject, options }, updateClosedListEntityRoleOperationSpec, callback) as Promise<Models.ModelUpdateClosedListEntityRoleResponse>; } /** * @summary Delete a role for a given list entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteClosedListEntityRoleResponse> */ deleteClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteClosedListEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param callback The callback */ deleteClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param options The optional parameters * @param callback The callback */ deleteClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteClosedListEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteClosedListEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, deleteClosedListEntityRoleOperationSpec, callback) as Promise<Models.ModelDeleteClosedListEntityRoleResponse>; } /** * @summary Get one role for a given regular expression entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetRegexEntityRoleResponse> */ getRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetRegexEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param callback The callback */ getRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.EntityRole>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param options The optional parameters * @param callback The callback */ getRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole>): void; getRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole>, callback?: msRest.ServiceCallback<Models.EntityRole>): Promise<Models.ModelGetRegexEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, getRegexEntityRoleOperationSpec, callback) as Promise<Models.ModelGetRegexEntityRoleResponse>; } /** * @summary Update a role for a given regular expression entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateRegexEntityRoleResponse> */ updateRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateRegexEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param callback The callback */ updateRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param options The optional parameters * @param callback The callback */ updateRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateRegexEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, entityRoleUpdateObject, options }, updateRegexEntityRoleOperationSpec, callback) as Promise<Models.ModelUpdateRegexEntityRoleResponse>; } /** * @summary Delete a role for a given regular expression in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteRegexEntityRoleResponse> */ deleteRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteRegexEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param callback The callback */ deleteRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param options The optional parameters * @param callback The callback */ deleteRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteRegexEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteRegexEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, deleteRegexEntityRoleOperationSpec, callback) as Promise<Models.ModelDeleteRegexEntityRoleResponse>; } /** * @summary Get one role for a given composite entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId entity role ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetCompositeEntityRoleResponse> */ getCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetCompositeEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId entity role ID. * @param callback The callback */ getCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, callback: msRest.ServiceCallback<Models.EntityRole>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId entity role ID. * @param options The optional parameters * @param callback The callback */ getCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole>): void; getCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole>, callback?: msRest.ServiceCallback<Models.EntityRole>): Promise<Models.ModelGetCompositeEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, roleId, options }, getCompositeEntityRoleOperationSpec, callback) as Promise<Models.ModelGetCompositeEntityRoleResponse>; } /** * @summary Update a role for a given composite entity in a version of the application * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateCompositeEntityRoleResponse> */ updateCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateCompositeEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param callback The callback */ updateCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param options The optional parameters * @param callback The callback */ updateCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateCompositeEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, roleId, entityRoleUpdateObject, options }, updateCompositeEntityRoleOperationSpec, callback) as Promise<Models.ModelUpdateCompositeEntityRoleResponse>; } /** * @summary Delete a role for a given composite entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId The entity role Id. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteCompositeEntityRoleResponse> */ deleteCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteCompositeEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId The entity role Id. * @param callback The callback */ deleteCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param cEntityId The composite entity extractor ID. * @param roleId The entity role Id. * @param options The optional parameters * @param callback The callback */ deleteCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteCompositeEntityRole(appId: string, versionId: string, cEntityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteCompositeEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, cEntityId, roleId, options }, deleteCompositeEntityRoleOperationSpec, callback) as Promise<Models.ModelDeleteCompositeEntityRoleResponse>; } /** * @summary Get one role for a given Pattern.any entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetPatternAnyEntityRoleResponse> */ getPatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetPatternAnyEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param callback The callback */ getPatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.EntityRole>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param options The optional parameters * @param callback The callback */ getPatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole>): void; getPatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole>, callback?: msRest.ServiceCallback<Models.EntityRole>): Promise<Models.ModelGetPatternAnyEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, getPatternAnyEntityRoleOperationSpec, callback) as Promise<Models.ModelGetPatternAnyEntityRoleResponse>; } /** * @summary Update a role for a given Pattern.any entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdatePatternAnyEntityRoleResponse> */ updatePatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdatePatternAnyEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param callback The callback */ updatePatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param options The optional parameters * @param callback The callback */ updatePatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updatePatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdatePatternAnyEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, entityRoleUpdateObject, options }, updatePatternAnyEntityRoleOperationSpec, callback) as Promise<Models.ModelUpdatePatternAnyEntityRoleResponse>; } /** * @summary Delete a role for a given Pattern.any entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param [options] The optional parameters * @returns Promise<Models.ModelDeletePatternAnyEntityRoleResponse> */ deletePatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeletePatternAnyEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param callback The callback */ deletePatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param options The optional parameters * @param callback The callback */ deletePatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deletePatternAnyEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeletePatternAnyEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, deletePatternAnyEntityRoleOperationSpec, callback) as Promise<Models.ModelDeletePatternAnyEntityRoleResponse>; } /** * @summary Get one role for a given hierarchical entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId entity role ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetHierarchicalEntityRoleResponse> */ getHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetHierarchicalEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId entity role ID. * @param callback The callback */ getHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, callback: msRest.ServiceCallback<Models.EntityRole>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId entity role ID. * @param options The optional parameters * @param callback The callback */ getHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole>): void; getHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole>, callback?: msRest.ServiceCallback<Models.EntityRole>): Promise<Models.ModelGetHierarchicalEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, roleId, options }, getHierarchicalEntityRoleOperationSpec, callback) as Promise<Models.ModelGetHierarchicalEntityRoleResponse>; } /** * @summary Update a role for a given hierarchical entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateHierarchicalEntityRoleResponse> */ updateHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateHierarchicalEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param callback The callback */ updateHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param options The optional parameters * @param callback The callback */ updateHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateHierarchicalEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, roleId, entityRoleUpdateObject, options }, updateHierarchicalEntityRoleOperationSpec, callback) as Promise<Models.ModelUpdateHierarchicalEntityRoleResponse>; } /** * @summary Delete a role for a given hierarchical role in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId The entity role Id. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteHierarchicalEntityRoleResponse> */ deleteHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteHierarchicalEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId The entity role Id. * @param callback The callback */ deleteHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param hEntityId The hierarchical entity extractor ID. * @param roleId The entity role Id. * @param options The optional parameters * @param callback The callback */ deleteHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteHierarchicalEntityRole(appId: string, versionId: string, hEntityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteHierarchicalEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, hEntityId, roleId, options }, deleteHierarchicalEntityRoleOperationSpec, callback) as Promise<Models.ModelDeleteHierarchicalEntityRoleResponse>; } /** * @summary Get one role for a given prebuilt entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param [options] The optional parameters * @returns Promise<Models.ModelGetCustomEntityRoleResponse> */ getCustomEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetCustomEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param callback The callback */ getCustomEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.EntityRole>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId entity ID. * @param roleId entity role ID. * @param options The optional parameters * @param callback The callback */ getCustomEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EntityRole>): void; getCustomEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EntityRole>, callback?: msRest.ServiceCallback<Models.EntityRole>): Promise<Models.ModelGetCustomEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, getCustomEntityRoleOperationSpec, callback) as Promise<Models.ModelGetCustomEntityRoleResponse>; } /** * @summary Update a role for a given prebuilt entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateCustomPrebuiltEntityRoleResponse> */ updateCustomPrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateCustomPrebuiltEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param callback The callback */ updateCustomPrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role ID. * @param entityRoleUpdateObject The new entity role. * @param options The optional parameters * @param callback The callback */ updateCustomPrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateCustomPrebuiltEntityRole(appId: string, versionId: string, entityId: string, roleId: string, entityRoleUpdateObject: Models.EntityRoleUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateCustomPrebuiltEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, entityRoleUpdateObject, options }, updateCustomPrebuiltEntityRoleOperationSpec, callback) as Promise<Models.ModelUpdateCustomPrebuiltEntityRoleResponse>; } /** * @summary Delete a role for a given prebuilt entity in a version of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteCustomEntityRoleResponse> */ deleteCustomEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteCustomEntityRoleResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param callback The callback */ deleteCustomEntityRole(appId: string, versionId: string, entityId: string, roleId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The entity ID. * @param roleId The entity role Id. * @param options The optional parameters * @param callback The callback */ deleteCustomEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteCustomEntityRole(appId: string, versionId: string, entityId: string, roleId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteCustomEntityRoleResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, roleId, options }, deleteCustomEntityRoleOperationSpec, callback) as Promise<Models.ModelDeleteCustomEntityRoleResponse>; } /** * @summary Get the explicit (exception) list of the pattern.any entity in a version of the * application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity Id. * @param itemId The explicit list item Id. * @param [options] The optional parameters * @returns Promise<Models.ModelGetExplicitListItemResponse> */ getExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, options?: msRest.RequestOptionsBase): Promise<Models.ModelGetExplicitListItemResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity Id. * @param itemId The explicit list item Id. * @param callback The callback */ getExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, callback: msRest.ServiceCallback<Models.ExplicitListItem>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity Id. * @param itemId The explicit list item Id. * @param options The optional parameters * @param callback The callback */ getExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ExplicitListItem>): void; getExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ExplicitListItem>, callback?: msRest.ServiceCallback<Models.ExplicitListItem>): Promise<Models.ModelGetExplicitListItemResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, itemId, options }, getExplicitListItemOperationSpec, callback) as Promise<Models.ModelGetExplicitListItemResponse>; } /** * @summary Updates an explicit (exception) list item for a Pattern.Any entity in a version of the * application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param itemId The explicit list item ID. * @param item The new explicit list item. * @param [options] The optional parameters * @returns Promise<Models.ModelUpdateExplicitListItemResponse> */ updateExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, item: Models.ExplicitListItemUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.ModelUpdateExplicitListItemResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param itemId The explicit list item ID. * @param item The new explicit list item. * @param callback The callback */ updateExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, item: Models.ExplicitListItemUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The Pattern.Any entity extractor ID. * @param itemId The explicit list item ID. * @param item The new explicit list item. * @param options The optional parameters * @param callback The callback */ updateExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, item: Models.ExplicitListItemUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; updateExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, item: Models.ExplicitListItemUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelUpdateExplicitListItemResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, itemId, item, options }, updateExplicitListItemOperationSpec, callback) as Promise<Models.ModelUpdateExplicitListItemResponse>; } /** * @summary Delete an item from the explicit (exception) list for a Pattern.any entity in a version * of the application. * @param appId The application ID. * @param versionId The version ID. * @param entityId The pattern.any entity id. * @param itemId The explicit list item which will be deleted. * @param [options] The optional parameters * @returns Promise<Models.ModelDeleteExplicitListItemResponse> */ deleteExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, options?: msRest.RequestOptionsBase): Promise<Models.ModelDeleteExplicitListItemResponse>; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The pattern.any entity id. * @param itemId The explicit list item which will be deleted. * @param callback The callback */ deleteExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, callback: msRest.ServiceCallback<Models.OperationStatus>): void; /** * @param appId The application ID. * @param versionId The version ID. * @param entityId The pattern.any entity id. * @param itemId The explicit list item which will be deleted. * @param options The optional parameters * @param callback The callback */ deleteExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void; deleteExplicitListItem(appId: string, versionId: string, entityId: string, itemId: number, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.ModelDeleteExplicitListItemResponse> { return this.client.sendOperationRequest( { appId, versionId, entityId, itemId, options }, deleteExplicitListItemOperationSpec, callback) as Promise<Models.ModelDeleteExplicitListItemResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const addIntentOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/intents", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "intentCreateObject", mapper: { ...Mappers.ModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listIntentsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/intents", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "IntentClassifier" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addEntityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/entities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "modelCreateObject", mapper: { ...Mappers.ModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listEntitiesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/entities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addHierarchicalEntityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/hierarchicalentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "hierarchicalModelCreateObject", mapper: { ...Mappers.HierarchicalEntityModel, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listHierarchicalEntitiesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/hierarchicalentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "HierarchicalEntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addCompositeEntityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/compositeentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "compositeModelCreateObject", mapper: { ...Mappers.CompositeEntityModel, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listCompositeEntitiesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/compositeentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "CompositeEntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listClosedListsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/closedlists", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "ClosedListEntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addClosedListOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/closedlists", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "closedListModelCreateObject", mapper: { ...Mappers.ClosedListModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addPrebuiltOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/prebuilts", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "prebuiltExtractorNames", mapper: { required: true, serializedName: "prebuiltExtractorNames", type: { name: "Sequence", element: { type: { name: "String" } } } } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "PrebuiltEntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listPrebuiltsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/prebuilts", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "PrebuiltEntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listPrebuiltEntitiesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/listprebuilts", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "AvailablePrebuiltEntityModel" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listModelsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/models", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "ModelInfoResponse" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const examplesMethodOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/models/{modelId}/examples", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.modelId ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "LabelTextObject" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getIntentOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/intents/{intentId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.intentId ], responses: { 200: { bodyMapper: Mappers.IntentClassifier }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateIntentOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/intents/{intentId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.intentId ], requestBody: { parameterPath: "modelUpdateObject", mapper: { ...Mappers.ModelUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteIntentOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/intents/{intentId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.intentId ], queryParameters: [ Parameters.deleteUtterances ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getEntityOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/entities/{entityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: Mappers.EntityExtractor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateEntityOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/entities/{entityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "modelUpdateObject", mapper: { ...Mappers.ModelUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteEntityOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/entities/{entityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getHierarchicalEntityOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId ], responses: { 200: { bodyMapper: Mappers.HierarchicalEntityExtractor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateHierarchicalEntityOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId ], requestBody: { parameterPath: "hierarchicalModelUpdateObject", mapper: { ...Mappers.HierarchicalEntityModel, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteHierarchicalEntityOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getCompositeEntityOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId ], responses: { 200: { bodyMapper: Mappers.CompositeEntityExtractor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateCompositeEntityOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId ], requestBody: { parameterPath: "compositeModelUpdateObject", mapper: { ...Mappers.CompositeEntityModel, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteCompositeEntityOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getClosedListOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/closedlists/{clEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.clEntityId ], responses: { 200: { bodyMapper: Mappers.ClosedListEntityExtractor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateClosedListOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/closedlists/{clEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.clEntityId ], requestBody: { parameterPath: "closedListModelUpdateObject", mapper: { ...Mappers.ClosedListModelUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const patchClosedListOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "apps/{appId}/versions/{versionId}/closedlists/{clEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.clEntityId ], requestBody: { parameterPath: "closedListModelPatchObject", mapper: { ...Mappers.ClosedListModelPatchObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteClosedListOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/closedlists/{clEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.clEntityId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getPrebuiltOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/prebuilts/{prebuiltId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.prebuiltId ], responses: { 200: { bodyMapper: Mappers.PrebuiltEntityExtractor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deletePrebuiltOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/prebuilts/{prebuiltId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.prebuiltId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteSubListOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/closedlists/{clEntityId}/sublists/{subListId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.clEntityId, Parameters.subListId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateSubListOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/closedlists/{clEntityId}/sublists/{subListId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.clEntityId, Parameters.subListId ], requestBody: { parameterPath: "wordListBaseUpdateObject", mapper: { ...Mappers.WordListBaseUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listIntentSuggestionsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/intents/{intentId}/suggest", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.intentId ], queryParameters: [ Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "IntentsSuggestionExample" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listEntitySuggestionsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/entities/{entityId}/suggest", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], queryParameters: [ Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntitiesSuggestionExample" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addSubListOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/closedlists/{clEntityId}/sublists", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.clEntityId ], requestBody: { parameterPath: "wordListCreateObject", mapper: { ...Mappers.WordListObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Number" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addCustomPrebuiltDomainOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/customprebuiltdomains", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "prebuiltDomainObject", mapper: { ...Mappers.PrebuiltDomainCreateBaseObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Uuid" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addCustomPrebuiltIntentOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/customprebuiltintents", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "prebuiltDomainModelCreateObject", mapper: { ...Mappers.PrebuiltDomainModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listCustomPrebuiltIntentsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/customprebuiltintents", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "IntentClassifier" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addCustomPrebuiltEntityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/customprebuiltentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "prebuiltDomainModelCreateObject", mapper: { ...Mappers.PrebuiltDomainModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listCustomPrebuiltEntitiesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/customprebuiltentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listCustomPrebuiltModelsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/customprebuiltmodels", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "CustomPrebuiltModel" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteCustomPrebuiltDomainOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/customprebuiltdomains/{domainName}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.domainName ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getHierarchicalEntityChildOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/children/{hChildId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId, Parameters.hChildId ], responses: { 200: { bodyMapper: Mappers.HierarchicalChildEntity }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateHierarchicalEntityChildOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/children/{hChildId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId, Parameters.hChildId ], requestBody: { parameterPath: "hierarchicalChildModelUpdateObject", mapper: { ...Mappers.HierarchicalChildModelUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteHierarchicalEntityChildOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/children/{hChildId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId, Parameters.hChildId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addHierarchicalEntityChildOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/children", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId ], requestBody: { parameterPath: "hierarchicalChildModelCreateObject", mapper: { ...Mappers.HierarchicalChildModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addCompositeEntityChildOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}/children", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId ], requestBody: { parameterPath: "compositeChildModelCreateObject", mapper: { ...Mappers.CompositeChildModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteCompositeEntityChildOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}/children/{cChildId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId, Parameters.cChildId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listRegexEntityInfosOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/regexentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "RegexEntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createRegexEntityModelOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/regexentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "regexEntityExtractorCreateObj", mapper: { ...Mappers.RegexModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listPatternAnyEntityInfosOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/patternanyentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], queryParameters: [ Parameters.skip, Parameters.take ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "PatternAnyEntityExtractor" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createPatternAnyEntityModelOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/patternanyentities", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0 ], requestBody: { parameterPath: "extractorCreateObject", mapper: { ...Mappers.PatternAnyModelCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listEntityRolesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/entities/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRole" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/entities/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "entityRoleCreateObject", mapper: { ...Mappers.EntityRoleCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listPrebuiltEntityRolesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/prebuilts/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRole" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createPrebuiltEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/prebuilts/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "entityRoleCreateObject", mapper: { ...Mappers.EntityRoleCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listClosedListEntityRolesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/closedlists/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRole" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createClosedListEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/closedlists/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "entityRoleCreateObject", mapper: { ...Mappers.EntityRoleCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listRegexEntityRolesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/regexentities/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRole" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createRegexEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/regexentities/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "entityRoleCreateObject", mapper: { ...Mappers.EntityRoleCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listCompositeEntityRolesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRole" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createCompositeEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId ], requestBody: { parameterPath: "entityRoleCreateObject", mapper: { ...Mappers.EntityRoleCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listPatternAnyEntityRolesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRole" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createPatternAnyEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "entityRoleCreateObject", mapper: { ...Mappers.EntityRoleCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listHierarchicalEntityRolesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRole" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createHierarchicalEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId ], requestBody: { parameterPath: "entityRoleCreateObject", mapper: { ...Mappers.EntityRoleCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listCustomPrebuiltEntityRolesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/customprebuiltentities/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRole" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createCustomPrebuiltEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/customprebuiltentities/{entityId}/roles", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "entityRoleCreateObject", mapper: { ...Mappers.EntityRoleCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Uuid" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getExplicitListOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/explicitlist", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "ExplicitListItem" } } } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const addExplicitListItemOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/explicitlist", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "item", mapper: { ...Mappers.ExplicitListItemCreateObject, required: true } }, responses: { 201: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Number" } } }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getRegexEntityEntityInfoOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/regexentities/{regexEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.regexEntityId ], responses: { 200: { bodyMapper: Mappers.RegexEntityExtractor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateRegexEntityModelOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/regexentities/{regexEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.regexEntityId ], requestBody: { parameterPath: "regexEntityUpdateObject", mapper: { ...Mappers.RegexModelUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteRegexEntityModelOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/regexentities/{regexEntityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.regexEntityId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getPatternAnyEntityInfoOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: Mappers.PatternAnyEntityExtractor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updatePatternAnyEntityModelOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], requestBody: { parameterPath: "patternAnyUpdateObject", mapper: { ...Mappers.PatternAnyModelUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deletePatternAnyEntityModelOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/entities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.EntityRole }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/entities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], requestBody: { parameterPath: "entityRoleUpdateObject", mapper: { ...Mappers.EntityRoleUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/entities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getPrebuiltEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/prebuilts/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.EntityRole }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updatePrebuiltEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/prebuilts/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], requestBody: { parameterPath: "entityRoleUpdateObject", mapper: { ...Mappers.EntityRoleUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deletePrebuiltEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/prebuilts/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getClosedListEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/closedlists/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.EntityRole }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateClosedListEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/closedlists/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], requestBody: { parameterPath: "entityRoleUpdateObject", mapper: { ...Mappers.EntityRoleUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteClosedListEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/closedlists/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getRegexEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/regexentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.EntityRole }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateRegexEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/regexentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], requestBody: { parameterPath: "entityRoleUpdateObject", mapper: { ...Mappers.EntityRoleUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteRegexEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/regexentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getCompositeEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.EntityRole }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateCompositeEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId, Parameters.roleId ], requestBody: { parameterPath: "entityRoleUpdateObject", mapper: { ...Mappers.EntityRoleUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteCompositeEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/compositeentities/{cEntityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.cEntityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getPatternAnyEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.EntityRole }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updatePatternAnyEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], requestBody: { parameterPath: "entityRoleUpdateObject", mapper: { ...Mappers.EntityRoleUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deletePatternAnyEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getHierarchicalEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.EntityRole }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateHierarchicalEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId, Parameters.roleId ], requestBody: { parameterPath: "entityRoleUpdateObject", mapper: { ...Mappers.EntityRoleUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteHierarchicalEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/hierarchicalentities/{hEntityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.hEntityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getCustomEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/customprebuiltentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.EntityRole }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateCustomPrebuiltEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/customprebuiltentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], requestBody: { parameterPath: "entityRoleUpdateObject", mapper: { ...Mappers.EntityRoleUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteCustomEntityRoleOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/customprebuiltentities/{entityId}/roles/{roleId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.roleId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getExplicitListItemOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/explicitlist/{itemId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.itemId ], responses: { 200: { bodyMapper: Mappers.ExplicitListItem }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateExplicitListItemOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/explicitlist/{itemId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.itemId ], requestBody: { parameterPath: "item", mapper: { ...Mappers.ExplicitListItemUpdateObject, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteExplicitListItemOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "apps/{appId}/versions/{versionId}/patternanyentities/{entityId}/explicitlist/{itemId}", urlParameters: [ Parameters.endpoint, Parameters.appId, Parameters.versionId0, Parameters.entityId, Parameters.itemId ], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import { Observable, Subject, } from "rxjs"; import config from "../../../config"; import { formatError, ICustomError } from "../../../errors"; import Manifest, { Adaptation, ISegment, Period, Representation, } from "../../../manifest"; import { ISegmentLoadingProgressInformation, ISegmentParserParsedInitSegment, ISegmentParserParsedSegment, ISegmentPipeline, } from "../../../transports"; import arrayIncludes from "../../../utils/array_includes"; import idGenerator from "../../../utils/id_generator"; import InitializationSegmentCache from "../../../utils/initialization_segment_cache"; import objectAssign from "../../../utils/object_assign"; import TaskCanceller, { CancellationSignal, } from "../../../utils/task_canceller"; import { IABRMetricsEvent, IABRRequestBeginEvent, IABRRequestEndEvent, IABRRequestProgressEvent, } from "../../abr"; import { IBufferType } from "../../segment_buffers"; import errorSelector from "../utils/error_selector"; import { tryURLsWithBackoff } from "../utils/try_urls_with_backoff"; const { DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR, DEFAULT_MAX_REQUESTS_RETRY_ON_OFFLINE, INITIAL_BACKOFF_DELAY_BASE, MAX_BACKOFF_DELAY_BASE } = config; const generateRequestID = idGenerator(); /** * Create a function which will fetch and parse segments. * @param {string} bufferType * @param {Object} transport * @param {Subject} requests$ * @param {Object} options * @returns {Function} */ export default function createSegmentFetcher< LoadedFormat, TSegmentDataType, >( bufferType : IBufferType, pipeline : ISegmentPipeline<LoadedFormat, TSegmentDataType>, requests$ : Subject<IABRMetricsEvent | IABRRequestBeginEvent | IABRRequestProgressEvent | IABRRequestEndEvent>, options : ISegmentFetcherOptions ) : ISegmentFetcher<TSegmentDataType> { /** * Cache audio and video initialization segments. * This allows to avoid doing too many requests for what are usually very * small files. */ const cache = arrayIncludes(["audio", "video"], bufferType) ? new InitializationSegmentCache<LoadedFormat>() : undefined; const { loadSegment, parseSegment } = pipeline; /** * Fetch a specific segment. * * This function returns an Observable which will fetch the segment on * subscription. * This Observable will emit various events during that request lifecycle and * throw if the segment request(s) (including potential retries) fail. * * The Observable will automatically complete once no events are left to be * sent. * @param {Object} content * @returns {Observable} */ return function fetchSegment( content : ISegmentLoaderContent ) : Observable<ISegmentFetcherEvent<TSegmentDataType>> { const { segment } = content; return new Observable((obs) => { // Retrieve from cache if it exists const cached = cache !== undefined ? cache.get(content) : null; if (cached !== null) { obs.next({ type: "chunk" as const, parse: generateParserFunction(cached, false) }); obs.next({ type: "chunk-complete" as const }); obs.complete(); return undefined; } const id = generateRequestID(); requests$.next({ type: "requestBegin", value: { duration: segment.duration, time: segment.time, requestTimestamp: performance.now(), id } }); const canceller = new TaskCanceller(); let hasRequestEnded = false; const loaderCallbacks = { /** * Callback called when the segment loader has progress information on * the request. * @param {Object} info */ onProgress(info : ISegmentLoadingProgressInformation) : void { if (info.totalSize !== undefined && info.size < info.totalSize) { requests$.next({ type: "progress", value: { duration: info.duration, size: info.size, totalSize: info.totalSize, timestamp: performance.now(), id } }); } }, /** * Callback called when the segment is communicated by the loader * through decodable sub-segment(s) called chunk(s), with a chunk in * argument. * @param {*} chunkData */ onNewChunk(chunkData : LoadedFormat) : void { obs.next({ type: "chunk" as const, parse: generateParserFunction(chunkData, true) }); }, }; tryURLsWithBackoff(segment.mediaURLs ?? [null], callLoaderWithUrl, objectAssign({ onRetry }, options), canceller.signal) .then((res) => { if (res.resultType === "segment-loaded") { const loadedData = res.resultData.responseData; if (cache !== undefined) { cache.add(content, res.resultData.responseData); } obs.next({ type: "chunk" as const, parse: generateParserFunction(loadedData, false) }); } else if (res.resultType === "segment-created") { obs.next({ type: "chunk" as const, parse: generateParserFunction(res.resultData, false) }); } hasRequestEnded = true; obs.next({ type: "chunk-complete" as const }); if ((res.resultType === "segment-loaded" || res.resultType === "chunk-complete") && res.resultData.size !== undefined && res.resultData.duration !== undefined) { requests$.next({ type: "metrics", value: { size: res.resultData.size, duration: res.resultData.duration, content } }); } if (!canceller.isUsed) { // The current Observable could have been canceled as a result of one // of the previous `next` calls. In that case, we don't want to send // a "requestEnd" again as it has already been sent on cancellation. // // Note that we only perform this check for `"requestEnd"` on // purpose. Observable's events should have been ignored by RxJS if // the Observable has already been canceled and we don't care if // `"metrics"` is sent there. requests$.next({ type: "requestEnd", value: { id } }); } obs.complete(); }) .catch((err) => { hasRequestEnded = true; obs.error(errorSelector(err)); }); return () => { if (!hasRequestEnded) { canceller.cancel(); requests$.next({ type: "requestEnd", value: { id } }); } }; /** * Call a segment loader for the given URL with the right arguments. * @param {string|null} url * @param {Object} cancellationSignal * @returns {Promise} */ function callLoaderWithUrl( url : string | null, cancellationSignal: CancellationSignal ) { return loadSegment(url, content, cancellationSignal, loaderCallbacks); } /** * Generate function allowing to parse a loaded segment. * @param {*} data * @param {Boolean} isChunked * @returns {Function} */ function generateParserFunction(data : LoadedFormat, isChunked : boolean) { return function parse(initTimescale? : number) : ISegmentParserParsedInitSegment<TSegmentDataType> | ISegmentParserParsedSegment<TSegmentDataType> { const loaded = { data, isChunked }; try { return parseSegment(loaded, content, initTimescale); } catch (error) { throw formatError(error, { defaultCode: "PIPELINE_PARSE_ERROR", defaultReason: "Unknown parsing error" }); } }; } /** * Function called when the function request is retried. * @param {*} err */ function onRetry(err: unknown) : void { obs.next({ type: "warning" as const, value: errorSelector(err) }); } }); }; } export type ISegmentFetcher<TSegmentDataType> = (content : ISegmentLoaderContent) => Observable<ISegmentFetcherEvent<TSegmentDataType>>; /** Event sent by the SegmentFetcher when fetching a segment. */ export type ISegmentFetcherEvent<TSegmentDataType> = ISegmentFetcherChunkCompleteEvent | ISegmentFetcherChunkEvent<TSegmentDataType> | ISegmentFetcherWarning; /** * Event sent when a new "chunk" of the segment is available. * A segment can contain n chunk(s) for n >= 0. */ export interface ISegmentFetcherChunkEvent<TSegmentDataType> { type : "chunk"; /** Parse the downloaded chunk. */ /** * Parse the downloaded chunk. * * Take in argument the timescale value that might have been obtained by * parsing an initialization segment from the same Representation. * Can be left to `undefined` if unknown or inexistant, segment parsers should * be resilient and still work without that information. * * @param {number} initTimescale * @returns {Object} */ parse(initTimescale? : number) : ISegmentParserParsedInitSegment<TSegmentDataType> | ISegmentParserParsedSegment<TSegmentDataType>; } /** * Event sent when all "chunk" of the segments have been communicated through * `ISegmentFetcherChunkEvent` events. */ export interface ISegmentFetcherChunkCompleteEvent { type: "chunk-complete" } /** Content used by the segment loader as a context to load a new segment. */ export interface ISegmentLoaderContent { manifest : Manifest; period : Period; adaptation : Adaptation; representation : Representation; segment : ISegment; } /** An Error happened while loading (usually a request error). */ export interface ISegmentFetcherWarning { type : "warning"; value : ICustomError; } export interface ISegmentFetcherOptions { /** * Initial delay to wait if a request fails before making a new request, in * milliseconds. */ baseDelay : number; /** * Maximum delay to wait if a request fails before making a new request, in * milliseconds. */ maxDelay : number; /** * Maximum number of retries to perform on "regular" errors (e.g. due to HTTP * status, integrity errors, timeouts...). */ maxRetryRegular : number; /** * Maximum number of retries to perform when it appears that the user is * currently offline. */ maxRetryOffline : number; } /** * @param {string} bufferType * @param {Object} * @returns {Object} */ export function getSegmentFetcherOptions( bufferType : string, { maxRetryRegular, maxRetryOffline, lowLatencyMode } : { maxRetryRegular? : number; maxRetryOffline? : number; lowLatencyMode : boolean; } ) : ISegmentFetcherOptions { return { maxRetryRegular: bufferType === "image" ? 0 : maxRetryRegular ?? DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR, maxRetryOffline: maxRetryOffline ?? DEFAULT_MAX_REQUESTS_RETRY_ON_OFFLINE, baseDelay: lowLatencyMode ? INITIAL_BACKOFF_DELAY_BASE.LOW_LATENCY : INITIAL_BACKOFF_DELAY_BASE.REGULAR, maxDelay: lowLatencyMode ? MAX_BACKOFF_DELAY_BASE.LOW_LATENCY : MAX_BACKOFF_DELAY_BASE.REGULAR }; }
the_stack
import type { Point, SimpleBBox } from '@antv/g-canvas'; import { isEmpty } from 'lodash'; import { CellTypes, HORIZONTAL_RESIZE_AREA_KEY_PRE, KEY_GROUP_COL_RESIZE_AREA, ResizeAreaEffect, ResizeDirectionType, S2Event, } from '../common/constant'; import { CellBorderPosition } from '../common/interface'; import type { DefaultCellTheme, IconTheme, TextTheme, } from '../common/interface'; import type { AreaRange } from '../common/interface/scroll'; import type { ColHeaderConfig } from '../facet/header/col'; import { adjustColHeaderScrollingTextPosition, adjustColHeaderScrollingViewport, getBorderPositionAndStyle, getTextAndFollowingIconPosition, getTextAreaRange, } from '../utils/cell/cell'; import { renderIcon, renderLine, renderRect } from '../utils/g-renders'; import { isLastColumnAfterHidden } from '../utils/hide-columns'; import { getOrCreateResizeAreaGroupById, getResizeAreaAttrs, shouldAddResizeArea, } from '../utils/interaction/resize'; import { isEqualDisplaySiblingNodeId } from './../utils/hide-columns'; import { HeaderCell } from './header-cell'; export class ColCell extends HeaderCell { protected declare headerConfig: ColHeaderConfig; /** 文字区域(含icon)绘制起始坐标 */ protected textAreaPosition: Point; public get cellType() { return CellTypes.COL_CELL; } protected initCell() { super.initCell(); // 1、draw rect background this.drawBackgroundShape(); // interactive background shape this.drawInteractiveBgShape(); // draw text this.drawTextShape(); // draw action icons this.drawActionIcons(); // draw borders this.drawBorders(); // draw resize ares this.drawResizeArea(); this.addExpandColumnIconShapes(); this.update(); } protected drawBackgroundShape() { const { backgroundColor, backgroundColorOpacity } = this.getStyle().cell; this.backgroundShape = renderRect(this, { ...this.getCellArea(), fill: backgroundColor, fillOpacity: backgroundColorOpacity, }); } // 交互使用的背景色 protected drawInteractiveBgShape() { this.stateShapes.set( 'interactiveBgShape', renderRect( this, { ...this.getCellArea(), }, { visible: false, }, ), ); } protected getTextStyle(): TextTheme { const { isLeaf, isTotals } = this.meta; const { text, bolderText, measureText } = this.getStyle(); if (this.isMeasureField()) { return measureText || text; } if (isTotals || !isLeaf) { return bolderText; } return text; } protected getMaxTextWidth(): number { const { width } = this.getContentArea(); return width - this.getActionIconsWidth(); } protected getIconPosition(): Point { const { isLeaf } = this.meta; const iconStyle = this.getIconStyle(); if (isLeaf) { return super.getIconPosition(this.getActionIconsCount()); } const position = this.textAreaPosition; const totalSpace = this.actualTextWidth + this.getActionIconsWidth() - iconStyle.margin.right; const startX = position.x - totalSpace / 2; return { x: startX + this.actualTextWidth + iconStyle.margin.left, y: position.y - iconStyle.size / 2, }; } protected getTextPosition(): Point { const { isLeaf } = this.meta; const { width, scrollContainsRowHeader, cornerWidth, scrollX } = this.headerConfig; const textStyle = this.getTextStyle(); const contentBox = this.getContentArea(); const iconStyle = this.getIconStyle(); if (isLeaf) { return getTextAndFollowingIconPosition( contentBox, textStyle, this.actualTextWidth, iconStyle, this.getActionIconsCount(), ).text; } /** * p(x, y) * +----------------------+ x * | +---------------> * | viewport | |ColCell | * | |-|---------+ * +--------------------|-+ * | * y | * v * * 将 viewport 坐标(p)映射到 col header 的坐标体系中,简化计算逻辑 * */ const viewport: AreaRange = { start: scrollX - (scrollContainsRowHeader ? cornerWidth : 0), width: width + (scrollContainsRowHeader ? cornerWidth : 0), }; const { textAlign } = this.getTextStyle(); const adjustedViewport = adjustColHeaderScrollingViewport( viewport, textAlign, this.getStyle().cell?.padding, ); const iconCount = this.getActionIconsCount(); const textAndIconSpace = this.actualTextWidth + this.getActionIconsWidth() - (iconCount ? iconStyle.margin.right : 0); const textAreaRange = getTextAreaRange( adjustedViewport, { start: contentBox.x, width: contentBox.width }, textAndIconSpace, // icon position 默认为 right ); // textAreaRange.start 是以文字样式为 center 计算出的文字绘制点 // 此处按实际样式(left or right)调整 const startX = adjustColHeaderScrollingTextPosition( textAreaRange.start, textAreaRange.width - textAndIconSpace, textAlign, ); const textY = contentBox.y + contentBox.height / 2; this.textAreaPosition = { x: startX, y: textY }; return { x: startX - textAndIconSpace / 2 + this.actualTextWidth / 2, y: textY, }; } protected getActionIconsWidth() { const { size, margin } = this.getStyle().icon; const iconCount = this.getActionIconsCount(); return (size + margin.left) * iconCount + iconCount > 0 ? margin.right : 0; } protected getColResizeAreaKey() { return this.meta.key; } protected getColResizeArea() { return getOrCreateResizeAreaGroupById( this.spreadsheet, KEY_GROUP_COL_RESIZE_AREA, ); } protected getHorizontalResizeAreaName() { return `${HORIZONTAL_RESIZE_AREA_KEY_PRE}${this.meta.key}`; } protected drawHorizontalResizeArea() { if (!this.shouldDrawResizeAreaByType('colCellVertical')) { return; } const { cornerWidth, viewportWidth: headerWidth } = this.headerConfig; const { y, height } = this.meta; const resizeStyle = this.getResizeAreaStyle(); const resizeArea = this.getColResizeArea(); const resizeAreaName = this.getHorizontalResizeAreaName(); const existedHorizontalResizeArea = resizeArea.find( (element) => element.attrs.name === resizeAreaName, ); // 如果已经绘制当前列高调整热区热区,则不再绘制 if (existedHorizontalResizeArea) { return; } const resizeAreaWidth = cornerWidth + headerWidth; // 列高调整热区 resizeArea.addShape('rect', { attrs: { ...getResizeAreaAttrs({ theme: resizeStyle, type: ResizeDirectionType.Vertical, id: this.getColResizeAreaKey(), effect: ResizeAreaEffect.Field, offsetX: 0, offsetY: y, width: resizeAreaWidth, height, }), name: resizeAreaName, x: 0, y: y + height - resizeStyle.size / 2, width: resizeAreaWidth, }, }); } protected shouldAddVerticalResizeArea() { const { x, y, width, height } = this.meta; const { scrollX, scrollY, scrollContainsRowHeader, cornerWidth, height: headerHeight, width: headerWidth, } = this.headerConfig; const resizeStyle = this.getResizeAreaStyle(); const resizeAreaBBox = { x: x + width - resizeStyle.size / 2, y, width: resizeStyle.size, height, }; const resizeClipAreaBBox = { x: scrollContainsRowHeader ? -cornerWidth : 0, y: 0, width: scrollContainsRowHeader ? cornerWidth + headerWidth : headerWidth, height: headerHeight, }; return shouldAddResizeArea(resizeAreaBBox, resizeClipAreaBBox, { scrollX, scrollY, }); } protected getVerticalResizeAreaOffset() { const { x, y } = this.meta; const { scrollX, position } = this.headerConfig; return { x: position.x + x - scrollX, y: position.y + y, }; } protected drawVerticalResizeArea() { if ( !this.meta.isLeaf || !this.shouldDrawResizeAreaByType('colCellHorizontal') ) { return; } const { label, width, height, parent } = this.meta; const resizeStyle = this.getResizeAreaStyle(); const resizeArea = this.getColResizeArea(); if (!this.shouldAddVerticalResizeArea()) { return; } const { x: offsetX, y: offsetY } = this.getVerticalResizeAreaOffset(); // 列宽调整热区 // 基准线是根据container坐标来的,因此把热区画在container resizeArea.addShape('rect', { attrs: { ...getResizeAreaAttrs({ theme: resizeStyle, type: ResizeDirectionType.Horizontal, effect: ResizeAreaEffect.Cell, id: parent.isTotals ? '' : label, offsetX, offsetY, width, height, }), x: offsetX + width - resizeStyle.size / 2, y: offsetY, height, }, }); } // 绘制热区 private drawResizeArea() { this.drawHorizontalResizeArea(); this.drawVerticalResizeArea(); } protected drawHorizontalBorder() { const { position, style } = getBorderPositionAndStyle( CellBorderPosition.TOP, this.meta as SimpleBBox, this.theme.colCell.cell, ); renderLine(this, position, style); } protected drawVerticalBorder(dir: CellBorderPosition) { const { position, style } = getBorderPositionAndStyle( dir, this.meta as SimpleBBox, this.theme.colCell.cell, ); renderLine(this, position, style); } protected drawBorders() { const { options, isTableMode } = this.spreadsheet; if ( this.meta.colIndex === 0 && isTableMode() && !options.showSeriesNumber ) { this.drawVerticalBorder(CellBorderPosition.LEFT); } this.drawHorizontalBorder(); this.drawVerticalBorder(CellBorderPosition.RIGHT); } protected hasHiddenColumnCell() { const { interaction: { hiddenColumnFields = [] }, tooltip: { operation }, } = this.spreadsheet.options; const hiddenColumnsDetail = this.spreadsheet.store.get( 'hiddenColumnsDetail', [], ); if ( isEmpty(hiddenColumnsDetail) || isEmpty(hiddenColumnFields) || !operation.hiddenColumns ) { return false; } return !!hiddenColumnsDetail.find((column) => isEqualDisplaySiblingNodeId(column?.displaySiblingNode, this.meta.id), ); } private getExpandIconTheme(): IconTheme { const themeCfg = this.getStyle() as DefaultCellTheme; return themeCfg.icon; } private addExpandColumnSplitLine() { const { x, y, width, height } = this.meta; const { horizontalBorderColor, horizontalBorderWidth, horizontalBorderColorOpacity, } = this.theme.splitLine; const lineX = this.isLastColumn() ? x + width - horizontalBorderWidth : x; renderLine( this, { x1: lineX, y1: y, x2: lineX, y2: y + height, }, { stroke: horizontalBorderColor, lineWidth: horizontalBorderWidth, strokeOpacity: horizontalBorderColorOpacity, }, ); } private addExpandColumnIconShapes() { if (!this.hasHiddenColumnCell()) { return; } this.addExpandColumnSplitLine(); this.addExpandColumnIcon(); } private addExpandColumnIcon() { const iconConfig = this.getExpandColumnIconConfig(); const icon = renderIcon(this, { ...iconConfig, name: 'ExpandColIcon', cursor: 'pointer', }); icon.on('click', () => { this.spreadsheet.emit(S2Event.LAYOUT_COLS_EXPANDED, this.meta); }); } // 在隐藏的下一个兄弟节点的起始坐标显示隐藏提示线和展开按钮, 如果是尾元素, 则显示在前一个兄弟节点的结束坐标 private getExpandColumnIconConfig() { const { size } = this.getExpandIconTheme(); const { x, y, width, height } = this.getCellArea(); const baseIconX = x - size; const iconX = this.isLastColumn() ? baseIconX + width : baseIconX; const iconY = y + height / 2 - size / 2; return { x: iconX, y: iconY, width: size * 2, height: size, }; } private isLastColumn() { return isLastColumnAfterHidden(this.spreadsheet, this.meta.id); } }
the_stack
import "@babylonjs/core/Debug/debugLayer"; import "@babylonjs/inspector"; import "@babylonjs/loaders/glTF"; import { Engine, Scene, ArcRotateCamera, Vector3, HemisphericLight, Mesh, MeshBuilder, FreeCamera, Color4, StandardMaterial, Color3, PointLight, ShadowGenerator, Quaternion, Matrix, SceneLoader } from "@babylonjs/core"; import { AdvancedDynamicTexture, Button, Control } from "@babylonjs/gui"; import { Environment } from "./environment"; import { Player } from "./characterController"; import { PlayerInput } from "./inputController"; enum State { START = 0, GAME = 1, LOSE = 2, CUTSCENE = 3 } class App { // General Entire Application private _scene: Scene; private _canvas: HTMLCanvasElement; private _engine: Engine; //Game State Related public assets; private _input: PlayerInput; private _environment; private _player: Player; //Scene - related private _state: number = 0; private _gamescene: Scene; private _cutScene: Scene; constructor() { this._canvas = this._createCanvas(); // initialize babylon scene and engine this._engine = new Engine(this._canvas, true); this._scene = new Scene(this._engine); // hide/show the Inspector window.addEventListener("keydown", (ev) => { // Shift+Ctrl+Alt+I if (ev.shiftKey && ev.ctrlKey && ev.altKey && ev.keyCode === 73) { if (this._scene.debugLayer.isVisible()) { this._scene.debugLayer.hide(); } else { this._scene.debugLayer.show(); } } }); // run the main render loop this._main(); } private _createCanvas(): HTMLCanvasElement { //Commented out for development // document.documentElement.style["overflow"] = "hidden"; // document.documentElement.style.overflow = "hidden"; // document.documentElement.style.width = "100%"; // document.documentElement.style.height = "100%"; // document.documentElement.style.margin = "0"; // document.documentElement.style.padding = "0"; // document.body.style.overflow = "hidden"; // document.body.style.width = "100%"; // document.body.style.height = "100%"; // document.body.style.margin = "0"; // document.body.style.padding = "0"; //create the canvas html element and attach it to the webpage this._canvas = document.createElement("canvas"); this._canvas.style.width = "100%"; this._canvas.style.height = "100%"; this._canvas.id = "gameCanvas"; document.body.appendChild(this._canvas); return this._canvas; } private async _main(): Promise<void> { await this._goToStart(); // Register a render loop to repeatedly render the scene this._engine.runRenderLoop(() => { switch (this._state) { case State.START: this._scene.render(); break; case State.CUTSCENE: this._scene.render(); break; case State.GAME: this._scene.render(); break; case State.LOSE: this._scene.render(); break; default: break; } }); //resize if the screen is resized/rotated window.addEventListener('resize', () => { this._engine.resize(); }); } private async _goToStart(){ this._engine.displayLoadingUI(); this._scene.detachControl(); let scene = new Scene(this._engine); scene.clearColor = new Color4(0,0,0,1); let camera = new FreeCamera("camera1", new Vector3(0, 0, 0), scene); camera.setTarget(Vector3.Zero()); //create a fullscreen ui for all of our GUI elements const guiMenu = AdvancedDynamicTexture.CreateFullscreenUI("UI"); guiMenu.idealHeight = 720; //fit our fullscreen ui to this height //create a simple button const startBtn = Button.CreateSimpleButton("start", "PLAY"); startBtn.width = 0.2 startBtn.height = "40px"; startBtn.color = "white"; startBtn.top = "-14px"; startBtn.thickness = 0; startBtn.verticalAlignment = Control.VERTICAL_ALIGNMENT_BOTTOM; guiMenu.addControl(startBtn); //this handles interactions with the start button attached to the scene startBtn.onPointerDownObservable.add(() => { this._goToCutScene(); scene.detachControl(); //observables disabled }); //--SCENE FINISHED LOADING-- await scene.whenReadyAsync(); this._engine.hideLoadingUI(); //lastly set the current state to the start state and set the scene to the start scene this._scene.dispose(); this._scene = scene; this._state = State.START; } private async _goToCutScene(): Promise<void> { this._engine.displayLoadingUI(); //--SETUP SCENE-- //dont detect any inputs from this ui while the game is loading this._scene.detachControl(); this._cutScene = new Scene(this._engine); let camera = new FreeCamera("camera1", new Vector3(0, 0, 0), this._cutScene); camera.setTarget(Vector3.Zero()); this._cutScene.clearColor = new Color4(0, 0, 0, 1); //--GUI-- const cutScene = AdvancedDynamicTexture.CreateFullscreenUI("cutscene"); //--PROGRESS DIALOGUE-- const next = Button.CreateSimpleButton("next", "NEXT"); next.color = "white"; next.thickness = 0; next.verticalAlignment = Control.VERTICAL_ALIGNMENT_BOTTOM; next.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_RIGHT; next.width = "64px"; next.height = "64px"; next.top = "-3%"; next.left = "-12%"; cutScene.addControl(next); next.onPointerUpObservable.add(() => { // this._goToGame(); }) //--WHEN SCENE IS FINISHED LOADING-- await this._cutScene.whenReadyAsync(); this._engine.hideLoadingUI(); this._scene.dispose(); this._state = State.CUTSCENE; this._scene = this._cutScene; //--START LOADING AND SETTING UP THE GAME DURING THIS SCENE-- var finishedLoading = false; await this._setUpGame().then(res =>{ finishedLoading = true; this._goToGame(); }); } private async _setUpGame() { let scene = new Scene(this._engine); this._gamescene = scene; //--CREATE ENVIRONMENT-- const environment = new Environment(scene); this._environment = environment; await this._environment.load(); //environment await this._loadCharacterAssets(scene); } private async _loadCharacterAssets(scene){ async function loadCharacter(){ //collision mesh const outer = MeshBuilder.CreateBox("outer", { width: 2, depth: 1, height: 3 }, scene); outer.isVisible = false; outer.isPickable = false; outer.checkCollisions = true; //move origin of box collider to the bottom of the mesh (to match player mesh) outer.bakeTransformIntoVertices(Matrix.Translation(0, 1.5, 0)) //for collisions outer.ellipsoid = new Vector3(1, 1.5, 1); outer.ellipsoidOffset = new Vector3(0, 1.5, 0); outer.rotationQuaternion = new Quaternion(0, 1, 0, 0); // rotate the player mesh 180 since we want to see the back of the player return SceneLoader.ImportMeshAsync(null, "./models/", "player.glb", scene).then((result) =>{ const root = result.meshes[0]; //body is our actual player mesh const body = root; body.parent = outer; body.isPickable = false; //so our raycasts dont hit ourself body.getChildMeshes().forEach(m => { m.isPickable = false; }) return { mesh: outer as Mesh, } }); } return loadCharacter().then(assets=> { console.log("load char assets") this.assets = assets; }) } private async _initializeGameAsync(scene): Promise<void> { //temporary light to light the entire scene var light0 = new HemisphericLight("HemiLight", new Vector3(0, 1, 0), scene); const light = new PointLight("sparklight", new Vector3(0, 0, 0), scene); light.diffuse = new Color3(0.08627450980392157, 0.10980392156862745, 0.15294117647058825); light.intensity = 35; light.radius = 1; const shadowGenerator = new ShadowGenerator(1024, light); shadowGenerator.darkness = 0.4; //Create the player this._player = new Player(this.assets, scene, shadowGenerator, this._input); const camera = this._player.activatePlayerCamera(); //set up lantern collision checks this._environment.checkLanterns(this._player); } private async _goToGame(){ //--SETUP SCENE-- this._scene.detachControl(); let scene = this._gamescene; scene.clearColor = new Color4(0.01568627450980392, 0.01568627450980392, 0.20392156862745098); // a color that fit the overall color scheme better //--GUI-- const playerUI = AdvancedDynamicTexture.CreateFullscreenUI("UI"); //dont detect any inputs from this ui while the game is loading scene.detachControl(); //create a simple button const loseBtn = Button.CreateSimpleButton("lose", "LOSE"); loseBtn.width = 0.2 loseBtn.height = "40px"; loseBtn.color = "white"; loseBtn.top = "-14px"; loseBtn.thickness = 0; loseBtn.verticalAlignment = Control.VERTICAL_ALIGNMENT_BOTTOM; playerUI.addControl(loseBtn); //this handles interactions with the start button attached to the scene loseBtn.onPointerDownObservable.add(() => { this._goToLose(); scene.detachControl(); //observables disabled }); //--INPUT-- this._input = new PlayerInput(scene); //detect keyboard/mobile inputs //primitive character and setting await this._initializeGameAsync(scene); //--WHEN SCENE FINISHED LOADING-- await scene.whenReadyAsync(); scene.getMeshByName("outer").position = scene.getTransformNodeByName("startPosition").getAbsolutePosition(); //move the player to the start position //get rid of start scene, switch to gamescene and change states this._scene.dispose(); this._state = State.GAME; this._scene = scene; this._engine.hideLoadingUI(); //the game is ready, attach control back this._scene.attachControl(); } private async _goToLose(): Promise<void> { this._engine.displayLoadingUI(); //--SCENE SETUP-- this._scene.detachControl(); let scene = new Scene(this._engine); scene.clearColor = new Color4(0, 0, 0, 1); let camera = new FreeCamera("camera1", new Vector3(0, 0, 0), scene); camera.setTarget(Vector3.Zero()); //--GUI-- const guiMenu = AdvancedDynamicTexture.CreateFullscreenUI("UI"); const mainBtn = Button.CreateSimpleButton("mainmenu", "MAIN MENU"); mainBtn.width = 0.2; mainBtn.height = "40px"; mainBtn.color = "white"; guiMenu.addControl(mainBtn); //this handles interactions with the start button attached to the scene mainBtn.onPointerUpObservable.add(() => { this._goToStart(); }); //--SCENE FINISHED LOADING-- await scene.whenReadyAsync(); this._engine.hideLoadingUI(); //when the scene is ready, hide loading //lastly set the current state to the lose state and set the scene to the lose scene this._scene.dispose(); this._scene = scene; this._state = State.LOSE; } } new App();
the_stack
import React, { useCallback, useEffect, useState } from 'react' import { makeStyles } from '@material-ui/core/styles' import { AppBar, ButtonBase, darken, Fade, IconButton, lighten, Toolbar, Typography, } from '@material-ui/core' import BackRoundedIcon from '@material-ui/icons/ArrowBackRounded' import { useHistory } from 'react-router' import { APP_BAR_HEIGHT, DRAWER_WIDTH, MAX_WIDTH, MIDDLE_WIDTH, MIN_WIDTH, } from 'src/config/constants' import isMobile from 'is-mobile' import { chromeAddressBarHeight } from 'src/config/constants' import { useScrollTrigger } from 'src/hooks' import getContrastPaperColor from 'src/utils/getContrastPaperColor' import getInvertedContrastPaperColor from 'src/utils/getInvertedContrastPaperColor' import useMediaExtendedQuery from 'src/hooks/useMediaExtendedQuery' import getCachedMode from 'src/utils/getCachedMode' import getSecondaryAppBarColor from 'src/utils/getSecondaryAppBarColor' import { History } from 'history' import isDarkTheme from 'src/utils/isDarkTheme' interface StyleProps { isShrinked?: boolean scrollProgress?: number backgroundColor?: string shrinkedBackgroundColor?: string disableShrinking?: boolean } const useStyles = makeStyles((theme) => ({ root: { background: theme.palette.background.default, minHeight: '100%', width: '100%', }, children: { maxWidth: MAX_WIDTH, display: 'flex', marginRight: 'auto', marginLeft: 'auto', alignItems: 'flex-start', [theme.breakpoints.up(MIDDLE_WIDTH)]: { marginTop: APP_BAR_HEIGHT, }, }, })) const useAppBarStyles = makeStyles((theme) => ({ toolbarIcons: { marginRight: theme.spacing(2), display: 'flex', }, header: { backgroundColor: ({ isShrinked, backgroundColor, shrinkedBackgroundColor, }: StyleProps) => isShrinked ? shrinkedBackgroundColor || getInvertedContrastPaperColor(theme) : backgroundColor || getContrastPaperColor(theme), color: theme.palette.text.primary, position: 'fixed', willChange: 'transform', flexGrow: 1, transform: ({ isShrinked }: StyleProps) => `translateZ(0) translateY(${isShrinked ? -16 : 0}px)`, transition: ({ disableShrinking }: StyleProps) => disableShrinking ? 'none' : 'all .3s cubic-bezier(0.4, 0, 0.2, 1)', [theme.breakpoints.up(MIDDLE_WIDTH)]: { paddingLeft: DRAWER_WIDTH, backgroundColor: getSecondaryAppBarColor(theme) + ' !important', }, [theme.breakpoints.between(MIN_WIDTH, MIDDLE_WIDTH)]: { backgroundColor: theme.palette.background.paper + ' !important', }, }, toolbar: { minHeight: 'unset', padding: 0, maxWidth: '100%', width: '100%', '&::before': { position: 'absolute', width: ({ scrollProgress }: StyleProps) => scrollProgress * 100 + '%', background: theme.palette.type === 'dark' ? 'rgba(255, 255, 255, .1)' : 'rgba(0, 0, 0, .1)', height: '100%', content: '""', transform: 'translateZ(0)', }, }, headerTitle: { fontFamily: 'Google Sans', fontWeight: 500, color: theme.palette.text.primary, fontSize: 20, letterHeight: '1.6', whiteSpace: 'nowrap', overflow: 'hidden', zIndex: 1000, textOverflow: 'ellipsis', marginRight: theme.spacing(2), [theme.breakpoints.up(MIDDLE_WIDTH)]: { marginLeft: theme.spacing(2), }, }, headerIcon: { marginLeft: 4, color: theme.palette.text.primary, [theme.breakpoints.up(MIDDLE_WIDTH)]: { display: 'none', }, }, marginContainer: { display: 'flex', width: '100%', flexDirection: 'column', }, content: { display: 'flex', flexDirection: 'row', width: '100%', alignItems: 'center', transform: 'translateZ(0)', height: APP_BAR_HEIGHT, flexGrow: 1, }, shrinkedHeaderTitle: { fontFamily: 'Google Sans', fontWeight: 500, color: theme.palette.text.secondary, fontSize: 16, transform: 'translateX(16px) translateY(8px)', letterHeight: '1.6', whiteSpace: 'nowrap', overflow: 'hidden', zIndex: 1000, maxWidth: 'calc(100% - 32px)', position: 'absolute', textOverflow: 'ellipsis', }, backButtonDesktop: { width: DRAWER_WIDTH, height: APP_BAR_HEIGHT, display: 'none', position: 'fixed', top: 0, left: 0, zIndex: theme.zIndex.drawer + 1, background: theme.palette.background.paper, cursor: 'pointer', '&:hover': { background: isDarkTheme(theme) ? lighten(theme.palette.background.paper, 0.05) : darken(theme.palette.background.paper, 0.05), }, [theme.breakpoints.up(MIDDLE_WIDTH)]: { display: 'flex', }, }, backButtonDesktopWrapper: { alignItems: 'center', justifyContent: 'flex-start', display: 'flex', flexDirection: 'row', padding: theme.spacing(0, 2), width: '100%', }, backButtonDesktopText: { marginLeft: theme.spacing(2), fontFamily: 'Google Sans', fontSize: 20, fontWeight: 500, }, })) interface Props { children: unknown headerText: unknown hidePositionBar: boolean shrinkedHeaderText: unknown shrinkedBackgroundColor: string disableShrinking: boolean backgroundColor: string toolbarIcons: JSX.Element onBackClick: ( backLinkFunction: (history: History<unknown>) => void ) => unknown scrollElement?: HTMLElement } const ShrinkedContentUnmemoized = ({ isShrinked, shrinkedHeaderText }) => { const classes = useAppBarStyles({}) return ( <Fade in={isShrinked} unmountOnExit mountOnEnter> <Typography className={classes.shrinkedHeaderTitle}> {shrinkedHeaderText} </Typography> </Fade> ) } const ShrinkedContent = React.memo(ShrinkedContentUnmemoized) const backLinkFunction = (history: History<unknown>) => { const goHome = () => history.push(getCachedMode().to + 'p/1') if (history.length > 1) { history.goBack() } else goHome() } const UnshrinkedContentUnmemoized = ({ headerText, onBackClick, isShrinked, headerTextUpdated, }) => { const classes = useAppBarStyles({}) const history = useHistory() const text = ( <Typography className={classes.headerTitle}>{headerText}</Typography> ) const onClick = () => { if (onBackClick) onBackClick(backLinkFunction) else backLinkFunction(history) } return ( <Fade in={!isShrinked} appear={false}> <div className={classes.content} style={{ overflow: 'hidden' }}> <IconButton disableRipple={isShrinked} className={classes.headerIcon} onClick={() => (isShrinked ? {} : onClick())} > <BackRoundedIcon /> </IconButton> {headerText && headerTextUpdated ? <Fade in>{text}</Fade> : text} </div> </Fade> ) } const UnshrinkedContent = React.memo(UnshrinkedContentUnmemoized) const ToolbarIconsWrapperUnmemoized = ({ isShrinked, children }) => { const classes = useAppBarStyles({}) return ( <Fade in={!isShrinked}> <div className={classes.toolbarIcons}>{children}</div> </Fade> ) } const ToolbarIconsWrapper = React.memo(ToolbarIconsWrapperUnmemoized) const NavBarUnmemoized = ({ headerText, shrinkedHeaderText, hidePositionBar = false, shrinkedBackgroundColor, backgroundColor, onBackClick, disableShrinking, toolbarIcons, scrollElement, }: Partial<Props>) => { const isShrinkedTrigger = useScrollTrigger({ threshold: 48, triggerValue: false, }) const [headerTextUpdated, setHeaderTextUpdated] = useState(false) const [scrollProgress, setScrollProgress] = useState(0) const isExtended = useMediaExtendedQuery() const history = useHistory() const isShrinked = disableShrinking || isExtended ? false : isShrinkedTrigger const classes = useAppBarStyles({ isShrinked, scrollProgress, backgroundColor, shrinkedBackgroundColor, disableShrinking, }) const scrollCallback = useCallback( () => requestAnimationFrame(() => { const getElementScroll = (el: HTMLElement) => { const docElement = document.documentElement const docBody = document.body const element = el || docElement || docBody return ( (docElement.scrollTop || docBody.scrollTop) / (element.offsetHeight - 200) ) } const newScrollProgress = getElementScroll(scrollElement) setScrollProgress(newScrollProgress) }), [scrollElement] ) useEffect(() => { if (!hidePositionBar && !disableShrinking) { // passive: true enhances scrolling experience window.addEventListener('scroll', scrollCallback, { passive: true }) return () => window.removeEventListener('scroll', scrollCallback) } else return () => null }, [hidePositionBar, disableShrinking, scrollElement]) // Remove fade effect on a title if it was set by default // If the title is being fetched (ex. Post), // we need to change the state and render Fade component useEffect(() => { !headerTextUpdated && setHeaderTextUpdated(!headerText) }, [headerText]) const onBackButtonClick = () => { if (onBackClick) onBackClick(backLinkFunction) else backLinkFunction(history) } return ( <> <div onClick={() => onBackButtonClick()} className={classes.backButtonDesktop} > <div className={classes.backButtonDesktopWrapper}> <BackRoundedIcon /> <Typography className={classes.backButtonDesktopText}> Назад </Typography> </div> </div> <AppBar className={classes.header} elevation={0}> <Toolbar className={classes.toolbar}> <div className={classes.marginContainer}> <div className={classes.content}> <UnshrinkedContent isShrinked={isShrinked} headerText={headerText} onBackClick={onBackClick} headerTextUpdated={headerTextUpdated} /> <ShrinkedContent isShrinked={isShrinked} shrinkedHeaderText={shrinkedHeaderText || headerText} /> <ToolbarIconsWrapper isShrinked={isShrinked}> {toolbarIcons} </ToolbarIconsWrapper> </div> </div> </Toolbar> </AppBar> </> ) } const NavBar = React.memo(NavBarUnmemoized) const OutsidePage: React.FC<Partial<Props>> = ({ children, ...props }) => { const classes = useStyles() return ( <div className={classes.root}> <NavBar {...props} /> <div className={classes.children}>{children}</div> </div> ) } export default React.memo(OutsidePage)
the_stack
export type UserId = { /** * id of the user for which the methods apply. * This value should be changed to the special keyword 'me' to simplify calls when access using OAuth2 with three-legged authentication */ user_id: string } export type PhoneNumber = { /** The phone number to which the order refers to. 'E164 with +'' format. */ phone_number: string } export type Identifier = { /** The user identifier (e.g. phone number) to filter the results */ identifier?: string } export type OfferId = { /** Id of the offer */ offer_id: string } export type OrderId = { /** Id of the purchase order */ order_id: string } export type CategoriesId = { /** List of wanted category ids separated by commas */ 'categories.id'?: string } export type Status = { /** The status of the subscribed product used to filter the results */ status?: string } export type Offers = Offer[] /** Offer object */ export type Offer = { /** Unique id of the offer */ id: string /** Name of the offer. User Friendly field. */ name: string /** List of user identifiers (e.g. phone_numbers) that can be used to subscribe to the offer */ identifiers?: string[] /** Description of the offer. User Friendly field. */ description: string /** List of categories for which the offer applies */ categories: OfferCategory[] /** Time when the offer will be available to the user, in ISO-8601 extended local date format. Time-offset from UTC may be used to match local OB time. */ start_date?: string /** Time when the offer will expire for the user, in ISO-8601 extended local date format. Time-offset from UTC may be used to match local OB time. */ end_date?: string /** List of prices for this offer */ prices: Price[] product: OfferedProduct } /** category of offer */ export type OfferCategory = { /** Name of the category. */ name: string /** short description of the category. User Friendly field. */ description?: string id: 'promotion' | 'bundle' | 'sms' | 'voice' | 'data' | 'value_added_service' | 'app' | 'iptv' | 'device' | 'recurring' | 'bolt-on' | 'dth' } /** Object that model a product definition */ export type Product = { /** Name to be displayed when referring to this product. User Friendly field. */ display_name: string product_type: ProductType descriptions?: Descriptions subscription_type?: SubscriptionType quota?: Quotas connection?: Connection packages?: Packages /** list of freely defined strings that tag the product based on some criteria */ tags?: string[] } /** Specifies how the service is paid (prepaid, postpaid, etc) */ export type SubscriptionType = 'prepaid' | 'postpaid' | 'control' /** The type of the product */ export type ProductType = 'mobile' | 'landline' | 'internet' | 'iptv' | 'bundle' | 'device' | 'voucher' | 'value_added_service' | 'bolt-on' | 'dth' /** Object that models an offered product */ export type OfferedProduct = Product & { /** Array of products objects. Only applies for product bundle */ sub_products: OfferedProduct[] } /** Object that models a subscribed product */ export type SubscribedProduct = Product & { /** Unique identifier of the product */ id: string /** Process state of the product */ status: 'active' | 'activating' | 'suspended' /** List of user identifiers (e.g. phone_numbers) associated to this specific product instance. */ identifiers: string[] /** Time when the product was subscribed, in ISO-8601 extended local date format. Time-offset from UTC may be used to match local OB time. */ start_date: string /** Time when the product will finalize, in ISO-8601 extended local date format. Time-offset from UTC may be used to match local OB time. */ end_date?: string /** List of prices for this subscribed product */ prices?: Price[] /** Array of products objects. Only applies for product bundle */ sub_products?: SubscribedProduct[] } /** It applies for product_type mobile, value_added_service and bolt-on, and provides information on available data, voice and sms quota */ export type Quotas = { /** list of data quotas associated to this product */ data: DataQuota[] /** list of voice quotas associated to this product */ voice: VoiceQuota[] /** list of SMS quotas associated to this product */ sms: SmsQuota[] } export type CommonQuota = { /** max units allowed by current quota. -1 is interpreted as there is no limit */ max: number time_bands?: TimeBand[] origins?: Origin[] } /** Data quota information */ export type DataQuota = CommonQuota & { /** Unit used on the quota */ unit: 'byte' | 'kilobyte' | 'megabyte' | 'gigabyte' } /** Voice quota information */ export type VoiceQuota = CommonQuota & { /** Unit used on the quota */ unit: 'second' | 'minute' | 'hour' destinations?: Destination[] } /** SMS quota information */ export type SmsQuota = CommonQuota & { /** Unit used on the quota */ unit: 'message' destinations?: Destination[] } /** Timebands when the quota applies */ export type TimeBand = 'day' | 'night' | 'morning' | 'evening' | 'weekends' | 'workdays' | 'all' /** Destinations for which the quota applies */ export type Destination = 'telefonica' | 'non-telefonica' | 'rural' | 'local' | 'regional' | 'national' | 'international' | 'mobile' | 'landline' | 'any' /** Origin for which the quota applies */ export type Origin = 'home' | 'roaming' | 'EU' /** It applies only for product_type internet and provides information on connections characteristics */ export type Connection = { /** Connection type */ type: 'fiber' | 'dsl' | 'unknown' /** Uplink speed in megabits per second */ uplink_mbps: number /** Downlink speed in megabits per second */ downlink_mbps: number } /** Package information */ export type Package = { /** Name of the package. User Friendly field. */ name: string /** Unique package identifier */ package_id: string } /** It applies only for product_type iptv and dth; provides information on available TV packages */ export type Packages = Package[] /** Information about the product for displaying purposes. */ export type Description = { /** Text with information about the product. User Friendly field. */ text: string /** HTTPS URL */ url?: string /** * Category of the description. This field is used to provide further info about displaying of the description text: * - 'general': Default value for any description without specific category. * - 'dates': Information about dates, related with the life-cycle of the product (e.g: contractual information about renowation conditions) * - 'promotion': Information about product acquisition conditions, such as if special price is being applied and for how long, or if data quota is duplicated during first three months. */ category?: 'general' | 'dates' | 'promotion' } export type Descriptions = Description[] /** Price information */ export type Price = { /** Description of the price. User Friendly field. */ description: string /** Type of the price */ type: 'recurring' | 'usage' | 'one-off' /** * Period between charge of the price. Applies when type equals recurring. * Additional to pre-defined values of daily, weekly, monthly, yearly, any indication of number of days or hours is possible, with format {x}-days or {x}-hours (e.g.: 7-days or 24-hours). */ recurring_period?: string /** * Period for which the product will be subscribed. It does not mean that offer is available for indicated period, it means that the product will be acquired and will last for indicated period. Applies when type equals one-off or usage. For backwards compatibility, in case of recurring prices, recurring_period param is used instead. * Additional to pre-defined values of day, week, month, year, any indication of number of days or hours is possible, with format {x}-days or {x}-hours (e.g.: 7-days or 24-hours). */ period_duration?: string amount: External1_MoneyAmount /** porcentage factor of the taxes applied */ tax: number } /** List of orders */ export type Orders = Order[] /** Information related to an order */ export type Order = { /** Unique id of the order */ id: string /** Id of the purchased offer */ offer_id?: string /** Id of the subscribed product this order relates to */ product_id?: string /** user identifer (e.g. phone number) associated to the order */ identifier?: string /** Time when the order was created, in ISO-8601 extended local date format. Time-offset from UTC may be used to match local OB time. */ creation_date: string /** type of the order */ type: 'purchase' | 'unsubscription' | 'update' status: OrderStatus error?: OrderError } export type OrderStatus = 'pending' | 'confirmed' | 'rejected' /** Information related to an error when trying to purchase an offer */ export type OrderError = { /** Error code produces when trying to purchase an offer */ code: string /** Message information related to the error when trying to purchase an offer. User Friendly field. */ description: string } /** Information of what offer has to be used to create the order */ export type CreatePurchaseOrderInvoice = { /** Id of the offer related to the new order */ offer_id: string /** user identifer (e.g. phone number) associated to the order */ identifier?: string } /** Information of what offer has to be used to create the order */ export type CreatePurchaseOrderWallet = { /** Id of the offer related to the new order */ offer_id: string /** user identifer (e.g. phone number) associated to the order */ identifier?: string wallet_type: WalletType } /** Information of what offer has to be used to create the order using invoice has payment method */ export type CreatePurchaseOrderByPhoneNumberInvoice = { /** Id of the offer related to the new order */ offer_id: string } /** Information of what offer has to be used to create the order using wallet as payment method */ export type CreatePurchaseOrderByPhoneNumberWallet = { /** Id of the offer related to the new order */ offer_id: string wallet_type: WalletType } /** type of the wallet */ export type WalletType = 'general' | 'communications' | 'additional_services' /** Information to create a product unsubscribe order */ export type CreateUnsubscribeOrder = { /** Id of the product to be unsubscribed */ product_id: string } /** Information to create an order to set renew config of a product. */ export type CreateUpdateRenewOrder = { /** Id of the product to be updated */ product_id: string /** True to indicate that product renovation config should be activated, false to do the opposite */ renew: boolean } export type External0_ModelError = { /** A human readable description of what the event represent */ message: string } export type External1_QuotaCategory = 'general' | 'promotion' | 'voucher' | 'application' | 'pay_per_use' export type External0_InvalidArgument = { /** Client specified an invalid argument, request body or query param. */ code: 'INVALID_ARGUMENT' } & External0_ModelError export type External0_PermissionDenied = { /** Client does not have sufficient permissions to perform this action. */ code: 'PERMISSION_DENIED' } & External0_ModelError export type External0_NotFound = { /** The specified resource is not found */ code: 'NOT_FOUND' } & External0_ModelError export type External0_AlreadyExists = { /** The resource that a client tried to create already exists. */ code: 'ALREADY_EXISTS' } & External0_ModelError export type External0_Internal = { /** Unknown server error.Typically a server bug. */ code: 'INTERNAL' } & External0_ModelError export type External0_Timeout = { /** Request timeout exceeded */ code: 'TIMEOUT' } & External0_ModelError /** Money amount */ export type External1_MoneyAmount = { /** Amount value */ value: number /** Currency code in which the amount is expressed. ISO 4217 */ currency: string /** true if the amount includes government taxes */ tax_included?: boolean }
the_stack
import ez = require("TypeScript/ez") import EZ_TEST = require("./TestFramework") export class TestTransform extends ez.TypescriptComponent { /* BEGIN AUTO-GENERATED: VARIABLES */ /* END AUTO-GENERATED: VARIABLES */ constructor() { super() } static RegisterMessageHandlers() { ez.TypescriptComponent.RegisterMessageHandler(ez.MsgGenericEvent, "OnMsgGenericEvent"); } ExecuteTests(): void { // constructor { let t = new ez.Transform(); EZ_TEST.VEC3(t.position, ez.Vec3.ZeroVector()); EZ_TEST.QUAT(t.rotation, ez.Quat.IdentityQuaternion()); EZ_TEST.VEC3(t.scale, ez.Vec3.OneVector()); } // Clone { let t = new ez.Transform(); t.position.Set(1, 2, 3); t.rotation.SetFromAxisAndAngle(ez.Vec3.UnitAxisZ(), ez.Angle.DegreeToRadian(90)); t.scale.Set(4, 5, 6); let c = t.Clone(); EZ_TEST.BOOL(t != c); EZ_TEST.BOOL(t.position != c.position); EZ_TEST.BOOL(t.rotation != c.rotation); EZ_TEST.BOOL(t.scale != c.scale); EZ_TEST.VEC3(t.position, c.position); EZ_TEST.QUAT(t.rotation, c.rotation); EZ_TEST.VEC3(t.scale, c.scale); } // SetTransform { let t = new ez.Transform(); t.position.Set(1, 2, 3); t.rotation.SetFromAxisAndAngle(ez.Vec3.UnitAxisZ(), ez.Angle.DegreeToRadian(90)); t.scale.Set(4, 5, 6); let c = new ez.Transform(); c.SetTransform(t); EZ_TEST.BOOL(t != c); EZ_TEST.BOOL(t.position != c.position); EZ_TEST.BOOL(t.rotation != c.rotation); EZ_TEST.BOOL(t.scale != c.scale); EZ_TEST.VEC3(t.position, c.position); EZ_TEST.QUAT(t.rotation, c.rotation); EZ_TEST.VEC3(t.scale, c.scale); } // SetIdentity { let t = new ez.Transform(); t.position.Set(1, 2, 3); t.rotation.SetFromAxisAndAngle(ez.Vec3.UnitAxisZ(), ez.Angle.DegreeToRadian(90)); t.scale.Set(4, 5, 6); t.SetIdentity(); EZ_TEST.VEC3(t.position, ez.Vec3.ZeroVector()); EZ_TEST.QUAT(t.rotation, ez.Quat.IdentityQuaternion()); EZ_TEST.VEC3(t.scale, ez.Vec3.OneVector()); } // IdentityTransform { let t = ez.Transform.IdentityTransform(); EZ_TEST.VEC3(t.position, ez.Vec3.ZeroVector()); EZ_TEST.QUAT(t.rotation, ez.Quat.IdentityQuaternion()); EZ_TEST.VEC3(t.scale, ez.Vec3.OneVector()); } // IsIdentical { let t = new ez.Transform(); t.position.Set(1, 2, 3); t.rotation.SetFromAxisAndAngle(ez.Vec3.UnitAxisZ(), ez.Angle.DegreeToRadian(90)); t.scale.Set(4, 5, 6); let c = new ez.Transform(); c.SetTransform(t); EZ_TEST.BOOL(t.IsIdentical(c)); c.position.x += 0.0001; EZ_TEST.BOOL(!t.IsIdentical(c)); } // IsEqual { let t = new ez.Transform(); t.position.Set(1, 2, 3); t.rotation.SetFromAxisAndAngle(ez.Vec3.UnitAxisZ(), ez.Angle.DegreeToRadian(90)); t.scale.Set(4, 5, 6); let c = new ez.Transform(); c.SetTransform(t); EZ_TEST.BOOL(t.IsEqual(c)); c.position.x += 0.0001; EZ_TEST.BOOL(t.IsEqual(c, 0.001)); EZ_TEST.BOOL(!t.IsEqual(c, 0.00001)); } // Translate { let t = new ez.Transform(); t.Translate(new ez.Vec3(1, 2, 3)); EZ_TEST.VEC3(t.position, new ez.Vec3(1, 2, 3)); EZ_TEST.QUAT(t.rotation, ez.Quat.IdentityQuaternion()); EZ_TEST.VEC3(t.scale, ez.Vec3.OneVector()); } // SetMulTransform / MulTransform { let tParent = new ez.Transform(); tParent.position.Set(1, 2, 3); tParent.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); tParent.scale.SetAll(2); let tToChild = new ez.Transform(); tToChild.position.Set(4, 5, 6); tToChild.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); tToChild.scale.SetAll(4); // this is exactly the same as SetGlobalTransform let tChild = new ez.Transform(); tChild.SetMulTransform(tParent, tToChild); EZ_TEST.BOOL(tChild.position.IsEqual(new ez.Vec3(13, 12, -5), 0.0001)); let q1 = new ez.Quat(); q1.SetConcatenatedRotations(tParent.rotation, tToChild.rotation); EZ_TEST.BOOL(tChild.rotation.IsEqualRotation(q1, 0.0001)); EZ_TEST.VEC3(tChild.scale, new ez.Vec3(8, 8, 8)); tChild = tParent.Clone(); tChild.MulTransform(tToChild); EZ_TEST.BOOL(tChild.position.IsEqual(new ez.Vec3(13, 12, -5), 0.0001)); q1.SetConcatenatedRotations(tParent.rotation, tToChild.rotation); EZ_TEST.QUAT(tChild.rotation, q1); EZ_TEST.VEC3(tChild.scale, new ez.Vec3(8, 8, 8)); let a = new ez.Vec3(7, 8, 9); let b = a.Clone(); tToChild.TransformPosition(b); tParent.TransformPosition(b); let c = a.Clone(); tChild.TransformPosition(c); EZ_TEST.VEC3(b, c); } // Invert / GetInverse { let tParent = new ez.Transform(); tParent.position.Set(1, 2, 3); tParent.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); tParent.scale.SetAll(2); let tToChild = new ez.Transform(); tParent.position.Set(4, 5, 6); tToChild.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); tToChild.scale.SetAll(4); let tChild = new ez.Transform(); tChild.SetMulTransform(tParent, tToChild); // invert twice -> get back original let t2 = tToChild.Clone(); t2.Invert(); EZ_TEST.BOOL(!t2.IsEqual(tToChild, 0.0001)); t2 = t2.GetInverse(); EZ_TEST.BOOL(t2.IsEqual(tToChild, 0.0001)); let tInvToChild = tToChild.GetInverse(); let tParentFromChild = new ez.Transform(); tParentFromChild.SetMulTransform(tChild, tInvToChild); EZ_TEST.BOOL(tParent.IsEqual(tParentFromChild, 0.0001)); } // SetLocalTransform { let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); let tParent = new ez.Transform(); tParent.position.Set(1, 2, 3); tParent.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); tParent.scale.SetAll(2); let tChild = new ez.Transform(); tChild.position.Set(13, 12, -5); tChild.rotation.SetConcatenatedRotations(tParent.rotation, q); tChild.scale.SetAll(8); let tToChild = new ez.Transform(); tToChild.SetLocalTransform(tParent, tChild); EZ_TEST.VEC3(tToChild.position, new ez.Vec3(4, 5, 6)); EZ_TEST.QUAT(tToChild.rotation, q); EZ_TEST.VEC3(tToChild.scale, new ez.Vec3(4, 4, 4)); } // SetGlobalTransform { let tParent = new ez.Transform(); tParent.position.Set(1, 2, 3); tParent.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); tParent.scale.SetAll(2); let tToChild = new ez.Transform(); tToChild.position.Set(4, 5, 6); tToChild.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); tToChild.scale.SetAll(4); let tChild = new ez.Transform(); tChild.SetGlobalTransform(tParent, tToChild); EZ_TEST.VEC3(tChild.position, new ez.Vec3(13, 12, -5)); let q = new ez.Quat(); q.SetConcatenatedRotations(tParent.rotation, tToChild.rotation); EZ_TEST.QUAT(tChild.rotation, q); EZ_TEST.VEC3(tChild.scale, new ez.Vec3(8, 8, 8)); } // TransformPosition / TransformDirection { let qRotX = new ez.Quat(); let qRotY = new ez.Quat(); qRotX.SetFromAxisAndAngle(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(90)); qRotY.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); let t = new ez.Transform(); t.position.Set(1, 2, 3); t.rotation.SetConcatenatedRotations(qRotY, qRotX); t.scale.Set(2, -2, 4); let v = new ez.Vec3(4, 5, 6); t.TransformPosition(v); EZ_TEST.VEC3(v, new ez.Vec3((5 * -2) + 1, (-6 * 4) + 2, (-4 * 2) + 3)); v.Set(4, 5, 6); t.TransformDirection(v); EZ_TEST.VEC3(v, new ez.Vec3((5 * -2), (-6 * 4), (-4 * 2))); } // ConcatenateRotations / ConcatenateRotationsReverse { let t = new ez.Transform(); t.position.Set(1, 2, 3); t.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); t.scale.SetAll(2); let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); let t2 = t.Clone(); let t4 = t.Clone(); t2.ConcatenateRotations(q); t4.ConcatenateRotationsReverse(q); let t3 = t.Clone(); t3.ConcatenateRotations(q); EZ_TEST.BOOL(t2.IsEqual(t3)); EZ_TEST.BOOL(!t3.IsEqual(t4)); let a = new ez.Vec3(7, 8, 9); let b = a.Clone(); t2.TransformPosition(b); let c = a.Clone(); q.RotateVec3(c); t.TransformPosition(c); EZ_TEST.VEC3(b, c); } // GetAsMat4 { let t = new ez.Transform(); t.position.Set(1, 2, 3); t.rotation.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(34)); t.scale.Set(2, -1, 5); let m = t.GetAsMat4(); // reference { let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(34)); let referenceTransform = new ez.Transform(); referenceTransform.position.Set(1, 2, 3); referenceTransform.rotation.SetQuat(q); referenceTransform.scale.Set(2, -1, 5); let refM = referenceTransform.GetAsMat4(); EZ_TEST.BOOL(m.IsEqual(refM)); } let p: ez.Vec3[] = [new ez.Vec3(- 4, 0, 0), new ez.Vec3(5, 0, 0), new ez.Vec3(0, -6, 0), new ez.Vec3(0, 7, 0), new ez.Vec3(0, 0, -8), new ez.Vec3(0, 0, 9), new ez.Vec3(1, -2, 3), new ez.Vec3(-4, 5, 7)]; for (let i = 0; i < 8; ++i) { let pt = p[i].Clone(); t.TransformPosition(pt); let pm = p[i].Clone(); m.TransformPosition(pm); EZ_TEST.VEC3(pt, pm); } } // SetFromMat4 { let mRot = new ez.Mat3(); mRot.SetRotationMatrix((new ez.Vec3(1, 2, 3)).GetNormalized(), ez.Angle.DegreeToRadian(42)); let mTrans = new ez.Mat4(); mTrans.SetTransformationMatrix(mRot, new ez.Vec3(1, 2, 3)); let t = new ez.Transform(); t.SetFromMat4(mTrans); EZ_TEST.VEC3(t.position, new ez.Vec3(1, 2, 3), 0); EZ_TEST.BOOL(t.rotation.GetAsMat3().IsEqual(mRot, 0.001)); } } OnMsgGenericEvent(msg: ez.MsgGenericEvent): void { if (msg.Message == "TestTransform") { this.ExecuteTests(); msg.Message = "done"; } } }
the_stack
import { CancellationToken, CancellationTokenSource, DisposableStore, Emitter, Event, isCanceledError, MapSet, Uri, } from '@velcro/common'; import type { Resolver, ResolverContext } from '@velcro/resolver'; import { Plugin, PluginManager } from '../plugins'; import { parse } from './commonjs'; import type { DependencyEdge } from './dependencyEdge'; import { Graph } from './graph'; import { DEFAULT_SHIM_GLOBALS } from './shims'; import { SourceModule } from './sourceModule'; import { SourceModuleDependency } from './sourceModuleDependency'; type ExternalTestFunction = ( dependency: SourceModuleDependency, fromSourceModule: SourceModule ) => boolean; export class Build { private readonly disposer = new DisposableStore(); private readonly edges = new Set<DependencyEdge>(); readonly errors: Error[] = []; readonly seen = new Set<unknown>(); private readonly sourceModules = new Map<string, SourceModule>(); private readonly pendingModuleOperations = new MapSet<string, Promise<unknown>>(); private readonly tokenSource: CancellationTokenSource; private readonly onCompletedEmitter = new Emitter<{ graph: Graph }>(); private readonly onErrorEmitter = new Emitter<{ error: Error }>(); private readonly onProgressEmitter = new Emitter<{ progress: { completed: number; pending: number; }; }>(); readonly done = new Promise<Graph>((resolve, reject) => { this.disposer.add(this.onCompleted(({ graph }) => resolve(graph))); this.disposer.add(this.onError(({ error }) => reject(error))); }); constructor(readonly rootUri: Uri, options: { token?: CancellationToken } = {}) { this.tokenSource = new CancellationTokenSource(options.token); this.disposer.add(this.tokenSource); this.done.catch(() => { // Prevent uncaught rejection }); } get onCompleted(): Event<{ graph: Graph }> { return this.onCompletedEmitter.event; } get onError(): Event<{ error: Error }> { return this.onErrorEmitter.event; } get onProgress(): Event<{ progress: { completed: number; pending: number; }; }> { return this.onProgressEmitter.event; } get token() { return this.tokenSource.token; } addEdge(edge: DependencyEdge) { this.edges.add(edge); } addSourceModule(sourceModule: SourceModule) { this.sourceModules.set(sourceModule.href, sourceModule); } cancel() { this.tokenSource.cancel(); } dispose() { this.cancel(); this.disposer.dispose(); } hasSourceModule(href: string) { return this.sourceModules.has(href); } runAsync(key: string, fn: () => Promise<unknown>): void { if (this.token.isCancellationRequested) { return; } const onError = (err: Error) => { if (ret) { this.pendingModuleOperations.delete(key, ret); } this.cancel(); if (!isCanceledError(err)) { this.errors.push(err); this.onErrorEmitter.fire({ error: err }); } }; const onSuccess = () => { this.pendingModuleOperations.delete(key, ret); if (!this.pendingModuleOperations.size) { this.onCompletedEmitter.fire({ graph: new Graph({ edges: this.edges, rootUri: this.rootUri, sourceModules: this.sourceModules.values(), }), }); } else { this.onProgressEmitter.fire({ progress: { completed: this.sourceModules.size, pending: this.pendingModuleOperations.size, }, }); } }; let ret: ReturnType<typeof fn>; try { ret = fn().then(onSuccess, onError); this.pendingModuleOperations.add(key, ret); } catch (err) { onError(err); } } } export class GraphBuilder { private readonly edgesByDependency = new WeakMap<SourceModuleDependency, DependencyEdge>(); private readonly edgesByInvalidation = new MapSet<string, DependencyEdge>(); private readonly external?: ExternalTestFunction; private readonly nodeEnv: string; private readonly resolver: Resolver; private readonly pluginManager: PluginManager; private readonly sourceModules = new Map<string, SourceModule>(); private readonly sourceModulesByInvalidation = new MapSet<string, SourceModule>(); constructor(options: GraphBuilder.Options) { this.resolver = options.resolver; this.external = options.external; this.nodeEnv = options.nodeEnv || 'development'; this.pluginManager = new PluginManager(options.plugins || []); } private loadDependency(build: Build, sourceModule: SourceModule, dep: SourceModuleDependency) { if (build.seen.has(dep)) return; build.seen.add(dep); if (this.external && this.external(dep, sourceModule)) { return; } // console.debug('loadDependency(%s, %s)', sourceModule.href, dep.spec); build.runAsync(`${sourceModule.href}|${dep.spec}`, async () => { const result = await this.pluginManager.executeResolveDependency( { nodeEnv: this.nodeEnv, resolver: this.resolver, token: build.token, }, dep, sourceModule ); const edge = this.createEdge( sourceModule.uri, sourceModule.rootUri, result.uri, result.rootUri, result.visited, dep ); build.addEdge(edge); this.loadEdge(build, edge); }); } private loadEdge(build: Build, edge: DependencyEdge) { const href = edge.toUri.toString(); if (build.hasSourceModule(href)) return; const existingSourceModule = this.sourceModules.get(href); if (existingSourceModule) { build.addSourceModule(existingSourceModule); return this.visitSourceModule(build, existingSourceModule); } // console.debug( // 'loadEdge(%s, %s, %s)', // edge.fromUri.toString(), // edge.dependency.spec, // edge.toUri.toString() // ); build.runAsync(href, async () => { // We need to check again in case another 'thread' already produced this // sourceModule if (build.hasSourceModule(href)) return; const loadResult = await this.pluginManager.executeLoad( { nodeEnv: this.nodeEnv, resolver: this.resolver, token: build.token, }, edge.toUri ); // We need to check again in case another 'thread' already produced this // sourceModule if (build.hasSourceModule(href)) return; const transformResult = await this.pluginManager.executeTransform( { nodeEnv: this.nodeEnv, resolver: this.resolver, token: build.token, }, edge.toUri, loadResult.code ); // We need to check again in case another 'thread' already produced this // sourceModule if (build.hasSourceModule(href)) return; const parseResult = parse(edge.toUri, transformResult.code, { globalModules: DEFAULT_SHIM_GLOBALS, nodeEnv: this.nodeEnv, }); const sourceModule = new SourceModule( edge.toUri, edge.toRootUri, parseResult.code, new Set(parseResult.dependencies), transformResult.sourceMapTree, [...transformResult.visited, ...loadResult.visited] ); build.addSourceModule(sourceModule); this.sourceModules.set(sourceModule.href, sourceModule); for (const visit of sourceModule.visits) { this.sourceModulesByInvalidation.add(visit.uri.toString(), sourceModule); } this.sourceModulesByInvalidation.add(sourceModule.href, sourceModule); this.visitSourceModule(build, sourceModule); }); } private loadEntrypoint(build: Build, uri: Uri) { const href = uri.toString(); // console.debug('loadEntrypoint(%s)', href); build.runAsync(href, async () => { const result = await this.pluginManager.executeResolveEntrypoint( { nodeEnv: this.nodeEnv, resolver: this.resolver, token: build.token, }, uri ); const edge = this.createEdge( build.rootUri, build.rootUri, result.uri, result.rootUri, result.visited, SourceModuleDependency.fromEntrypoint(uri) ); build.addEdge(edge); this.loadEdge(build, edge); }); } private visitSourceModule(build: Build, sourceModule: SourceModule) { if (build.seen.has(sourceModule)) return; build.seen.add(sourceModule); // console.debug('visitSourceModule(%s)', sourceModule.href); for (const dep of sourceModule.dependencies) { const existingEdge = this.edgesByDependency.get(dep); if (existingEdge) { build.addEdge(existingEdge); this.loadEdge(build, existingEdge); } else { this.loadDependency(build, sourceModule, dep); } } } build( entrypoints: (string | Uri)[], options: { incremental?: boolean; token?: CancellationToken } = {} ) { const rootUri = Uri.parse('velcro:/'); const build = new Build(rootUri, { token: options.token }); for (const uri of entrypoints) { this.loadEntrypoint(build, Uri.isUri(uri) ? uri : Uri.parse(uri)); } return build; } invalidate(uri: Uri | string) { const href = Uri.isUri(uri) ? uri.toString() : uri; const sourceModules = this.sourceModulesByInvalidation.get(href); if (sourceModules) { for (const sourceModule of sourceModules) { this.sourceModules.delete(sourceModule.href); } this.sourceModulesByInvalidation.deleteAll(href); } this.sourceModules.delete(href); const edges = this.edgesByInvalidation.get(href); if (edges) { for (const edge of edges) { this.edgesByDependency.delete(edge.dependency); } this.edgesByInvalidation.deleteAll(href); } this.resolver.invalidate(uri); } private createEdge( fromUri: Uri, fromRootUri: Uri, toUri: Uri, toRootUri: Uri, visited: ResolverContext.Visit[], dependency: SourceModuleDependency ) { const edge = { dependency, fromUri, fromRootUri, toUri, toRootUri, visited }; this.edgesByDependency.set(dependency, edge); this.edgesByInvalidation.add(toUri.toString(), edge); for (const visit of visited) { this.edgesByInvalidation.add(visit.uri.toString(), edge); } return edge; } } export namespace GraphBuilder { export interface Options { external?: ExternalTestFunction; nodeEnv?: string; plugins?: Plugin[]; resolver: Resolver; } }
the_stack
import { CUSTOM_ELEMENTS_SCHEMA, DebugElement } from '@angular/core'; import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Store, StoreModule } from '@ngrx/store'; import { authReducer, AuthState } from '../../core/auth/auth.reducer'; import { EPersonMock } from '../testing/eperson.mock'; import { TranslateModule } from '@ngx-translate/core'; import { AppState } from '../../app.reducer'; import { AuthNavMenuComponent } from './auth-nav-menu.component'; import { HostWindowServiceStub } from '../testing/host-window-service.stub'; import { HostWindowService } from '../host-window.service'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { AuthTokenInfo } from '../../core/auth/models/auth-token-info.model'; import { AuthService } from '../../core/auth/auth.service'; import { of } from 'rxjs'; describe('AuthNavMenuComponent', () => { let component: AuthNavMenuComponent; let deNavMenu: DebugElement; let deNavMenuItem: DebugElement; let fixture: ComponentFixture<AuthNavMenuComponent>; let notAuthState: AuthState; let authState: AuthState; let authService: AuthService; let routerState = { url: '/home' }; function serviceInit() { authService = jasmine.createSpyObj('authService', { getAuthenticatedUserFromStore: of(EPersonMock), setRedirectUrl: {} }); } function init() { notAuthState = { authenticated: false, loaded: false, blocking: false, loading: false, idle: false }; authState = { authenticated: true, loaded: true, blocking: false, loading: false, authToken: new AuthTokenInfo('test_token'), userId: EPersonMock.id, idle: false }; } describe('when is a not mobile view', () => { beforeEach(waitForAsync(() => { const window = new HostWindowServiceStub(800); serviceInit(); // refine the test module by declaring the test component TestBed.configureTestingModule({ imports: [ NoopAnimationsModule, StoreModule.forRoot(authReducer, { runtimeChecks: { strictStateImmutability: false, strictActionImmutability: false } }), TranslateModule.forRoot() ], declarations: [ AuthNavMenuComponent ], providers: [ { provide: HostWindowService, useValue: window }, { provide: AuthService, useValue: authService } ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { init(); }); describe('when route is /login and user is not authenticated', () => { beforeEach(inject([Store], (store: Store<AppState>) => { routerState = { url: '/login' }; store .subscribe((state) => { (state as any).router = Object.create({}); (state as any).router.state = routerState; (state as any).core = Object.create({}); (state as any).core.auth = notAuthState; }); // create component and test fixture fixture = TestBed.createComponent(AuthNavMenuComponent); // get test component from the fixture component = fixture.componentInstance; fixture.detectChanges(); const navMenuSelector = '.navbar-nav'; deNavMenu = fixture.debugElement.query(By.css(navMenuSelector)); const navMenuItemSelector = 'li'; deNavMenuItem = deNavMenu.query(By.css(navMenuItemSelector)); })); afterEach(() => { fixture.destroy(); }); it('should not render', () => { expect(component).toBeTruthy(); expect(deNavMenu.nativeElement).toBeDefined(); expect(deNavMenuItem).toBeNull(); }); }); describe('when route is /logout and user is authenticated', () => { beforeEach(inject([Store], (store: Store<AppState>) => { routerState = { url: '/logout' }; store .subscribe((state) => { (state as any).router = Object.create({}); (state as any).router.state = routerState; (state as any).core = Object.create({}); (state as any).core.auth = authState; }); // create component and test fixture fixture = TestBed.createComponent(AuthNavMenuComponent); // get test component from the fixture component = fixture.componentInstance; fixture.detectChanges(); const navMenuSelector = '.navbar-nav'; deNavMenu = fixture.debugElement.query(By.css(navMenuSelector)); const navMenuItemSelector = 'li'; deNavMenuItem = deNavMenu.query(By.css(navMenuItemSelector)); })); afterEach(() => { fixture.destroy(); }); it('should not render', () => { expect(component).toBeTruthy(); expect(deNavMenu.nativeElement).toBeDefined(); expect(deNavMenuItem).toBeNull(); }); }); describe('when route is not /login neither /logout', () => { describe('when user is not authenticated', () => { beforeEach(inject([Store], (store: Store<AppState>) => { routerState = { url: '/home' }; store .subscribe((state) => { (state as any).router = Object.create({}); (state as any).router.state = routerState; (state as any).core = Object.create({}); (state as any).core.auth = notAuthState; }); // create component and test fixture fixture = TestBed.createComponent(AuthNavMenuComponent); // get test component from the fixture component = fixture.componentInstance; fixture.detectChanges(); const navMenuSelector = '.navbar-nav'; deNavMenu = fixture.debugElement.query(By.css(navMenuSelector)); const navMenuItemSelector = 'li'; deNavMenuItem = deNavMenu.query(By.css(navMenuItemSelector)); })); afterEach(() => { fixture.destroy(); component = null; }); it('should render login dropdown menu', () => { const loginDropdownMenu = deNavMenuItem.query(By.css('div.loginDropdownMenu')); expect(loginDropdownMenu.nativeElement).toBeDefined(); }); }); describe('when user is authenticated', () => { beforeEach(inject([Store], (store: Store<AppState>) => { routerState = { url: '/home' }; store .subscribe((state) => { (state as any).router = Object.create({}); (state as any).router.state = routerState; (state as any).core = Object.create({}); (state as any).core.auth = authState; }); // create component and test fixture fixture = TestBed.createComponent(AuthNavMenuComponent); // get test component from the fixture component = fixture.componentInstance; fixture.detectChanges(); const navMenuSelector = '.navbar-nav'; deNavMenu = fixture.debugElement.query(By.css(navMenuSelector)); const navMenuItemSelector = 'li'; deNavMenuItem = deNavMenu.query(By.css(navMenuItemSelector)); })); afterEach(() => { fixture.destroy(); component = null; }); it('should render UserMenuComponent component', () => { const logoutDropdownMenu = deNavMenuItem.query(By.css('ds-user-menu')); expect(logoutDropdownMenu.nativeElement).toBeDefined(); }); }); }); }); describe('when is a mobile view', () => { beforeEach(waitForAsync(() => { const window = new HostWindowServiceStub(300); serviceInit(); // refine the test module by declaring the test component TestBed.configureTestingModule({ imports: [ NoopAnimationsModule, StoreModule.forRoot(authReducer, { runtimeChecks: { strictStateImmutability: false, strictActionImmutability: false } }), TranslateModule.forRoot() ], declarations: [ AuthNavMenuComponent ], providers: [ { provide: HostWindowService, useValue: window }, { provide: AuthService, useValue: authService } ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { init(); }); describe('when user is not authenticated', () => { beforeEach(inject([Store], (store: Store<AppState>) => { store .subscribe((state) => { (state as any).router = Object.create({}); (state as any).router.state = routerState; (state as any).core = Object.create({}); (state as any).core.auth = notAuthState; }); // create component and test fixture fixture = TestBed.createComponent(AuthNavMenuComponent); // get test component from the fixture component = fixture.componentInstance; fixture.detectChanges(); const navMenuSelector = '.navbar-nav'; deNavMenu = fixture.debugElement.query(By.css(navMenuSelector)); const navMenuItemSelector = 'li'; deNavMenuItem = deNavMenu.query(By.css(navMenuItemSelector)); })); afterEach(() => { fixture.destroy(); component = null; }); it('should render login link', () => { const loginDropdownMenu = deNavMenuItem.query(By.css('.loginLink')); expect(loginDropdownMenu.nativeElement).toBeDefined(); }); }); describe('when user is authenticated', () => { beforeEach(inject([Store], (store: Store<AppState>) => { store .subscribe((state) => { (state as any).router = Object.create({}); (state as any).router.state = routerState; (state as any).core = Object.create({}); (state as any).core.auth = authState; }); // create component and test fixture fixture = TestBed.createComponent(AuthNavMenuComponent); // get test component from the fixture component = fixture.componentInstance; fixture.detectChanges(); const navMenuSelector = '.navbar-nav'; deNavMenu = fixture.debugElement.query(By.css(navMenuSelector)); const navMenuItemSelector = 'li'; deNavMenuItem = deNavMenu.query(By.css(navMenuItemSelector)); })); afterEach(() => { fixture.destroy(); component = null; }); it('should render logout link', inject([Store], (store: Store<AppState>) => { const logoutDropdownMenu = deNavMenuItem.query(By.css('a[id=logoutLink]')); expect(logoutDropdownMenu.nativeElement).toBeDefined(); })); }); }); });
the_stack
import { AnyShapeStyle, RectangleShapeStyle, StrokeStyle } from "./configs" import { LinePosition, Position } from "./types" import * as V from "../common/vector" import minBy from "lodash-es/minBy" interface Line { source: Position target: Position } /** * Convert `LinePosition` to list of `Position` * @param line `LinePosition` instance * @returns list of `Position` instance */ export function lineTo2Positions(line: LinePosition): [Position, Position] { const { x1, x2, y1, y2 } = line return [ { x: x1, y: y1 }, { x: x2, y: y2 }, ] } /** * Convert two `Position` to `LinePosition` * @param p1 source position of the line * @param p2 target position of the line * @returns `LinePosition` instance */ export function positionsToLinePosition(p1: Position, p2: Position): LinePosition { return { x1: p1.x, y1: p1.y, x2: p2.x, y2: p2.y } } /** * Calculate the intersection of a line and a circle. * @param line line * @param targetSide side of the line where the node is located. true: target side, false: source side * @param center center of the circle * @param radius radius of the circle * @returns intersection point */ export function getIntersectionOfLineAndCircle( line: Line, targetSide: boolean, center: Position, radius: number ): Position | null { return ( V.getIntersectionOfLineTargetAndCircle( V.Vector.fromObject(targetSide ? line.source : line.target), V.Vector.fromObject(targetSide ? line.target : line.source), V.Vector.fromObject(center), radius )?.toObject() ?? null ) } /** * Calculate the intersection of two lines. * @param line1 line 1 * @param line2 line 2 * @returns intersection point */ export function getIntersectionPointOfLines(line1: Line, line2: Line): Position { const l1 = V.fromPositions(line1.source, line1.target) const l2 = V.fromPositions(line2.source, line2.target) return V.getIntersectionPointOfLines(l1, l2).toObject() } /** * Calculate whether a point is contained in a circle. * @param point point * @param center center of the circle * @param radius radius of the circle * @returns whether point is contained in a circle */ export function isPointContainedInCircle( point: Position, center: Position, radius: number ): boolean { const p = V.Vector.fromObject(point) const c = V.Vector.fromObject(center) const v = p.subtract(c) return v.lengthSq() < radius * radius } /** * Calculate the distance of the line. * @param line line * @returns distance */ export function calculateDistance(line: LinePosition) { const x = line.x2 - line.x1 const y = line.y2 - line.y1 return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) } /** * Get the distance that a line should be away from the * edge to avoid contacting a rounded rectangle. * @param sourcePos source position of the line * @param targetPos target position of the line * @param rect rectangle style * @param scale scale factor * @returns distance from target position */ function calculateDistanceToAvoidOverlapsWithRect( sourcePos: Position, targetPos: Position, // 対象角丸四角形の位置 rect: RectangleShapeStyle, scale: number ) { const centerLine = V.fromPositions(sourcePos, targetPos) const left = targetPos.x - (rect.width / 2) * scale const top = targetPos.y - (rect.height / 2) * scale const right = targetPos.x + (rect.width / 2) * scale const bottom = targetPos.y + (rect.height / 2) * scale const vertexes = [] const borderRadius = rect.borderRadius * scale // Calculate the nearest neighbor points of the vertices // and lines of a figure. if (borderRadius == 0) { // Since it is a simple rectangle, the four corners are the vertices. vertexes.push( V.Vector.fromArray([left, top]), V.Vector.fromArray([left, bottom]), V.Vector.fromArray([right, top]), V.Vector.fromArray([right, bottom]) ) } else { // The edge of each line and the center of the rounded corner are // the vertices. const hypo = borderRadius * Math.sin(Math.PI / 4) // 45deg vertexes.push( V.Vector.fromArray([left + borderRadius, top]), V.Vector.fromArray([left, top + borderRadius]), V.Vector.fromArray([left + borderRadius - hypo, top + borderRadius - hypo]), V.Vector.fromArray([left + borderRadius, bottom]), V.Vector.fromArray([left, bottom - borderRadius]), V.Vector.fromArray([left + borderRadius - hypo, bottom - borderRadius + hypo]), V.Vector.fromArray([right - borderRadius, top]), V.Vector.fromArray([right, top + borderRadius]), V.Vector.fromArray([right - borderRadius + hypo, top + borderRadius - hypo]), V.Vector.fromArray([right - borderRadius, bottom]), V.Vector.fromArray([right, bottom - borderRadius]), V.Vector.fromArray([right - borderRadius + hypo, bottom - borderRadius + hypo]) ) } const hits = vertexes.map(p => V.getNearestPoint(p, centerLine)) const minP = minBy(hits, p => V.toLineVector(centerLine.source, p).lengthSq()) ?? centerLine.target return V.toLineVector(minP, centerLine.target).length() } /** * Calculate the position to display the edge label from the * positions of the edge. * @param linePos line segment between the outermost of the nodes * @param edgeStyle stroke style of edges * @param margin margin from line * @param padding padding from outside * @param scale scale factor * @returns edge label display area */ export function calculateEdgeLabelArea( linePos: LinePosition, edgeStyle: StrokeStyle, margin: number, padding: number, scale: number ) { // the line segment between the outermost of the nodes const line = V.fromLinePosition(linePos) const normalized = line.v.clone().normalize() // source side const sv = padding === 0 ? line.source : line.source.clone().add(normalized.clone().multiplyScalar(padding * scale)) // target side const tv = padding === 0 ? line.target : line.target.clone().subtract(normalized.clone().multiplyScalar(padding * scale)) // margin for edges const labelMargin = (edgeStyle.width / 2 + margin) * scale const vMargin = V.Vector.fromArray([-normalized.y, normalized.x]).multiplyScalar(labelMargin) let sourceAbove = sv.clone().subtract(vMargin).toObject() as Position let sourceBelow = sv.clone().add(vMargin).toObject() as Position let targetAbove = tv.clone().subtract(vMargin).toObject() as Position let targetBelow = tv.clone().add(vMargin).toObject() as Position const angle = line.v.angleDeg() if (angle < -90 || angle >= 90) { // upside down [sourceAbove, sourceBelow] = [sourceBelow, sourceAbove] ;[targetAbove, targetBelow] = [targetBelow, targetAbove] } return { source: { above: sourceAbove, below: sourceBelow }, target: { above: targetAbove, below: targetBelow }, } } /** * Calculate the distances between center of node and edge of node. * @param sourceNodePos position of source node * @param targetNodePos position of target node * @param sourceNodeShape shape config of source node * @param targetNodeShape shape config of target node * @returns the distances */ export function calculateDistancesFromCenterOfNodeToEndOfNode( sourceNodePos: Position, targetNodePos: Position, sourceNodeShape: AnyShapeStyle, targetNodeShape: AnyShapeStyle ): [number, number] { // source side let distance1: number if (sourceNodeShape.type === "circle") { distance1 = sourceNodeShape.radius } else { distance1 = calculateDistanceToAvoidOverlapsWithRect( targetNodePos, sourceNodePos, sourceNodeShape, 1 // scale ) } // target side let distance2: number if (targetNodeShape.type === "circle") { distance2 = targetNodeShape.radius } else { distance2 = calculateDistanceToAvoidOverlapsWithRect( sourceNodePos, targetNodePos, targetNodeShape, 1 // scale ) } return [distance1, distance2] } /** * Calculates the line position to which the margin is applied. * @param linePos original position of the line * @param sourceMargin margin for source side * @param targetMargin margin for target side * @returns the line position */ export function applyMarginToLine( linePos: LinePosition, sourceMargin: number, targetMargin: number ): LinePosition { const line = V.fromLinePosition(linePos) return applyMarginToLineInner(line, sourceMargin, targetMargin) } function applyMarginToLineInner(line: V.Line, sourceMargin: number, targetMargin: number) { const normalized = line.v.clone().normalize() line.v.angle() const sv = line.source.clone().add(normalized.clone().multiplyScalar(sourceMargin)) const tv = line.target.clone().subtract(normalized.clone().multiplyScalar(targetMargin)) let [x1, y1] = sv.toArray() let [x2, y2] = tv.toArray() const check = V.toLineVector(sv, tv) if (line.v.angle() * check.angle() < 0) { // reversed const c1 = V.Vector.fromArray([(x1 + x2) / 2, (y1 + y2) / 2]) const c2 = c1.clone().add(normalized.multiplyScalar(0.5)) ;[x1, y1] = c1.toArray() ;[x2, y2] = c2.toArray() } return { x1, y1, x2, y2 } } /** * Calculates the position of a given distance along the circumference. * @param pos original position * @param center center of the circle * @param radian radius of the circle * @returns the moved position */ export function moveOnCircumference(pos: Position, center: Position, radian: number) { const { x, y } = pos const dx = x - center.x const dy = y - center.y return { x: dx * Math.cos(radian) - dy * Math.sin(radian) + center.x, y: dx * Math.sin(radian) + dy * Math.cos(radian) + center.y, } } /** * Reverse the direction of the angle. * @param theta angle * @returns reversed angle */ export function reverseAngleRadian(theta: number): number { if (theta > 0) { return -(Math.PI * 2 - theta) } else { return Math.PI * 2 + theta } } export function inverseLine(line: LinePosition): LinePosition { return { x1: line.x2, y1: line.y2, x2: line.x1, y2: line.y1 } } export function calculateBezierCurveControlPoint( p1: V.Vector, center: V.Vector, p2: V.Vector, theta0: number ): V.Vector[] { const control: V.Vector[] = [] const centerToSource = V.fromVectors(center, p1) const centerToTarget = V.fromVectors(center, p2) let theta = V.calculateRelativeAngleRadian(centerToSource, centerToTarget) if (theta0 * theta < 0) { theta = reverseAngleRadian(theta) } const middle = V.Vector.fromObject(moveOnCircumference(p1, center, -theta / 2)) const centerToMp = V.fromVectors(center, middle) const mpTangent = V.calculatePerpendicularLine(centerToMp) const theta1 = V.calculateRelativeAngleRadian(centerToSource, centerToMp) let tangent = V.calculatePerpendicularLine(centerToSource) if (Math.abs(theta1) < Math.PI / 2) { const cp = V.getIntersectionPointOfLines(tangent, mpTangent) control.push(cp) } else { // If greater than 90 degrees, go through the midpoint. const mp = V.Vector.fromObject(moveOnCircumference(middle, center, theta1 / 2)) const tangent2 = V.calculatePerpendicularLine(V.fromVectors(center, V.Vector.fromObject(mp))) const cp1 = V.getIntersectionPointOfLines(tangent, tangent2) const cp2 = V.getIntersectionPointOfLines(tangent2, mpTangent) control.push(cp1, mp, cp2) } control.push(middle) const theta2 = V.calculateRelativeAngleRadian(centerToTarget, centerToMp) tangent = V.calculatePerpendicularLine(centerToTarget) if (Math.abs(theta2) < Math.PI / 2) { const cp = V.getIntersectionPointOfLines(tangent, mpTangent) control.push(cp) } else { // If greater than 90 degrees, go through the midpoint. const mp = V.Vector.fromObject(moveOnCircumference(middle, center, theta2 / 2)) const tangent2 = V.calculatePerpendicularLine(V.fromVectors(center, V.Vector.fromObject(mp))) const cp1 = V.getIntersectionPointOfLines(mpTangent, tangent2) const cp2 = V.getIntersectionPointOfLines(tangent2, tangent) control.push(cp1, mp, cp2) } return control }
the_stack
import { Duration, Resource } from '@aws-cdk/core'; import { Construct } from 'constructs'; import { Grant } from './grant'; import { IIdentity } from './identity-base'; import { IManagedPolicy } from './managed-policy'; import { Policy } from './policy'; import { PolicyDocument } from './policy-document'; import { PolicyStatement } from './policy-statement'; import { AddToPrincipalPolicyResult, IPrincipal, PrincipalPolicyFragment } from './principals'; /** * Properties for defining an IAM Role. */ export interface RoleProps { /** * The IAM principal (i.e. `new ServicePrincipal('sns.amazonaws.com')`) which can assume this role. * * You can later modify the assume role policy document by accessing it via * the `assumeRolePolicy` property. */ readonly assumedBy: IPrincipal; /** * (deprecated) ID that the role assumer needs to provide when assuming this role. * * If the configured and provided external IDs do not match, the * AssumeRole operation will fail. * * @default No external ID required * @deprecated see {@link externalIds} */ readonly externalId?: string; /** * List of IDs that the role assumer needs to provide one of when assuming this role. * * If the configured and provided external IDs do not match, the * AssumeRole operation will fail. * * @default No external ID required */ readonly externalIds?: string[]; /** * A list of managed policies associated with this role. * * You can add managed policies later using * `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`. * * @default - No managed policies. */ readonly managedPolicies?: IManagedPolicy[]; /** * A list of named policies to inline into this role. * * These policies will be * created with the role, whereas those added by ``addToPolicy`` are added * using a separate CloudFormation resource (allowing a way around circular * dependencies that could otherwise be introduced). * * @default - No policy is inlined in the Role resource. */ readonly inlinePolicies?: { [name: string]: PolicyDocument; }; /** * The path associated with this role. * * For information about IAM paths, see * Friendly Names and Paths in IAM User Guide. * * @default / */ readonly path?: string; /** * AWS supports permissions boundaries for IAM entities (users or roles). * * A permissions boundary is an advanced feature for using a managed policy * to set the maximum permissions that an identity-based policy can grant to * an IAM entity. An entity's permissions boundary allows it to perform only * the actions that are allowed by both its identity-based policies and its * permissions boundaries. * * @default - No permissions boundary. * @link https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html */ readonly permissionsBoundary?: IManagedPolicy; /** * A name for the IAM role. * * For valid values, see the RoleName parameter for * the CreateRole action in the IAM API Reference. * * IMPORTANT: If you specify a name, you cannot perform updates that require * replacement of this resource. You can perform updates that require no or * some interruption. If you must replace the resource, specify a new name. * * If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to * acknowledge your template's capabilities. For more information, see * Acknowledging IAM Resources in AWS CloudFormation Templates. * * @default - AWS CloudFormation generates a unique physical ID and uses that ID * for the role name. */ readonly roleName?: string; /** * The maximum session duration that you want to set for the specified role. * * This setting can have a value from 1 hour (3600sec) to 12 (43200sec) hours. * * Anyone who assumes the role from the AWS CLI or API can use the * DurationSeconds API parameter or the duration-seconds CLI parameter to * request a longer session. The MaxSessionDuration setting determines the * maximum duration that can be requested using the DurationSeconds * parameter. * * If users don't specify a value for the DurationSeconds parameter, their * security credentials are valid for one hour by default. This applies when * you use the AssumeRole* API operations or the assume-role* CLI operations * but does not apply when you use those operations to create a console URL. * * @default Duration.hours(1) * @link https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html */ readonly maxSessionDuration?: Duration; /** * A description of the role. * * It can be up to 1000 characters long. * * @default - No description. */ readonly description?: string; } /** * Options allowing customizing the behavior of {@link Role.fromRoleArn}. */ export interface FromRoleArnOptions { /** * (experimental) Whether the imported role can be modified by attaching policy resources to it. * * @default true * @experimental */ readonly mutable?: boolean; } /** * IAM Role. * * Defines an IAM role. The role is created with an assume policy document associated with * the specified AWS service principal defined in `serviceAssumeRole`. */ export declare class Role extends Resource implements IRole { /** * Import an external role by ARN. * * If the imported Role ARN is a Token (such as a * `CfnParameter.valueAsString` or a `Fn.importValue()`) *and* the referenced * role has a `path` (like `arn:...:role/AdminRoles/Alice`), the * `roleName` property will not resolve to the correct value. Instead it * will resolve to the first path component. We unfortunately cannot express * the correct calculation of the full path name as a CloudFormation * expression. In this scenario the Role ARN should be supplied without the * `path` in order to resolve the correct role resource. * * @param scope construct scope. * @param id construct id. * @param roleArn the ARN of the role to import. * @param options allow customizing the behavior of the returned role. */ static fromRoleArn(scope: Construct, id: string, roleArn: string, options?: FromRoleArnOptions): IRole; /** * The principal to grant permissions to. */ readonly grantPrincipal: IPrincipal; /** * The AWS account ID of this principal. * * Can be undefined when the account is not known * (for example, for service principals). * Can be a Token - in that case, * it's assumed to be AWS::AccountId. */ readonly principalAccount: string | undefined; /** * When this Principal is used in an AssumeRole policy, the action to use. */ readonly assumeRoleAction: string; /** * The assume role policy document associated with this role. */ readonly assumeRolePolicy?: PolicyDocument; /** * Returns the ARN of this role. */ readonly roleArn: string; /** * Returns the stable and unique string identifying the role. * * For example, * AIDAJQABLZS4A3QDU576Q. * * @attribute true */ readonly roleId: string; /** * Returns the name of the role. */ readonly roleName: string; /** * Returns the role. */ readonly policyFragment: PrincipalPolicyFragment; /** * Returns the permissions boundary attached to this role. */ readonly permissionsBoundary?: IManagedPolicy; private defaultPolicy?; private readonly managedPolicies; private readonly attachedPolicies; private readonly inlinePolicies; private immutableRole?; /** * */ constructor(scope: Construct, id: string, props: RoleProps); /** * Adds a permission to the role's default policy document. * * If there is no default policy attached to this role, it will be created. * * @param statement The permission statement to add to the policy document. */ addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult; /** * Add to the policy of this principal. */ addToPolicy(statement: PolicyStatement): boolean; /** * Attaches a managed policy to this role. * * @param policy The the managed policy to attach. */ addManagedPolicy(policy: IManagedPolicy): void; /** * Attaches a policy to this role. * * @param policy The policy to attach. */ attachInlinePolicy(policy: Policy): void; /** * Grant the actions defined in actions to the identity Principal on this resource. */ grant(grantee: IPrincipal, ...actions: string[]): Grant; /** * Grant permissions to the given principal to pass this role. */ grantPassRole(identity: IPrincipal): Grant; /** * Return a copy of this Role object whose Policies will not be updated. * * Use the object returned by this method if you want this Role to be used by * a construct without it automatically updating the Role's Policies. * * If you do, you are responsible for adding the correct statements to the * Role's policies yourself. */ withoutPolicyUpdates(): IRole; /** * Validate the current construct. * * This method can be implemented by derived constructs in order to perform * validation logic. It is called on all constructs before synthesis. */ protected validate(): string[]; } /** * A Role object. */ export interface IRole extends IIdentity { /** * Returns the ARN of this role. * * @attribute true */ readonly roleArn: string; /** * Returns the name of this role. * * @attribute true */ readonly roleName: string; /** * Grant the actions defined in actions to the identity Principal on this resource. */ grant(grantee: IPrincipal, ...actions: string[]): Grant; /** * Grant permissions to the given principal to pass this role. */ grantPassRole(grantee: IPrincipal): Grant; }
the_stack
import { Transaction } from '@ethereumjs/tx' import Web3 from 'web3' import axios from 'axios' import chai from 'chai' import chaiAsPromised from 'chai-as-promised' import express from 'express' import sinon from 'sinon' import sinonChai from 'sinon-chai' import { ChildProcessWithoutNullStreams } from 'child_process' import { HttpProvider } from 'web3-core' import { PrefixedHexString, toBuffer } from 'ethereumjs-util' import { RelayHubInstance, PenalizerInstance, TestTokenInstance, StakeManagerInstance, TestRecipientInstance, TestPaymasterEverythingAcceptedInstance } from '@opengsn/contracts/types/truffle-contracts' import { RelayRequest } from '@opengsn/common/dist/EIP712/RelayRequest' import { _dumpRelayingResult, GSNUnresolvedConstructorInput, RelayClient, EmptyDataCallback } from '@opengsn/provider/dist/RelayClient' import { Address, Web3ProviderBaseInterface } from '@opengsn/common/dist/types/Aliases' import { defaultGsnConfig, GSNConfig, LoggerConfiguration } from '@opengsn/provider/dist/GSNConfigurator' import { replaceErrors } from '@opengsn/common/dist/ErrorReplacerJSON' import { GsnTransactionDetails } from '@opengsn/common/dist/types/GsnTransactionDetails' import { BadHttpClient } from '../dummies/BadHttpClient' import { BadRelayedTransactionValidator } from '../dummies/BadRelayedTransactionValidator' import { configureGSN, deployHub, emptyBalance, revert, snapshot, startRelay, stopRelay } from '../TestUtils' import { RelayInfo } from '@opengsn/common/dist/types/RelayInfo' import { PingResponse } from '@opengsn/common/dist/PingResponse' import { registerForwarderForGsn } from '@opengsn/common/dist/EIP712/ForwarderUtil' import { GsnEvent } from '@opengsn/provider/dist/GsnEvents' import bodyParser from 'body-parser' import { Server } from 'http' import { HttpClient } from '@opengsn/common/dist/HttpClient' import { HttpWrapper } from '@opengsn/common/dist/HttpWrapper' import { RelayTransactionRequest } from '@opengsn/common/dist/types/RelayTransactionRequest' import { createClientLogger } from '@opengsn/provider/dist/ClientWinstonLogger' import { LoggerInterface } from '@opengsn/common/dist/LoggerInterface' import { ether } from '@openzeppelin/test-helpers' import { BadContractInteractor } from '../dummies/BadContractInteractor' import { ContractInteractor } from '@opengsn/common/dist/ContractInteractor' import { defaultEnvironment } from '@opengsn/common/dist/Environments' import { RelayRegistrarInstance } from '@opengsn/contracts' import { constants, splitRelayUrlForRegistrar } from '@opengsn/common' import { ConfigResponse } from '@opengsn/common/dist/ConfigResponse' const StakeManager = artifacts.require('StakeManager') const Penalizer = artifacts.require('Penalizer') const TestRecipient = artifacts.require('TestRecipient') const TestToken = artifacts.require('TestToken') const TestPaymasterEverythingAccepted = artifacts.require('TestPaymasterEverythingAccepted') const Forwarder = artifacts.require('Forwarder') const RelayRegistrar = artifacts.require('RelayRegistrar') const { expect, assert } = chai.use(chaiAsPromised) chai.use(sinonChai) const localhostOne = 'http://localhost:8090' const localhost127One = 'http://127.0.0.1:8090' const underlyingProvider = web3.currentProvider as HttpProvider class MockHttpClient extends HttpClient { constructor (readonly mockPort: number, logger: LoggerInterface, httpWrapper: HttpWrapper, config: Partial<GSNConfig>) { super(httpWrapper, logger) } async relayTransaction (relayUrl: string, request: RelayTransactionRequest): Promise<PrefixedHexString> { return await super.relayTransaction(this.mapUrl(relayUrl), request) } private mapUrl (relayUrl: string): string { return relayUrl.replace(':8090', `:${this.mockPort}`) } } contract('RelayClient', function (accounts) { let web3: Web3 let relayHub: RelayHubInstance let relayRegistrar: RelayRegistrarInstance let stakeManager: StakeManagerInstance let penalizer: PenalizerInstance let testRecipient: TestRecipientInstance let testToken: TestTokenInstance let paymaster: TestPaymasterEverythingAcceptedInstance const gasLess = accounts[10] let relayProcess: ChildProcessWithoutNullStreams let forwarderAddress: Address let logger: LoggerInterface let relayClient: RelayClient let gsnConfig: Partial<GSNConfig> let options: GsnTransactionDetails let to: Address let from: Address let data: PrefixedHexString let gsnEvents: GsnEvent[] = [] const stake = ether('1') const cheapRelayerUrl = 'http://localhost:54321' // register a very cheap relayer, so client will attempt to use it first. async function registerCheapRelayer (testToken: TestTokenInstance, relayHub: RelayHubInstance): Promise<void> { const relayWorker = '0x'.padEnd(42, '2') const relayOwner = accounts[3] const relayManager = accounts[4] await testToken.mint(stake, { from: relayOwner }) await testToken.approve(stakeManager.address, stake, { from: relayOwner }) await stakeManager.setRelayManagerOwner(relayOwner, { from: relayManager }) await stakeManager.stakeForRelayManager(testToken.address, relayManager, 15000, stake, { from: relayOwner }) await stakeManager.authorizeHubByOwner(relayManager, relayHub.address, { from: relayOwner }) await relayHub.addRelayWorkers([relayWorker], { from: relayManager }) await relayRegistrar.registerRelayServer(relayHub.address, 1, 1, splitRelayUrlForRegistrar(cheapRelayerUrl), { from: relayManager }) } before(async function () { web3 = new Web3(underlyingProvider) testToken = await TestToken.new() stakeManager = await StakeManager.new(defaultEnvironment.maxUnstakeDelay, 0, 0, constants.BURN_ADDRESS, constants.BURN_ADDRESS) penalizer = await Penalizer.new(defaultEnvironment.penalizerConfiguration.penalizeBlockDelay, defaultEnvironment.penalizerConfiguration.penalizeBlockExpiration) relayHub = await deployHub(stakeManager.address, penalizer.address, constants.ZERO_ADDRESS, testToken.address, stake.toString()) relayRegistrar = await RelayRegistrar.at(await relayHub.getRelayRegistrar()) const forwarderInstance = await Forwarder.new() forwarderAddress = forwarderInstance.address testRecipient = await TestRecipient.new(forwarderAddress) // register hub's RelayRequest with forwarder, if not already done. await registerForwarderForGsn(forwarderInstance) paymaster = await TestPaymasterEverythingAccepted.new() await paymaster.setTrustedForwarder(forwarderAddress) await paymaster.setRelayHub(relayHub.address) await paymaster.deposit({ value: web3.utils.toWei('1', 'ether') }) await testToken.mint(stake, { from: accounts[1] }) await testToken.approve(stakeManager.address, stake, { from: accounts[1] }) relayProcess = await startRelay(relayHub.address, testToken, stakeManager, { initialReputation: 100, stake: 1e18.toString(), relayOwner: accounts[1], ethereumNodeUrl: underlyingProvider.host }) const loggerConfiguration: LoggerConfiguration = { logLevel: 'debug' } gsnConfig = { loggerConfiguration, performDryRunViewRelayCall: false, paymasterAddress: paymaster.address } logger = createClientLogger(loggerConfiguration) relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig }) await relayClient.init() await emptyBalance(gasLess, accounts[0]) from = gasLess to = testRecipient.address data = testRecipient.contract.methods.emitMessage('hello world').encodeABI() options = { from, to, data, paymasterData: '0x', clientId: '1', maxFeePerGas: '0', maxPriorityFeePerGas: '0' } }) beforeEach(async function () { const { maxFeePerGas, maxPriorityFeePerGas } = await relayClient.calculateGasFees() options = { ...options, maxFeePerGas, maxPriorityFeePerGas } }) after(function () { stopRelay(relayProcess) }) describe('#_initInternal()', () => { it('should set metamask defaults', async () => { const metamaskProvider: Web3ProviderBaseInterface = { // @ts-ignore isMetaMask: true, send: (options: any, cb: any) => { (web3.currentProvider as any).send(options, cb) } } const constructorInput: GSNUnresolvedConstructorInput = { provider: metamaskProvider, config: { paymasterAddress: paymaster.address } } const anotherRelayClient = new RelayClient(constructorInput) assert.equal(anotherRelayClient.config, undefined) await anotherRelayClient._initInternal() assert.equal(anotherRelayClient.config.methodSuffix, '_v4') assert.equal(anotherRelayClient.config.jsonStringifyRequest, true) }) it('should allow to override metamask defaults', async () => { const minMaxPriorityFeePerGas = 777 const suffix = 'suffix' const metamaskProvider = { isMetaMask: true, send: (options: any, cb: any) => { (web3.currentProvider as any).send(options, cb) } } const constructorInput: GSNUnresolvedConstructorInput = { provider: metamaskProvider, config: { minMaxPriorityFeePerGas: minMaxPriorityFeePerGas, paymasterAddress: paymaster.address, methodSuffix: suffix, jsonStringifyRequest: 5 as any } } const anotherRelayClient = new RelayClient(constructorInput) assert.equal(anotherRelayClient.config, undefined) // note: to check boolean override, we explicitly set it to something that // is not in the defaults.. await anotherRelayClient._initInternal() assert.equal(anotherRelayClient.config.methodSuffix, suffix) assert.equal(anotherRelayClient.config.jsonStringifyRequest as any, 5) assert.equal(anotherRelayClient.config.minMaxPriorityFeePerGas, minMaxPriorityFeePerGas) assert.equal(anotherRelayClient.config.sliceSize, defaultGsnConfig.sliceSize, 'default value expected for a skipped field') }) }) describe('#relayTransaction()', function () { it('should warn if called relayTransaction without calling init first', async function () { const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig }) sinon.spy(relayClient, '_warn') try { await relayClient.relayTransaction(options) expect(relayClient._warn).to.have.been.calledWithMatch(/.*call.*RelayClient.init*/) } finally { // @ts-ignore relayClient._warn.restore() } }) it('should not warn if called "new RelayClient().init()"', async function () { const relayClient = await new RelayClient({ provider: underlyingProvider, config: gsnConfig }).init() sinon.spy(relayClient, '_warn') try { await relayClient.relayTransaction(options) expect(relayClient._warn).to.have.not.been.called } finally { // @ts-ignore relayClient._warn.restore() } }) it('should send transaction to a relay and receive a signed transaction in response', async function () { const relayingResult = await relayClient.relayTransaction(options) const validTransaction = relayingResult.transaction if (validTransaction == null) { assert.fail(`validTransaction is null: ${JSON.stringify(relayingResult, replaceErrors)}`) return } const validTransactionHash: string = validTransaction.hash().toString('hex') const txHash = `0x${validTransactionHash}` const res = await web3.eth.getTransactionReceipt(txHash) // validate we've got the "SampleRecipientEmitted" event // TODO: use OZ test helpers const topic: string = web3.utils.sha3('SampleRecipientEmitted(string,address,address,address,uint256,uint256,uint256)') ?? '' assert.ok(res.logs.find(log => log.topics.includes(topic)), 'log not found') const destination: string = validTransaction.to!.toString() assert.equal(destination, relayHub.address.toString().toLowerCase()) }) it('should skip timed-out server', async function () { let server: Server | undefined try { const pingResponse = await axios.get('http://localhost:8090/getaddr').then(res => res.data) const mockServer = express() mockServer.use(bodyParser.urlencoded({ extended: false })) mockServer.use(bodyParser.json()) // used to work before workspaces, needs research // eslint-disable-next-line @typescript-eslint/no-misused-promises mockServer.get('/getaddr', async (req, res) => { console.log('=== got GET ping', req.query) res.send(pingResponse) }) mockServer.post('/relay', () => { console.log('== got relay.. ignoring') // don't answer... keeping client in limbo }) await new Promise((resolve) => { // @ts-ignore server = mockServer.listen(0, resolve) }) const mockServerPort = (server as any).address().port // MockHttpClient alter the server port, so the client "thinks" it works with relayUrl, but actually // it uses the mockServer's port const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { httpClient: new MockHttpClient(mockServerPort, logger, new HttpWrapper({ timeout: 100 }), gsnConfig) } }) await relayClient.init() // async relayTransaction (relayUrl: string, request: RelayTransactionRequest): Promise<PrefixedHexString> { const relayingResult = await relayClient.relayTransaction(options) assert.match(_dumpRelayingResult(relayingResult), /timeout.*exceeded/) } finally { server?.close() } }) it('should return errors encountered in ping', async function () { const badHttpClient = new BadHttpClient(logger, true, false, false) const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { httpClient: badHttpClient } }) await relayClient.init() const { transaction, relayingErrors, pingErrors } = await relayClient.relayTransaction(options) assert.isUndefined(transaction) assert.equal(relayingErrors.size, 0) assert.equal(pingErrors.size, 1) assert.equal(pingErrors.get(localhostOne)!.message, BadHttpClient.message) }) it('should return errors encountered in relaying', async function () { const badHttpClient = new BadHttpClient(logger, false, true, false) const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { httpClient: badHttpClient } }) await relayClient.init() const { transaction, relayingErrors, pingErrors } = await relayClient.relayTransaction(options) assert.isUndefined(transaction) assert.equal(pingErrors.size, 0) assert.equal(relayingErrors.size, 1) assert.equal(relayingErrors.get(localhostOne)!.message, BadHttpClient.message) }) it('should abort scanning if user cancels signature request', async () => { const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig }) await relayClient.init() // @ts-ignore const getRelayInfoForManagers = sinon.stub(relayClient.dependencies.knownRelaysManager, 'getRelayInfoForManagers') const mockRelays = [ { relayUrl: localhostOne, relayManager: '0x'.padEnd(42, '1'), baseRelayFee: '0', pctRelayFee: '70' }, { relayUrl: localhost127One, relayManager: '0x'.padEnd(42, '2'), baseRelayFee: '0', pctRelayFee: '70' } ] getRelayInfoForManagers.returns(Promise.resolve(mockRelays)) sinon.stub(relayClient.dependencies.accountManager, 'sign').onCall(0).throws(new Error('client sig failure')) const { transaction, relayingErrors, pingErrors } = await relayClient.relayTransaction(options) assert.isUndefined(transaction) assert.equal(pingErrors.size, 0) assert.equal(relayingErrors.size, 1) assert.equal(relayingErrors.get(localhost127One)!.message, 'client sig failure') }) it('should continue scanning if returned relayer TX is malformed', async () => { const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig }) await relayClient.init() // @ts-ignore const getRelayInfoForManagers = sinon.stub(relayClient.dependencies.knownRelaysManager, 'getRelayInfoForManagers') const mockRelays = [ { relayUrl: localhostOne, relayManager: '0x'.padEnd(42, '1'), baseRelayFee: '70', pctRelayFee: '70' }, { relayUrl: localhost127One, relayManager: '0x'.padEnd(42, '2'), baseRelayFee: '70', pctRelayFee: '70' } ] getRelayInfoForManagers.returns(Promise.resolve(mockRelays)) sinon.stub(relayClient.dependencies.transactionValidator, 'validateRelayResponse').throws(new Error('fail returned tx')) const { transaction, relayingErrors, pingErrors } = await relayClient.relayTransaction(options) assert.isUndefined(transaction) assert.equal(pingErrors.size, 0) assert.equal(relayingErrors.size, 2) assert.equal(Array.from(relayingErrors.values())[0]!.message, 'fail returned tx') }) it('should continue looking up relayers after relayer error', async function () { const badHttpClient = new BadHttpClient(logger, false, true, false) const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { httpClient: badHttpClient } }) await relayClient.init() // @ts-ignore const getRelayInfoForManagers = sinon.stub(relayClient.dependencies.knownRelaysManager, 'getRelayInfoForManagers') const mockRelays = [ { relayUrl: localhostOne, relayManager: '0x'.padEnd(42, '1'), baseRelayFee: '0', pctRelayFee: '70' }, { relayUrl: localhost127One, relayManager: '0x'.padEnd(42, '2'), baseRelayFee: '0', pctRelayFee: '70' } ] getRelayInfoForManagers.returns(Promise.resolve(mockRelays)) const { transaction, relayingErrors, pingErrors } = await relayClient.relayTransaction(options) assert.isUndefined(transaction) assert.equal(pingErrors.size, 0) assert.equal(relayingErrors.size, 2) assert.equal(relayingErrors.get(localhostOne)!.message, BadHttpClient.message) }) it('should return errors in callback (asyncApprovalData) ', async function () { const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { asyncApprovalData: async () => { throw new Error('approval-error') } } }) await relayClient.init() const { transaction, relayingErrors, pingErrors } = await relayClient.relayTransaction(options) assert.isUndefined(transaction) assert.equal(pingErrors.size, 0) assert.equal(relayingErrors.size, 1) assert.match(relayingErrors.values().next().value.message, /approval-error/) }) it('should return errors in callback (asyncPaymasterData) ', async function () { const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { asyncPaymasterData: async () => { throw new Error('paymasterData-error') } } }) await relayClient.init() const { transaction, relayingErrors, pingErrors } = await relayClient.relayTransaction(options) assert.isUndefined(transaction) assert.equal(pingErrors.size, 0) assert.equal(relayingErrors.size, 1) assert.equal(relayingErrors.keys().next().value, constants.DRY_RUN_KEY) assert.match(relayingErrors.values().next().value.message, /paymasterData-error/) }) it.skip('should return errors in callback (scoreCalculator) ', async function () { // can't be used: scoring is completely disabled const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { scoreCalculator: async () => { throw new Error('score-error') } } }) await relayClient.init() const ret = await relayClient.relayTransaction(options) const { transaction, relayingErrors, pingErrors } = ret assert.isUndefined(transaction) assert.equal(pingErrors.size, 0) assert.equal(relayingErrors.size, 1) assert.match(relayingErrors.values().next().value.message, /score-error/) }) describe('with events listener', () => { function eventsHandler (e: GsnEvent): void { gsnEvents.push(e) } before('registerEventsListener', async () => { relayClient = await new RelayClient({ provider: underlyingProvider, config: gsnConfig }).init() relayClient.registerEventListener(eventsHandler) }) it('should call all events handler', async function () { await relayClient.relayTransaction(options) assert.equal(gsnEvents.length, 7) assert.equal(gsnEvents[0].step, 1) assert.equal(gsnEvents[0].total, 7) assert.equal(gsnEvents[6].step, 7) }) describe('removing events listener', () => { before('registerEventsListener', () => { gsnEvents = [] relayClient.unregisterEventListener(eventsHandler) }) it('should call events handler', async function () { await relayClient.relayTransaction(options) assert.equal(gsnEvents.length, 0) }) }) }) }) describe('#_calculateDefaultGasPrice()', function () { it('should use minimum gas price if calculated is too low', async function () { const minMaxPriorityFeePerGas = 1e18 const gsnConfig: Partial<GSNConfig> = { loggerConfiguration: { logLevel: 'error' }, paymasterAddress: paymaster.address, minMaxPriorityFeePerGas: minMaxPriorityFeePerGas } const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig }) await relayClient.init() const calculatedGasPrice = await relayClient.calculateGasFees() assert.equal(calculatedGasPrice.maxPriorityFeePerGas, `0x${minMaxPriorityFeePerGas.toString(16)}`) }) }) describe('#_attemptRelay()', function () { const relayUrl = localhostOne const relayWorkerAddress = accounts[1] const relayManager = accounts[2] const relayOwner = accounts[3] let pingResponse: PingResponse let relayInfo: RelayInfo let optionsWithGas: GsnTransactionDetails before(async function () { await testToken.mint(stake, { from: relayOwner }) await testToken.approve(stakeManager.address, stake, { from: relayOwner }) await stakeManager.setRelayManagerOwner(relayOwner, { from: relayManager }) await stakeManager.stakeForRelayManager(testToken.address, relayManager, 7 * 24 * 3600, stake, { from: relayOwner }) await stakeManager.authorizeHubByOwner(relayManager, relayHub.address, { from: relayOwner }) await relayHub.addRelayWorkers([relayWorkerAddress], { from: relayManager }) await relayRegistrar.registerRelayServer(relayHub.address, 2e16.toString(), '10', splitRelayUrlForRegistrar('url'), { from: relayManager }) await relayHub.depositFor(paymaster.address, { value: (2e18).toString() }) pingResponse = { ownerAddress: relayOwner, relayWorkerAddress: relayWorkerAddress, relayManagerAddress: relayManager, relayHubAddress: relayManager, minMaxPriorityFeePerGas: '', maxAcceptanceBudget: 1e10.toString(), ready: true, version: '' } relayInfo = { relayInfo: { relayManager, relayUrl, baseRelayFee: '0', pctRelayFee: '0' }, pingResponse } optionsWithGas = Object.assign({}, options, { gas: '0xf4240', maxFeePerGas: '0x51f4d5c00', maxPriorityFeePerGas: '0x51f4d5c00' }) }) it('should return error if view call to \'relayCall()\' fails', async function () { const maxPageSize = Number.MAX_SAFE_INTEGER const badContractInteractor = new BadContractInteractor({ environment: defaultEnvironment, provider: web3.currentProvider as HttpProvider, logger, maxPageSize, deployment: { paymasterAddress: gsnConfig.paymasterAddress } }, true) await badContractInteractor.init() const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { contractInteractor: badContractInteractor } }) await relayClient.init() const relayRequest = await relayClient._prepareRelayRequest(optionsWithGas) const { transaction, error, isRelayError } = await relayClient._attemptRelay(relayInfo, relayRequest) assert.isUndefined(transaction) assert.isUndefined(isRelayError) // @ts-ignore assert.equal(error.message, `local view call to 'relayCall()' reverted: ${BadContractInteractor.message}`) }) it('should report relays that timeout to the Known Relays Manager', async function () { const badHttpClient = new BadHttpClient(logger, false, false, true) const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { httpClient: badHttpClient } }) await relayClient.init() // @ts-ignore (sinon allows spying on all methods of the object, but TypeScript does not seem to know that) sinon.spy(relayClient.dependencies.knownRelaysManager) const relayRequest = await relayClient._prepareRelayRequest(optionsWithGas) const attempt = await relayClient._attemptRelay(relayInfo, relayRequest) assert.equal(attempt.isRelayError, true, 'timeout should not abort relay search') assert.equal(attempt.error?.message, 'some error describing how timeout occurred somewhere') expect(relayClient.dependencies.knownRelaysManager.saveRelayFailure).to.have.been.calledWith(sinon.match.any, relayManager, relayUrl) }) it('should not report relays if error is not timeout', async function () { const badHttpClient = new BadHttpClient(logger, false, true, false) const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { httpClient: badHttpClient } }) await relayClient.init() // @ts-ignore (sinon allows spying on all methods of the object, but TypeScript does not seem to know that) sinon.spy(relayClient.dependencies.knownRelaysManager) const relayRequest = await relayClient._prepareRelayRequest(optionsWithGas) await relayClient._attemptRelay(relayInfo, relayRequest) expect(relayClient.dependencies.knownRelaysManager.saveRelayFailure).to.have.not.been.called }) it('should return error if transaction returned by a relay does not pass validation', async function () { const maxPageSize = Number.MAX_SAFE_INTEGER const contractInteractor = await new ContractInteractor({ environment: defaultEnvironment, provider: web3.currentProvider as HttpProvider, logger, maxPageSize, deployment: { paymasterAddress: paymaster.address } }).init() const badHttpClient = new BadHttpClient(logger, false, false, false, pingResponse, '0xc6808080808080') const badTransactionValidator = new BadRelayedTransactionValidator(logger, true, contractInteractor, configureGSN(gsnConfig)) const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { contractInteractor, httpClient: badHttpClient, transactionValidator: badTransactionValidator } }) await relayClient.init() // @ts-ignore (sinon allows spying on all methods of the object, but TypeScript does not seem to know that) sinon.spy(relayClient.dependencies.knownRelaysManager) const relayRequest = await relayClient._prepareRelayRequest(optionsWithGas) const { transaction, error, isRelayError } = await relayClient._attemptRelay(relayInfo, relayRequest) assert.isUndefined(transaction) assert.equal(isRelayError, true) // @ts-ignore assert.equal(error.message, 'Returned transaction did not pass validation') expect(relayClient.dependencies.knownRelaysManager.saveRelayFailure).to.have.been.calledWith(sinon.match.any, relayManager, relayUrl) }) describe('#_prepareRelayHttpRequest()', function () { const asyncApprovalData = async function (_: RelayRequest): Promise<PrefixedHexString> { return await Promise.resolve('0x1234567890') } const asyncPaymasterData = async function (_: RelayRequest): Promise<PrefixedHexString> { return await Promise.resolve('0xabcd') } it('should use provided approval function', async function () { const relayClient = new RelayClient({ provider: underlyingProvider, config: Object.assign({}, gsnConfig, { maxApprovalDataLength: 5, maxPaymasterDataLength: 2 }), overrideDependencies: { asyncApprovalData, asyncPaymasterData } }) await relayClient.init() const relayRequest = await relayClient._prepareRelayRequest(optionsWithGas) const httpRequest = await relayClient._prepareRelayHttpRequest(relayRequest, relayInfo) assert.equal(httpRequest.metadata.approvalData, '0x1234567890') assert.equal(httpRequest.relayRequest.relayData.paymasterData, '0xabcd') }) }) it('should throw if variable length parameters are bigger than reported', async function () { try { const getLongData = async function (_: RelayRequest): Promise<PrefixedHexString> { return '0x' + 'ff'.repeat(101) } relayClient.dependencies.asyncApprovalData = getLongData const relayRequest1 = await relayClient._prepareRelayRequest(optionsWithGas) await expect(relayClient._prepareRelayHttpRequest(relayRequest1, relayInfo)) .to.eventually.be.rejectedWith('actual approvalData larger than maxApprovalDataLength') relayClient.dependencies.asyncPaymasterData = getLongData const relayRequest2 = await relayClient._prepareRelayRequest(optionsWithGas) await expect(relayClient._prepareRelayHttpRequest(relayRequest2, relayInfo)) .to.eventually.be.rejectedWith('actual paymasterData larger than maxPaymasterDataLength') } finally { relayClient.dependencies.asyncApprovalData = EmptyDataCallback relayClient.dependencies.asyncPaymasterData = EmptyDataCallback } }) }) describe('#_broadcastRawTx()', function () { // TODO: TBD: there has to be other behavior then that. Maybe query the transaction with the nonce somehow? it('should return \'wrongNonce\' if broadcast fails with nonce error', async function () { const maxPageSize = Number.MAX_SAFE_INTEGER const badContractInteractor = new BadContractInteractor({ environment: defaultEnvironment, provider: underlyingProvider, logger, maxPageSize, deployment: { paymasterAddress: gsnConfig.paymasterAddress } }, true) const transaction = Transaction.fromSerializedTx(toBuffer('0xc6808080808080')) const relayClient = new RelayClient({ provider: underlyingProvider, config: gsnConfig, overrideDependencies: { contractInteractor: badContractInteractor } }) await relayClient.init() const { hasReceipt, wrongNonce, broadcastError } = await relayClient._broadcastRawTx(transaction) assert.isFalse(hasReceipt) assert.isTrue(wrongNonce) assert.equal(broadcastError?.message, BadContractInteractor.wrongNonceMessage) }) }) describe('multiple relayers', () => { let id: string before(async () => { id = (await snapshot()).result await registerCheapRelayer(testToken, relayHub) }) after(async () => { await revert(id) }) it('should succeed to relay, but report ping error', async () => { const relayingResult = await relayClient.relayTransaction(options) assert.match(relayingResult.pingErrors.get(cheapRelayerUrl)?.message as string, /ECONNREFUSED/, `relayResult: ${_dumpRelayingResult(relayingResult)}`) assert.exists(relayingResult.transaction) }) it('should use preferred relay if one is set', async () => { relayClient = new RelayClient({ provider: underlyingProvider, config: { ...gsnConfig, preferredRelays: ['http://localhost:8090'] } }) await relayClient.init() const relayingResult = await relayClient.relayTransaction(options) assert.equal(relayingResult.pingErrors.size, 0) assert.exists(relayingResult.transaction) }) }) describe('_resolveConfiguration()', function () { it('should prioritize client config in that order: config function argument, website-supplied config, default config', async function () { sinon.stub(relayClient, '_resolveConfigurationFromServer').returns(Promise.resolve({ methodSuffix: 'test suffix from _resolveConfigurationFromServer' })) const config: Partial<GSNConfig> = { methodSuffix: 'test suffix from arg' } let resolvedConfig = await relayClient._resolveConfiguration({ provider: relayClient.getUnderlyingProvider(), config }) assert.equal(resolvedConfig.methodSuffix, 'test suffix from arg') resolvedConfig = await relayClient._resolveConfiguration({ provider: relayClient.getUnderlyingProvider(), config: {} }) assert.equal(resolvedConfig.methodSuffix, 'test suffix from _resolveConfigurationFromServer') sinon.restore() sinon.stub(relayClient, '_resolveConfigurationFromServer').returns(Promise.resolve({})) resolvedConfig = await relayClient._resolveConfiguration({ provider: relayClient.getUnderlyingProvider(), config: {} }) assert.equal(resolvedConfig.methodSuffix, defaultGsnConfig.methodSuffix) sinon.restore() }) it('should not use website configuration if useClientDefaultConfigUrl is false', async function () { const spy = sinon.spy(relayClient, '_resolveConfigurationFromServer') const config: Partial<GSNConfig> = { useClientDefaultConfigUrl: false } const resolvedConfig = await relayClient._resolveConfiguration({ provider: relayClient.getUnderlyingProvider(), config }) assert.equal(resolvedConfig.methodSuffix, defaultGsnConfig.methodSuffix) sinon.assert.notCalled(spy) sinon.restore() }) describe('_resolveConfigurationFromServer()', function () { let supportedNetworks: number[] let jsonConfig: ConfigResponse before('get all supported networks', async function () { jsonConfig = await relayClient.dependencies.httpClient.getNetworkConfiguration(defaultGsnConfig.clientDefaultConfigUrl) supportedNetworks = Object.keys(jsonConfig.networks).map(k => parseInt(k)) }) it('should get configuration from opengsn for all supported networks', async function () { for (const network of supportedNetworks) { const config = await relayClient._resolveConfigurationFromServer(network, defaultGsnConfig.clientDefaultConfigUrl) const GSNConfigKeys = Object.keys(defaultGsnConfig) Object.keys(config).forEach(key => assert.isTrue(GSNConfigKeys.includes(key), `key ${key} not found in GSConfig`)) } }) it('should not throw if docs website doesn\'t respond', async function () { const spy = sinon.spy(relayClient.logger, 'error') const config = await relayClient._resolveConfigurationFromServer(supportedNetworks[0], 'https://opengsn.org/badurl') assert.deepEqual(config, {}) sinon.assert.calledWithMatch(spy, 'Could not fetch default configuration:') sinon.restore() }) }) }) context('with performDryRunViewRelayCall set to true', function () { it('should report the revert reason only once without requesting client signature', async function () { const relayClient = new RelayClient({ provider: underlyingProvider, config: { ...gsnConfig, performDryRunViewRelayCall: true } }) await relayClient.init() const getSenderNonceStub = sinon.stub(relayClient.dependencies.contractInteractor, 'getSenderNonce') getSenderNonceStub.returns(Promise.resolve('1')) const { transaction, relayingErrors, pingErrors } = await relayClient.relayTransaction(options) assert.isUndefined(transaction) assert.equal(pingErrors.size, 0) assert.equal(relayingErrors.size, 1) assert.equal(relayingErrors.keys().next().value, constants.DRY_RUN_KEY) assert.match(relayingErrors.values().next().value.message, /paymaster rejected in DRY-RUN.*FWD: nonce mismatch/s) }) }) })
the_stack
import * as promisify from '@google-cloud/promisify'; import * as assert from 'assert'; import {before, beforeEach, afterEach, describe, it} from 'mocha'; import * as proxyquire from 'proxyquire'; import * as sinon from 'sinon'; import {google} from '../protos/protos'; import * as fm from '../src/family'; import {Table} from '../src/table'; let promisified = false; const fakePromisify = Object.assign({}, promisify, { promisifyAll(klass: Function) { if (klass.name === 'Family') { promisified = true; } }, }); const sandbox = sinon.createSandbox(); describe('Bigtable/Family', () => { const FAMILY_ID = 'family-test'; const TABLE = { bigtable: { request: () => {}, }, id: 'my-table', name: 'projects/my-project/instances/my-inststance/tables/my-table', getFamilies: () => {}, createFamily: () => {}, } as {} as Table; const FAMILY_NAME = `${TABLE.name}/columnFamilies/${FAMILY_ID}`; let Family: typeof fm.Family; let family: fm.Family; let FamilyError: typeof fm.FamilyError; before(() => { const Fake = proxyquire('../src/family.js', { '@google-cloud/promisify': fakePromisify, }); Family = Fake.Family; FamilyError = Fake.FamilyError; }); beforeEach(() => { family = new Family(TABLE, FAMILY_NAME); }); afterEach(() => sandbox.restore()); describe('instantiation', () => { it('should promisify all the things', () => { assert(promisified); }); it('should localize the Bigtable instance', () => { assert.strictEqual(family.bigtable, TABLE.bigtable); }); it('should localize the Table instance', () => { assert.strictEqual(family.table, TABLE); }); it('should localize the full resource path', () => { assert.strictEqual(family.id, FAMILY_ID); }); it('should extract the family name', () => { const family = new Family(TABLE, FAMILY_ID); assert.strictEqual(family.name, FAMILY_NAME); }); it('should leave full family names unaltered and localize the id from the name', () => { const family = new Family(TABLE, FAMILY_NAME); assert.strictEqual(family.name, FAMILY_NAME); assert.strictEqual(family.id, FAMILY_ID); }); it('should throw if family id in wrong format', () => { const id = `/project/bad-project/instances/bad-instance/columnFamiles/${FAMILY_ID}`; assert.throws(() => { new Family(TABLE, id); }, Error); }); }); describe('formatRule_', () => { it('should capture the max age option', () => { const originalRule = { age: 10, }; const rule = Family.formatRule_(originalRule); assert.deepStrictEqual(rule, { maxAge: originalRule.age, }); }); it('should capture the max number of versions option', () => { const originalRule = { versions: 10, }; const rule = Family.formatRule_(originalRule); assert.deepStrictEqual(rule, { maxNumVersions: originalRule.versions, }); }); it('should create a union rule', () => { const originalRule = { age: 10, versions: 2, union: true, }; const rule = Family.formatRule_(originalRule); assert.deepStrictEqual(rule, { union: { rules: [ { maxAge: originalRule.age, }, { maxNumVersions: originalRule.versions, }, ], }, }); }); it('should create an intersecting rule', () => { const originalRule = { age: 10, versions: 2, }; const rule = Family.formatRule_(originalRule); assert.deepStrictEqual(rule, { intersection: { rules: [ { maxAge: originalRule.age, }, { maxNumVersions: originalRule.versions, }, ], }, }); }); it('should allow nested rules', () => { const originalRule = { age: 10, rule: {age: 30, versions: 2}, union: true, }; const rule = Family.formatRule_(originalRule); assert.deepStrictEqual(rule, { union: { rules: [ {maxAge: originalRule.age}, { intersection: { rules: [ {maxAge: originalRule.rule.age}, {maxNumVersions: originalRule.rule.versions}, ], }, }, ], }, }); }); it('should throw if union only has one rule', () => { assert.throws(() => { Family.formatRule_({age: 10, union: true}); }, /A union must have more than one garbage collection rule\./); }); it('should throw if no rules are provided', () => { assert.throws(() => { Family.formatRule_({}); }, /No garbage collection rules were specified\./); }); }); describe('create', () => { it('should call createFamily from table', done => { const options = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any (family as any).table.createFamily = ( id: string, options_: {}, callback: Function ) => { assert.strictEqual(id, family.id); assert.strictEqual(options_, options); callback(); // done() }; family.create(options, done); }); it('should not require options', done => { // eslint-disable-next-line @typescript-eslint/no-explicit-any (family as any).table.createFamily = ( name: string, options: {}, callback: Function ) => { assert.deepStrictEqual(options, {}); callback(); // done() }; family.create(done); }); }); describe('delete', () => { it('should make the correct request', done => { sandbox.stub(family.bigtable, 'request').callsFake((config, callback) => { assert.strictEqual(config.client, 'BigtableTableAdminClient'); assert.strictEqual(config.method, 'modifyColumnFamilies'); assert.deepStrictEqual(config.reqOpts, { name: family.table.name, modifications: [ { id: family.id, drop: true, }, ], }); assert.deepStrictEqual(config.gaxOpts, {}); callback!(null); // done() }); family.delete(done); }); it('should accept gaxOptions', done => { const gaxOptions = {}; sandbox.stub(family.bigtable, 'request').callsFake(config => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }); family.delete(gaxOptions, assert.ifError); }); }); describe('exists', () => { it('should not require gaxOptions', done => { sandbox.stub(family, 'getMetadata').callsFake(gaxOptions => { assert.deepStrictEqual(gaxOptions, {}); done(); }); family.exists(assert.ifError); }); it('should pass gaxOptions to getMetadata', done => { const gaxOptions = {}; sandbox.stub(family, 'getMetadata').callsFake(gaxOptions_ => { assert.strictEqual(gaxOptions_, gaxOptions); done(); }); family.exists(gaxOptions, assert.ifError); }); it('should return false if FamilyError', done => { const error = new FamilyError('Error.'); sandbox.stub(family, 'getMetadata').callsArgWith(1, error); family.exists((err, exists) => { assert.ifError(err); assert.strictEqual(exists, false); done(); }); }); it('should return error if not FamilyError', done => { const error = new Error('Error.'); sandbox.stub(family, 'getMetadata').callsArgWith(1, error); family.exists(err => { assert.strictEqual(err, error); done(); }); }); it('should return true if no error', done => { sandbox.stub(family, 'getMetadata').callsArgWith(1, null, {}); family.exists((err, exists) => { assert.ifError(err); assert.strictEqual(exists, true); done(); }); }); }); describe('get', () => { it('should call getMetadata', done => { const options = { gaxOptions: {}, }; sandbox.stub(family, 'getMetadata').callsFake(gaxOptions => { assert.strictEqual(gaxOptions, options.gaxOptions); done(); }); family.get(options, assert.ifError); }); it('should not require an options object', done => { sandbox.stub(family, 'getMetadata').callsFake(gaxOptions => { assert.deepStrictEqual(gaxOptions, undefined); done(); }); family.get(assert.ifError); }); it('should auto create with a FamilyError error', done => { const error = new FamilyError(TABLE.id); const options = { autoCreate: true, gaxOptions: {}, }; sandbox.stub(family, 'getMetadata').callsArgOnWith(1, error); // eslint-disable-next-line @typescript-eslint/no-explicit-any (family as any).create = (options_: any, callback: Function) => { assert.strictEqual(options_.gaxOptions, options.gaxOptions); callback(); }; family.get(options, done); }); it('should pass the rules when auto creating', done => { const error = new FamilyError(TABLE.id); const options = { autoCreate: true, rule: { versions: 1, }, }; sandbox.stub(family, 'getMetadata').callsArgWith(1, error); // eslint-disable-next-line @typescript-eslint/no-explicit-any (family as any).create = (options_: {}, callback: Function) => { assert.deepStrictEqual(options.rule, {versions: 1}); callback(); }; family.get(options, done); }); it('should not auto create without a FamilyError error', done => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const error: any = new Error('Error.'); error.code = 'NOT-5'; const options = { autoCreate: true, }; sandbox.stub(family, 'getMetadata').callsArgWith(1, error); family.create = () => { throw new Error('Should not create.'); }; family.get(options, err => { assert.strictEqual(err, error); done(); }); }); it('should not auto create unless requested', done => { const error = new FamilyError(TABLE.id); sandbox.stub(family, 'getMetadata').callsArgWith(1, error); family.create = () => { throw new Error('Should not create.'); }; family.get(err => { assert.strictEqual(err, error); done(); }); }); it('should return an error from getMetadata', done => { const error = new Error('Error.'); sandbox.stub(family, 'getMetadata').callsArgWith(1, error); family.get(err => { assert.strictEqual(err, error); done(); }); }); it('should return self and API response', done => { const apiResponse = {}; sandbox.stub(family, 'getMetadata').callsArgWith(1, null, apiResponse); family.get((err, family_, apiResponse_) => { assert.ifError(err); assert.strictEqual(family_, family); assert.strictEqual(apiResponse_, apiResponse); done(); }); }); }); describe('getMetadata', () => { it('should accept gaxOptions', done => { const gaxOptions = {}; sandbox.stub(family.table, 'getFamilies').callsFake(gaxOptions_ => { assert.strictEqual(gaxOptions_, gaxOptions); done(); }); family.getMetadata(gaxOptions, assert.ifError); }); it('should return an error to the callback', done => { const err = new Error('err'); const response = {}; sandbox .stub(family.table, 'getFamilies') .callsArgWith(1, err, null, response); family.getMetadata(err_ => { assert.strictEqual(err, err_); done(); }); }); it('should update the metadata', done => { const family = new Family(TABLE, FAMILY_NAME); family.metadata = { a: 'a', b: 'b', } as google.bigtable.admin.v2.IColumnFamily; sandbox.stub(family.table, 'getFamilies').callsArgWith(1, null, [family]); family.getMetadata((err, metadata) => { assert.ifError(err); assert.strictEqual(metadata, family.metadata); done(); }); }); it('should return a custom error if no results', done => { sandbox.stub(family.table, 'getFamilies').callsArgWith(1, null, []); family.getMetadata(err => { assert(err instanceof FamilyError); done(); }); }); }); describe('setMetadata', () => { it('should provide the proper request options', done => { sandbox.stub(family.bigtable, 'request').callsFake(config => { assert.strictEqual(config.client, 'BigtableTableAdminClient'); assert.strictEqual(config.method, 'modifyColumnFamilies'); assert.strictEqual(config.reqOpts.name, TABLE.name); assert.deepStrictEqual(config.reqOpts.modifications, [ { id: FAMILY_ID, update: {}, }, ]); done(); }); family.setMetadata({}, assert.ifError); }); it('should respect the gc rule option', done => { const formatRule = Family.formatRule_; const formattedRule = { a: 'a', b: 'b', } as fm.IGcRule; const metadata = { rule: { c: 'c', d: 'd', }, } as fm.SetFamilyMetadataOptions; sandbox.stub(Family, 'formatRule_').callsFake(rule => { assert.strictEqual(rule, metadata.rule); return formattedRule; }); sandbox.stub(family.bigtable, 'request').callsFake(config => { assert.deepStrictEqual(config.reqOpts, { name: TABLE.name, modifications: [ { id: family.id, update: { gcRule: formattedRule, }, }, ], }); Family.formatRule_ = formatRule; done(); }); family.setMetadata(metadata, assert.ifError); }); it('should return an error to the callback', done => { const error = new Error('err'); sandbox.stub(family.bigtable, 'request').callsArgWith(1, error); family.setMetadata({}, err => { assert.strictEqual(err, error); done(); }); }); it('should update the metadata property', done => { const fakeMetadata = {}; const response = { columnFamilies: { 'family-test': fakeMetadata, }, }; sandbox.stub(family.bigtable, 'request').callsArgWith(1, null, response); family.setMetadata({}, (err, metadata, apiResponse) => { assert.ifError(err); assert.strictEqual(metadata, fakeMetadata); assert.strictEqual(family.metadata, fakeMetadata); assert.strictEqual(apiResponse, response); done(); }); }); }); describe('FamilyError', () => { it('should set the code and message', () => { const err = new FamilyError(FAMILY_NAME); assert.strictEqual(err.code, 404); assert.strictEqual( err.message, 'Column family not found: ' + FAMILY_NAME + '.' ); }); }); });
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CreateCanaryCommand, CreateCanaryCommandInput, CreateCanaryCommandOutput, } from "./commands/CreateCanaryCommand"; import { DeleteCanaryCommand, DeleteCanaryCommandInput, DeleteCanaryCommandOutput, } from "./commands/DeleteCanaryCommand"; import { DescribeCanariesCommand, DescribeCanariesCommandInput, DescribeCanariesCommandOutput, } from "./commands/DescribeCanariesCommand"; import { DescribeCanariesLastRunCommand, DescribeCanariesLastRunCommandInput, DescribeCanariesLastRunCommandOutput, } from "./commands/DescribeCanariesLastRunCommand"; import { DescribeRuntimeVersionsCommand, DescribeRuntimeVersionsCommandInput, DescribeRuntimeVersionsCommandOutput, } from "./commands/DescribeRuntimeVersionsCommand"; import { GetCanaryCommand, GetCanaryCommandInput, GetCanaryCommandOutput } from "./commands/GetCanaryCommand"; import { GetCanaryRunsCommand, GetCanaryRunsCommandInput, GetCanaryRunsCommandOutput, } from "./commands/GetCanaryRunsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { StartCanaryCommand, StartCanaryCommandInput, StartCanaryCommandOutput } from "./commands/StartCanaryCommand"; import { StopCanaryCommand, StopCanaryCommandInput, StopCanaryCommandOutput } from "./commands/StopCanaryCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateCanaryCommand, UpdateCanaryCommandInput, UpdateCanaryCommandOutput, } from "./commands/UpdateCanaryCommand"; import { SyntheticsClient } from "./SyntheticsClient"; /** * <fullname>Amazon CloudWatch Synthetics</fullname> * <p>You can use Amazon CloudWatch Synthetics to continually monitor your services. You can * create and manage <i>canaries</i>, which are modular, lightweight scripts * that monitor your endpoints and APIs * from the outside-in. You can set up your canaries to run * 24 hours a day, once per minute. The canaries help you check the availability and latency * of your web services and troubleshoot anomalies by investigating load time data, * screenshots of the UI, logs, and metrics. The canaries seamlessly integrate with CloudWatch * ServiceLens to help you trace the causes of impacted nodes in your applications. For more * information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ServiceLens.html">Using ServiceLens to Monitor * the Health of Your Applications</a> in the <i>Amazon CloudWatch User * Guide</i>.</p> * * <p>Before you create and manage canaries, be aware of the security considerations. 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> */ export class Synthetics extends SyntheticsClient { /** * <p>Creates a canary. Canaries are scripts that monitor your endpoints and APIs from the * outside-in. Canaries help you check the availability and latency of your web services and * troubleshoot anomalies by investigating load time data, screenshots of the UI, logs, and * metrics. You can set up a canary to run continuously or just once. </p> * <p>Do not use <code>CreateCanary</code> to modify an existing canary. Use <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_UpdateCanary.html">UpdateCanary</a> instead.</p> * <p>To create canaries, you must have the <code>CloudWatchSyntheticsFullAccess</code> policy. * If you are creating a new IAM role for the canary, you also need the * the <code>iam:CreateRole</code>, <code>iam:CreatePolicy</code> and * <code>iam:AttachRolePolicy</code> permissions. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Roles">Necessary * Roles and Permissions</a>.</p> * <p>Do not include secrets or proprietary information in your canary names. The canary name * makes up part of the Amazon Resource Name (ARN) for the canary, 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> */ public createCanary( args: CreateCanaryCommandInput, options?: __HttpHandlerOptions ): Promise<CreateCanaryCommandOutput>; public createCanary(args: CreateCanaryCommandInput, cb: (err: any, data?: CreateCanaryCommandOutput) => void): void; public createCanary( args: CreateCanaryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateCanaryCommandOutput) => void ): void; public createCanary( args: CreateCanaryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateCanaryCommandOutput) => void), cb?: (err: any, data?: CreateCanaryCommandOutput) => void ): Promise<CreateCanaryCommandOutput> | void { const command = new CreateCanaryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Permanently deletes the specified canary.</p> * <p>When you delete a canary, resources used and created by the canary are not automatically deleted. After you delete a canary that you do not intend to * use again, you * should also delete the following:</p> * <ul> * <li> * <p>The Lambda functions and layers used by this canary. These have the prefix * <code>cwsyn-<i>MyCanaryName</i> * </code>.</p> * </li> * <li> * <p>The CloudWatch alarms created for this canary. These alarms have a name of * <code>Synthetics-SharpDrop-Alarm-<i>MyCanaryName</i> * </code>.</p> * </li> * <li> * <p>Amazon S3 objects and buckets, such as the canary's artifact location.</p> * </li> * <li> * <p>IAM roles created for the canary. If they were created in the console, these roles * have the name <code> * role/service-role/CloudWatchSyntheticsRole-<i>MyCanaryName</i> * </code>.</p> * </li> * <li> * <p>CloudWatch Logs log groups created for the canary. These logs groups have the name * <code>/aws/lambda/cwsyn-<i>MyCanaryName</i> * </code>. </p> * </li> * </ul> * * <p>Before you delete a canary, you might want to use <code>GetCanary</code> to display * the information about this canary. Make * note of the information returned by this operation so that you can delete these resources * after you delete the canary.</p> */ public deleteCanary( args: DeleteCanaryCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteCanaryCommandOutput>; public deleteCanary(args: DeleteCanaryCommandInput, cb: (err: any, data?: DeleteCanaryCommandOutput) => void): void; public deleteCanary( args: DeleteCanaryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteCanaryCommandOutput) => void ): void; public deleteCanary( args: DeleteCanaryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteCanaryCommandOutput) => void), cb?: (err: any, data?: DeleteCanaryCommandOutput) => void ): Promise<DeleteCanaryCommandOutput> | void { const command = new DeleteCanaryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>This operation returns a list of the canaries in your account, along with full details * about each canary.</p> * <p>This operation does not have resource-level authorization, so if a user is able to use * <code>DescribeCanaries</code>, the user can see all of the canaries in the account. A * deny policy can only be used to restrict access to all canaries. It cannot be used on * specific resources. </p> */ public describeCanaries( args: DescribeCanariesCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeCanariesCommandOutput>; public describeCanaries( args: DescribeCanariesCommandInput, cb: (err: any, data?: DescribeCanariesCommandOutput) => void ): void; public describeCanaries( args: DescribeCanariesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeCanariesCommandOutput) => void ): void; public describeCanaries( args: DescribeCanariesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeCanariesCommandOutput) => void), cb?: (err: any, data?: DescribeCanariesCommandOutput) => void ): Promise<DescribeCanariesCommandOutput> | void { const command = new DescribeCanariesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Use this operation to see information from the most recent run of each canary that you have created.</p> */ public describeCanariesLastRun( args: DescribeCanariesLastRunCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeCanariesLastRunCommandOutput>; public describeCanariesLastRun( args: DescribeCanariesLastRunCommandInput, cb: (err: any, data?: DescribeCanariesLastRunCommandOutput) => void ): void; public describeCanariesLastRun( args: DescribeCanariesLastRunCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeCanariesLastRunCommandOutput) => void ): void; public describeCanariesLastRun( args: DescribeCanariesLastRunCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeCanariesLastRunCommandOutput) => void), cb?: (err: any, data?: DescribeCanariesLastRunCommandOutput) => void ): Promise<DescribeCanariesLastRunCommandOutput> | void { const command = new DescribeCanariesLastRunCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of Synthetics canary runtime versions. For more information, * see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html"> * Canary Runtime Versions</a>.</p> */ public describeRuntimeVersions( args: DescribeRuntimeVersionsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeRuntimeVersionsCommandOutput>; public describeRuntimeVersions( args: DescribeRuntimeVersionsCommandInput, cb: (err: any, data?: DescribeRuntimeVersionsCommandOutput) => void ): void; public describeRuntimeVersions( args: DescribeRuntimeVersionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeRuntimeVersionsCommandOutput) => void ): void; public describeRuntimeVersions( args: DescribeRuntimeVersionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeRuntimeVersionsCommandOutput) => void), cb?: (err: any, data?: DescribeRuntimeVersionsCommandOutput) => void ): Promise<DescribeRuntimeVersionsCommandOutput> | void { const command = new DescribeRuntimeVersionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves complete information about one canary. You must specify * the name of the canary that you want. To get a list of canaries * and their names, use <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html">DescribeCanaries</a>.</p> */ public getCanary(args: GetCanaryCommandInput, options?: __HttpHandlerOptions): Promise<GetCanaryCommandOutput>; public getCanary(args: GetCanaryCommandInput, cb: (err: any, data?: GetCanaryCommandOutput) => void): void; public getCanary( args: GetCanaryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetCanaryCommandOutput) => void ): void; public getCanary( args: GetCanaryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetCanaryCommandOutput) => void), cb?: (err: any, data?: GetCanaryCommandOutput) => void ): Promise<GetCanaryCommandOutput> | void { const command = new GetCanaryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves a list of runs for a specified canary.</p> */ public getCanaryRuns( args: GetCanaryRunsCommandInput, options?: __HttpHandlerOptions ): Promise<GetCanaryRunsCommandOutput>; public getCanaryRuns( args: GetCanaryRunsCommandInput, cb: (err: any, data?: GetCanaryRunsCommandOutput) => void ): void; public getCanaryRuns( args: GetCanaryRunsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetCanaryRunsCommandOutput) => void ): void; public getCanaryRuns( args: GetCanaryRunsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetCanaryRunsCommandOutput) => void), cb?: (err: any, data?: GetCanaryRunsCommandOutput) => void ): Promise<GetCanaryRunsCommandOutput> | void { const command = new GetCanaryRunsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Displays the tags associated with a canary.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Use this operation to run a canary that has already been created. * The frequency of the canary runs is determined by the value of the canary's <code>Schedule</code>. To see a canary's schedule, * use <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_GetCanary.html">GetCanary</a>.</p> */ public startCanary(args: StartCanaryCommandInput, options?: __HttpHandlerOptions): Promise<StartCanaryCommandOutput>; public startCanary(args: StartCanaryCommandInput, cb: (err: any, data?: StartCanaryCommandOutput) => void): void; public startCanary( args: StartCanaryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StartCanaryCommandOutput) => void ): void; public startCanary( args: StartCanaryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartCanaryCommandOutput) => void), cb?: (err: any, data?: StartCanaryCommandOutput) => void ): Promise<StartCanaryCommandOutput> | void { const command = new StartCanaryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Stops the canary to prevent all future runs. If the canary is currently running, * Synthetics stops waiting for the current run of the specified canary to complete. The * run that is in progress completes on its own, publishes metrics, and uploads artifacts, but * it is not recorded in Synthetics as a completed run.</p> * <p>You can use <code>StartCanary</code> to start it running again * with the canary’s current schedule at any point in the future. </p> */ public stopCanary(args: StopCanaryCommandInput, options?: __HttpHandlerOptions): Promise<StopCanaryCommandOutput>; public stopCanary(args: StopCanaryCommandInput, cb: (err: any, data?: StopCanaryCommandOutput) => void): void; public stopCanary( args: StopCanaryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StopCanaryCommandOutput) => void ): void; public stopCanary( args: StopCanaryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StopCanaryCommandOutput) => void), cb?: (err: any, data?: StopCanaryCommandOutput) => void ): Promise<StopCanaryCommandOutput> | void { const command = new StopCanaryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Assigns one or more tags (key-value pairs) to the specified 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 resources with * certain tag values.</p> * <p>Tags don't have any semantic meaning to Amazon Web Services and are interpreted strictly as strings of characters.</p> * <p>You can use the <code>TagResource</code> action with a canary that already has tags. If you specify a new tag key for the alarm, * this tag is appended to the list of tags associated * with the alarm. If you specify a tag key that is already associated with the alarm, the new tag value that you specify replaces * the previous value for that tag.</p> * <p>You can associate as many as 50 tags with a canary.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes one or more tags from the specified canary.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Use this operation to change the settings of a canary that has * already been created.</p> * <p>You can't use this operation to update the tags of an existing canary. To * change the tags of an existing canary, use * <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_TagResource.html">TagResource</a>.</p> */ public updateCanary( args: UpdateCanaryCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateCanaryCommandOutput>; public updateCanary(args: UpdateCanaryCommandInput, cb: (err: any, data?: UpdateCanaryCommandOutput) => void): void; public updateCanary( args: UpdateCanaryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateCanaryCommandOutput) => void ): void; public updateCanary( args: UpdateCanaryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateCanaryCommandOutput) => void), cb?: (err: any, data?: UpdateCanaryCommandOutput) => void ): Promise<UpdateCanaryCommandOutput> | void { const command = new UpdateCanaryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { StorageBackendPlugin } from '@worldbrain/storex' import { DexieStorageBackend } from '@worldbrain/storex-backend-dexie' import { AnnotSearchParams } from './types' import { transformUrl } from '../pipeline' import AnnotsStorage from 'src/annotations/background/storage' import { Annotation } from 'src/annotations/types' const moment = require('moment-timezone') export class AnnotationsListPlugin extends StorageBackendPlugin< DexieStorageBackend > { static TERMS_SEARCH_OP_ID = 'memex:dexie.searchAnnotations' static LIST_BY_PAGE_OP_ID = 'memex:dexie.listAnnotationsByPage' static LIST_BY_DAY_OP_ID = 'memex:dexie.listAnnotationsByDay' static DEF_INNER_LIMIT_MULTI = 2 install(backend: DexieStorageBackend) { super.install(backend) backend.registerOperation( AnnotationsListPlugin.TERMS_SEARCH_OP_ID, this.searchAnnots.bind(this), ) backend.registerOperation( AnnotationsListPlugin.LIST_BY_PAGE_OP_ID, this.listAnnotsByPage.bind(this), ) backend.registerOperation( AnnotationsListPlugin.LIST_BY_DAY_OP_ID, this.listAnnotsByDay.bind(this), ) } private listWithUrl = ({ url, endDate, startDate, }: Partial<AnnotSearchParams>) => { if (!url) { throw new Error('URL must be supplied to list annotations.') } const coll = this.backend.dexieInstance .table<Annotation, string>(AnnotsStorage.ANNOTS_COLL) .where('pageUrl') .equals(url) if (!startDate && !endDate) { return coll } // Set defaults startDate = startDate || 0 endDate = endDate || Date.now() // Ensure ms extracted from any Date instances startDate = startDate instanceof Date ? startDate.getTime() : startDate endDate = endDate instanceof Date ? endDate.getTime() : endDate return coll.filter(({ lastEdited }) => { const time = lastEdited.getTime() return time >= startDate && time <= endDate }) } private async filterByBookmarks(urls: string[]) { return this.backend.dexieInstance .table<any, string>(AnnotsStorage.BMS_COLL) .where('url') .anyOf(urls) .primaryKeys() } private async filterByTags(urls: string[], params: AnnotSearchParams) { const tagsExc = params.tagsExc && params.tagsExc.length ? new Set(params.tagsExc) : null const tagsInc = params.tagsInc && params.tagsInc.length ? new Set(params.tagsInc) : null let tagsForUrls = new Map<string, string[]>() await this.backend.dexieInstance .table<any, [string, string]>(AnnotsStorage.TAGS_COLL) .where('url') .anyOf(urls) .eachPrimaryKey(([tag, url]) => { const curr = tagsForUrls.get(url) || [] tagsForUrls.set(url, [...curr, tag]) }) if (tagsExc) { tagsForUrls = new Map( [...tagsForUrls].filter(([, tags]) => tags.some((tag) => !tagsExc.has(tag)), ), ) } if (tagsInc) { tagsForUrls = new Map( [...tagsForUrls].filter(([, tags]) => tags.some((tag) => tagsInc.has(tag)), ), ) } return urls.filter((url) => { if (!tagsInc) { // Make sure current url doesn't have any excluded tag const urlTags = tagsForUrls.get(url) || [] return urlTags.some((tag) => !tagsExc.has(tag)) } return tagsForUrls.has(url) }) } private async filterByCollections( urls: string[], params: AnnotSearchParams, ) { const ids = params.collections.map((id) => Number(id)) const pageEntries = await this.backend.dexieInstance .table('pageListEntries') .where('listId') .anyOf(ids) .primaryKeys() const pageUrls = new Set(pageEntries.map((pk) => pk[1])) return this.backend.dexieInstance .table(AnnotsStorage.ANNOTS_COLL) .where('url') .anyOf(urls) .and((annot) => pageUrls.has(annot.pageUrl)) .primaryKeys() as Promise<string[]> // IMPLEMENTATION FOR ANNOTS COLLECTIONS // const [listIds, entries] = await Promise.all([ // this.backend.dexieInstance // .table<any, number>(AnnotsStorage.LISTS_COLL) // .where('name') // .anyOf(params.collections) // .primaryKeys(), // this.backend.dexieInstance // .table<any, [number, string]>(AnnotsStorage.LIST_ENTRIES_COLL) // .where('url') // .anyOf(urls) // .primaryKeys(), // ]) // const lists = new Set(listIds) // const entryUrls = new Set( // entries // .filter(([listId]) => lists.has(listId)) // .map(([, url]) => url), // )) } private async filterByDomains( urls: string[], { domainsInc, domainsExc }: AnnotSearchParams, ) { const inc = domainsInc && domainsInc.length ? new Set(domainsInc) : null const exc = new Set(domainsExc) return urls.filter((url) => { const { domain } = transformUrl(url) if (!inc) { return !exc.has(domain) } return inc.has(domain) && !exc.has(domain) }) } private async mapUrlsToAnnots(urls: string[]): Promise<Annotation[]> { const annotUrlMap = new Map<string, Annotation>() await this.backend.dexieInstance .table(AnnotsStorage.ANNOTS_COLL) .where('url') .anyOf(urls) .each((annot) => annotUrlMap.set(annot.url, annot)) // Ensure original order of input is kept return urls.map((url) => annotUrlMap.get(url)) } private async filterResults(results: string[], params: AnnotSearchParams) { if (params.bookmarksOnly) { results = await this.filterByBookmarks(results) } if ( (params.tagsInc && params.tagsInc.length) || (params.tagsExc && params.tagsExc.length) ) { results = await this.filterByTags(results, params) } if (params.collections && params.collections.length) { results = await this.filterByCollections(results, params) } if ( (params.domainsExc && params.domainsInc.length) || (params.domainsExc && params.domainsExc.length) ) { results = await this.filterByDomains(results, params) } return results } private async calcHardLowerTimeBound({ startDate }: AnnotSearchParams) { const earliestAnnot: Annotation = await this.backend.dexieInstance .table(AnnotsStorage.ANNOTS_COLL) .orderBy('lastEdited') .first() if ( earliestAnnot && moment(earliestAnnot.lastEdited).isAfter(startDate || 0) ) { return moment(earliestAnnot.lastEdited) } return startDate ? moment(new Date(startDate)) : moment('2018-06-01') // The date annots feature was released } private mergeResults( a: Map<number, Map<string, Annotation[]>>, b: Map<number, Map<string, Annotation[]>>, ) { for (const [date, pagesB] of b) { const pagesA = a.get(date) || new Map() for (const [page, annotsB] of pagesB) { const existing = pagesA.get(page) || [] pagesA.set(page, [...existing, ...annotsB]) } a.set(date, pagesA) } } private clusterAnnotsByDays( annots: Annotation[], ): Map<number, Annotation[]> { const annotsByDays = new Map<number, Annotation[]>() for (const annot of annots.sort( (a, b) => b.lastEdited.getTime() - a.lastEdited.getTime(), )) { const date = moment(annot.lastEdited).startOf('day').toDate() const existing = annotsByDays.get(date.getTime()) || [] annotsByDays.set(date.getTime(), [...existing, annot]) } return annotsByDays } private clusterAnnotsByPage( annots: Annotation[], ): Map<number, Map<string, Annotation[]>> { const annotsByPage = new Map<number, Map<string, Annotation[]>>() for (const [date, matching] of this.clusterAnnotsByDays(annots)) { const pageMap = new Map<string, Annotation[]>() for (const annot of matching) { const existing = pageMap.get(annot.pageUrl) || [] pageMap.set(annot.pageUrl, [...existing, annot]) } annotsByPage.set(date, pageMap) } return annotsByPage } private async queryAnnotsByDay(startDate: Date, endDate: Date) { const collection = this.backend.dexieInstance .table<Annotation>(AnnotsStorage.ANNOTS_COLL) .where('lastEdited') .between(startDate, endDate, true, true) .reverse() return collection.toArray() } private async queryTermsField( args: { field: string term: string }, { startDate, endDate }: AnnotSearchParams, ): Promise<string[]> { let coll = this.backend.dexieInstance .table<Annotation>(AnnotsStorage.ANNOTS_COLL) .where(args.field) .equals(args.term) if (startDate || endDate) { coll = coll.filter( (annot) => annot.lastEdited >= new Date(startDate || 0) && annot.lastEdited <= new Date(endDate || Date.now()), ) } return coll.primaryKeys() as Promise<string[]> } private async lookupTerms({ termsInc, includeHighlights, includeNotes, ...params }: AnnotSearchParams) { const fields = [] if (includeHighlights) { fields.push('_body_terms') } if (includeNotes) { fields.push('_comment_terms') } const results = new Map<string, string[]>() // Run all needed queries for each term and on each field concurrently for (const term of termsInc) { const termRes = await Promise.all( fields.map((field) => this.queryTermsField({ field, term }, params), ), ) // Collect all results from each field for this term results.set(term, [...new Set([].concat(...termRes))]) } // Get intersection of results for all terms (all terms must match) const intersected = [...results.values()].reduce((a, b) => { const bSet = new Set(b) return a.filter((res) => bSet.has(res)) }) return intersected } private async paginateAnnotsResults( results: string[], { skip, limit }: AnnotSearchParams, ) { const internalPageSize = limit * 2 const annotsByPage = new Map<string, Annotation[]>() const seenPages = new Set<string>() let internalSkip = 0 while (annotsByPage.size < limit) { const resSlice = results.slice( internalSkip, internalSkip + internalPageSize, ) if (!resSlice.length) { break } const annots = await this.mapUrlsToAnnots(resSlice) annots.forEach((annot) => { seenPages.add(annot.pageUrl) const prev = annotsByPage.get(annot.pageUrl) || [] if (annotsByPage.size !== limit && seenPages.size > skip) { annotsByPage.set(annot.pageUrl, [...prev, annot]) } }) internalSkip += internalPageSize } return annotsByPage } async searchAnnots(params: AnnotSearchParams) { const termsSearchResults = await this.lookupTerms(params) const filteredResults = await this.filterResults( termsSearchResults, params, ) const annotsByPage = await this.paginateAnnotsResults( filteredResults, params, ) return annotsByPage } /** * Don't use `params.skip` for pagination. Instead, as results * are ordered by day, use `params.endDate`. */ async listAnnotsByDay(params: AnnotSearchParams) { const hardLowerLimit = await this.calcHardLowerTimeBound(params) let dateCursor = params.endDate ? moment(params.endDate) : moment().endOf('day') let results = new Map<number, Map<string, Annotation[]>>() while ( results.size < params.limit && dateCursor.isAfter(hardLowerLimit) ) { const upperBound = dateCursor.clone() // Keep going back `limit` days until enough results, or until hard lower limit hit if (dateCursor.diff(hardLowerLimit, 'days') < params.limit) { dateCursor = hardLowerLimit } else { dateCursor.subtract(params.limit, 'days') } let annots = await this.queryAnnotsByDay( dateCursor.toDate(), upperBound.toDate(), ) const filteredPks = new Set( await this.filterResults( annots.map((a) => a.url), params, ), ) annots = annots.filter((annot) => filteredPks.has(annot.url)) this.mergeResults(results, this.clusterAnnotsByPage(annots)) } // Cut off any excess if (results.size > params.limit) { results = new Map( [...results].slice(params.skip, params.skip + params.limit), ) } return results } async listAnnotsByPage( { limit = 10, skip = 0, ...params }: AnnotSearchParams, innerLimitMultiplier = AnnotationsListPlugin.DEF_INNER_LIMIT_MULTI, ): Promise<Annotation[]> { const innerLimit = limit * innerLimitMultiplier let innerSkip = 0 let results: string[] = [] let continueLookup: boolean do { // The results found in this iteration let innerResults: string[] = [] innerResults = await this.listWithUrl(params) .offset(innerSkip) .limit(innerLimit) .primaryKeys() continueLookup = innerResults.length >= innerLimit innerResults = await this.filterResults(innerResults, params) results = [...results, ...innerResults] innerSkip += innerLimit } while (continueLookup) // Cut off any excess if (results.length > limit) { results = [...results].slice(skip, skip + limit) } return this.mapUrlsToAnnots(results) } }
the_stack
import Raw from './raw.js'; import Ref from './ref.js'; import Runner from './runner.js'; import Formatter from './formatter.js'; import Transaction from './transaction.js'; import QueryBuilder from './query/builder.js'; import QueryCompiler from './query/compiler.js'; import SchemaBuilder from './schema/builder.js'; import SchemaCompiler from './schema/compiler.js'; import TableBuilder from './schema/tablebuilder.js'; import TableCompiler from './schema/tablecompiler.js'; import ColumnBuilder from './schema/columnbuilder.js'; import ColumnCompiler from './schema/columncompiler.js'; import tarn from './deps/tarn@3.0.0/dist/tarn.js'; const Pool = tarn.Pool; const TimeoutError = tarn.TimeoutError; import inherits from './deps/inherits@2.0.4/inherits.js'; import { EventEmitter } from './deps/@jspm/core@1.1.0/nodelibs/events.js'; import { promisify } from './deps/@jspm/core@1.1.0/nodelibs/util.js'; import { makeEscape } from './query/string.js'; import _ from './deps/lodash@4.17.15/index.js'; const cloneDeep = _.cloneDeep; const defaults = _.defaults; const uniqueId = _.uniqueId; import Logger from './logger.js'; import { KnexTimeoutError } from './util/timeout.js'; import debuglib from './deps/debug@4.1.1/src/index.js'; const debug = debuglib('knex:client'); const _debugQuery = debuglib('knex:query'); const debugBindings = debuglib('knex:bindings'); const debugQuery = (sql, txId) => _debugQuery(sql.replace(/%/g, '%%'), txId); import { POOL_CONFIG_OPTIONS } from './constants.js'; // The base client provides the general structure // for a dialect specific client object. function Client(config = {}) { this.config = config; this.logger = new Logger(config); //Client is a required field, so throw error if it's not supplied. //If 'this.dialect' is set, then this is a 'super()' call, in which case //'client' does not have to be set as it's already assigned on the client prototype. if (this.dialect && !this.config.client) { this.logger.warn( `Using 'this.dialect' to identify the client is deprecated and support for it will be removed in the future. Please use configuration option 'client' instead.` ); } const dbClient = this.config.client || this.dialect; if (!dbClient) { throw new Error(`knex: Required configuration option 'client' is missing.`); } if (config.version) { this.version = config.version; } if (config.connection && config.connection instanceof Function) { this.connectionConfigProvider = config.connection; this.connectionConfigExpirationChecker = () => true; // causes the provider to be called on first use } else { this.connectionSettings = cloneDeep(config.connection || {}); this.connectionConfigExpirationChecker = null; } if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || (config.pool && config.pool.max !== 0)) { this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } } inherits(Client, EventEmitter); Object.assign(Client.prototype, { formatter(builder) { return new Formatter(this, builder); }, queryBuilder() { return new QueryBuilder(this); }, queryCompiler(builder) { return new QueryCompiler(this, builder); }, schemaBuilder() { return new SchemaBuilder(this); }, schemaCompiler(builder) { return new SchemaCompiler(this, builder); }, tableBuilder(type, tableName, fn) { return new TableBuilder(this, type, tableName, fn); }, tableCompiler(tableBuilder) { return new TableCompiler(this, tableBuilder); }, columnBuilder(tableBuilder, type, args) { return new ColumnBuilder(this, tableBuilder, type, args); }, columnCompiler(tableBuilder, columnBuilder) { return new ColumnCompiler(this, tableBuilder, columnBuilder); }, runner(builder) { return new Runner(this, builder); }, transaction(container, config, outerTx) { return new Transaction(this, container, config, outerTx); }, raw() { return new Raw(this).set(...arguments); }, ref() { return new Ref(this, ...arguments); }, _formatQuery(sql, bindings, timeZone) { bindings = bindings == null ? [] : [].concat(bindings); let index = 0; return sql.replace(/\\?\?/g, (match) => { if (match === '\\?') { return '?'; } if (index === bindings.length) { return match; } const value = bindings[index++]; return this._escapeBinding(value, { timeZone }); }); }, _escapeBinding: makeEscape({ escapeString(str) { return `'${str.replace(/'/g, "''")}'`; }, }), query(connection, obj) { if (typeof obj === 'string') obj = { sql: obj }; obj.bindings = this.prepBindings(obj.bindings); const { __knexUid, __knexTxId } = connection; this.emit('query', Object.assign({ __knexUid, __knexTxId }, obj)); debugQuery(obj.sql, __knexTxId); debugBindings(obj.bindings, __knexTxId); obj.sql = this.positionBindings(obj.sql); return this._query(connection, obj).catch((err) => { err.message = this._formatQuery(obj.sql, obj.bindings) + ' - ' + err.message; this.emit( 'query-error', err, Object.assign({ __knexUid, __knexTxId }, obj) ); throw err; }); }, stream(connection, obj, stream, options) { if (typeof obj === 'string') obj = { sql: obj }; obj.bindings = this.prepBindings(obj.bindings); const { __knexUid, __knexTxId } = connection; this.emit('query', Object.assign({ __knexUid, __knexTxId }, obj)); debugQuery(obj.sql, __knexTxId); debugBindings(obj.bindings, __knexTxId); obj.sql = this.positionBindings(obj.sql); return this._stream(connection, obj, stream, options); }, prepBindings(bindings) { return bindings; }, positionBindings(sql) { return sql; }, postProcessResponse(resp, queryContext) { if (this.config.postProcessResponse) { return this.config.postProcessResponse(resp, queryContext); } return resp; }, wrapIdentifier(value, queryContext) { return this.customWrapIdentifier( value, this.wrapIdentifierImpl, queryContext ); }, customWrapIdentifier(value, origImpl, queryContext) { if (this.config.wrapIdentifier) { return this.config.wrapIdentifier(value, origImpl, queryContext); } return origImpl(value); }, wrapIdentifierImpl(value) { return value !== '*' ? `"${value.replace(/"/g, '""')}"` : '*'; }, initializeDriver() { try { this.driver = this._driver(); } catch (e) { const message = `Knex: run\n$ npm install ${this.driverName} --save`; this.logger.error(`${message}\n${e.message}\n${e.stack}`); throw new Error(`${message}\n${e.message}`); } }, poolDefaults() { return { min: 2, max: 10, propagateCreateError: true }; }, getPoolSettings(poolConfig) { poolConfig = defaults({}, poolConfig, this.poolDefaults()); POOL_CONFIG_OPTIONS.forEach((option) => { if (option in poolConfig) { this.logger.warn( [ `Pool config option "${option}" is no longer supported.`, `See https://github.com/Vincit/tarn.js for possible pool config options.`, ].join(' ') ); } }); const timeouts = [ this.config.acquireConnectionTimeout || 60000, poolConfig.acquireTimeoutMillis, ].filter((timeout) => timeout !== undefined); // acquire connection timeout can be set on config or config.pool // choose the smallest, positive timeout setting and set on poolConfig poolConfig.acquireTimeoutMillis = Math.min(...timeouts); const updatePoolConnectionSettingsFromProvider = async () => { if (!this.connectionConfigProvider) { return; // static configuration, nothing to update } if ( !this.connectionConfigExpirationChecker || !this.connectionConfigExpirationChecker() ) { return; // not expired, reuse existing connection } const providerResult = await this.connectionConfigProvider(); if (providerResult.expirationChecker) { this.connectionConfigExpirationChecker = providerResult.expirationChecker; delete providerResult.expirationChecker; // MySQL2 driver warns on receiving extra properties } else { this.connectionConfigExpirationChecker = null; } this.connectionSettings = providerResult; }; return Object.assign(poolConfig, { create: async () => { await updatePoolConnectionSettingsFromProvider(); const connection = await this.acquireRawConnection(); connection.__knexUid = uniqueId('__knexUid'); if (poolConfig.afterCreate) { await promisify(poolConfig.afterCreate)(connection); } return connection; }, destroy: (connection) => { if (connection !== void 0) { return this.destroyRawConnection(connection); } }, validate: (connection) => { if (connection.__knex__disposed) { this.logger.warn(`Connection Error: ${connection.__knex__disposed}`); return false; } return this.validateConnection(connection); }, }); }, initializePool(config = this.config) { if (this.pool) { this.logger.warn('The pool has already been initialized'); return; } const tarnPoolConfig = { ...this.getPoolSettings(config.pool), }; // afterCreate is an internal knex param, tarn.js does not support it if (tarnPoolConfig.afterCreate) { delete tarnPoolConfig.afterCreate; } this.pool = new Pool(tarnPoolConfig); }, validateConnection(connection) { return true; }, // Acquire a connection from the pool. async acquireConnection() { if (!this.pool) { throw new Error('Unable to acquire a connection'); } try { const connection = await this.pool.acquire().promise; debug('acquired connection from pool: %s', connection.__knexUid); return connection; } catch (error) { let convertedError = error; if (error instanceof TimeoutError) { convertedError = new KnexTimeoutError( 'Knex: Timeout acquiring a connection. The pool is probably full. ' + 'Are you missing a .transacting(trx) call?' ); } throw convertedError; } }, // Releases a connection back to the connection pool, // returning a promise resolved when the connection is released. releaseConnection(connection) { debug('releasing connection to pool: %s', connection.__knexUid); const didRelease = this.pool.release(connection); if (!didRelease) { debug('pool refused connection: %s', connection.__knexUid); } return Promise.resolve(); }, // Destroy the current connection pool for the client. destroy(callback) { const maybeDestroy = this.pool && this.pool.destroy(); return Promise.resolve(maybeDestroy) .then(() => { this.pool = void 0; if (typeof callback === 'function') { callback(); } }) .catch((err) => { if (typeof callback === 'function') { callback(err); } return Promise.reject(err); }); }, // Return the database being used by this client. database() { return this.connectionSettings.database; }, toString() { return '[object KnexClient]'; }, canCancelQuery: false, assertCanCancelQuery() { if (!this.canCancelQuery) { throw new Error('Query cancelling not supported for this dialect'); } }, cancelQuery() { throw new Error('Query cancelling not supported for this dialect'); }, }); export default Client;
the_stack
import {Body, Get, HttpCode, HttpStatus, Param, Post, Query, Req} from '@nestjs/common'; import {Request} from 'express'; import { PathHash, GeneratePrivateKey, PathAddress, PathAddressContractAddress, QueryMnemonic, Pagination, PathXpub, } from '@tatumio/blockchain-connector-common'; import { BroadcastTx, EgldTransaction, EgldEsdtTransaction, EgldBasicTransaction, } from '@tatumio/tatum'; import {EgldError} from './EgldError'; import {EgldService} from './EgldService'; export abstract class EgldController { protected constructor(protected readonly service: EgldService) { } @Post('node/:xApiKey/*') @HttpCode(HttpStatus.OK) public async nodeMethodPost(@Req() req: Request, @Param() param: { xApiKey: string }) { try { return await this.service.nodeMethod(req, param.xApiKey); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('node/:xApiKey/*') @HttpCode(HttpStatus.OK) public async nodeMethodGet(@Req() req: Request, @Param() param: { xApiKey: string }) { try { return await this.service.nodeMethod(req, param.xApiKey); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Post('transaction') @HttpCode(HttpStatus.OK) public async sendEgldTransaction(@Body() body: EgldEsdtTransaction) { try { return await this.service.sendEgldTransaction(body); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Post('gas') @HttpCode(HttpStatus.OK) public async estimateGas(@Body() body: EgldBasicTransaction) { try { return await this.service.estimateGas(body); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('transaction/count/:address') @HttpCode(HttpStatus.OK) public async countTransactions(@Param() param: PathAddress) { try { return await this.service.getTransactionCount(param.address); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Post('broadcast') @HttpCode(HttpStatus.OK) public async broadcast(@Body() body: BroadcastTx) { try { return await this.service.broadcast(body.txData, body.signatureId); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('block/current') @HttpCode(HttpStatus.OK) public async getCurrentBlock() { try { return await this.service.getCurrentBlock(); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('account/balance/:address') @HttpCode(HttpStatus.OK) public async getAccountBalance(@Param() path: PathAddress) { try { return await this.service.getBalance(path.address); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('account/esdt/balance/:address/:tokenId') @HttpCode(HttpStatus.OK) public async getAccountBalanceErc20(@Param() path: PathAddressContractAddress) { try { return await this.service.getBalanceErc20(path.address, path.contractAddress); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('address/:mnem/:i') @HttpCode(HttpStatus.OK) public async generateAddress(@Param() { mnem, i }: {mnem: string, i: string}) { try { return await this.service.generateAddress(mnem, i); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('wallet') @HttpCode(HttpStatus.OK) async generateWallet(@Query() { mnemonic }: QueryMnemonic) { try { return await this.service.generateWallet(mnemonic) } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Post('wallet/priv') @HttpCode(HttpStatus.OK) async generatePrivateKey(@Body() { mnemonic, index }: GeneratePrivateKey) { try { return await this.service.generatePrivateKey(mnemonic, index) } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('block/:hash') @HttpCode(HttpStatus.OK) public async getBlock(@Param() path: PathHash) { try { return await this.service.getBlock(path.hash); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('transaction/:hash') public async getTransaction(@Param() path: PathHash) { try { return await this.service.getTransaction(path.hash); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } @Get('transaction/address/:address') async getTransactionsByAccount(@Param() path: PathAddress, @Query() query: Pagination): Promise<EgldTransaction[]> { try { return await this.service.getTransactionsByAccount( path.address, query?.pageSize, query?.offset, query?.count, ); } catch (e) { throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); } } // @Post('esdt/deploy') // @HttpCode(HttpStatus.OK) // public async deploySmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.deploySmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('esdt/mint') // @HttpCode(HttpStatus.OK) // public async mintSmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.mintSmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('esdt/burn') // @HttpCode(HttpStatus.OK) // public async burnSmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.burnSmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // these endpoints are not implemented: // @Post('esdt/pause') // @HttpCode(HttpStatus.OK) // public async pauseSmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.pauseSmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('esdt/role') // @HttpCode(HttpStatus.OK) // public async specialRoleSmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.specialRoleSmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('esdt/freeze') // @HttpCode(HttpStatus.OK) // public async freezeSmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.freezeOrWipeOrOwvershipSmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('esdt/wipe') // @HttpCode(HttpStatus.OK) // public async wipeSmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.freezeOrWipeOrOwvershipSmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('esdt/owner') // @HttpCode(HttpStatus.OK) // public async ownerSmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.freezeOrWipeOrOwvershipSmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('esdt/control') // @HttpCode(HttpStatus.OK) // public async controlChangesSmartContract(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.controlChangesSmartContract(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('esdt/transfer') // @HttpCode(HttpStatus.OK) // public async invokeSmartContractMethod(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.invokeSmartContractMethod(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('nft/deploy') // @HttpCode(HttpStatus.OK) // public async deployNft(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.deployNft(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('nft/create') // @HttpCode(HttpStatus.OK) // public async createNft(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.createNft(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // these endpoints are not implemented: // @Post('nft/role-transfer') // @HttpCode(HttpStatus.OK) // public async roleTransferNft(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.roleTransferNft(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('nft/stop-create') // @HttpCode(HttpStatus.OK) // public async stopNftCreate(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.stopNftCreate(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('nft/add') // @HttpCode(HttpStatus.OK) // public async addNftQuantity(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.addOrBurnNftQuantity(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('nft/burn') // @HttpCode(HttpStatus.OK) // public async burnNftQuantity(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.addOrBurnNftQuantity(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('nft/freeze') // @HttpCode(HttpStatus.OK) // public async freezeNft(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.freezeNft(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('nft/wipe') // @HttpCode(HttpStatus.OK) // public async wipeNft(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.wipeNft(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } // @Post('nft/transfer') // @HttpCode(HttpStatus.OK) // public async transferNft(@Body() body: EgldEsdtTransaction) { // try { // return await this.service.transferNft(body); // } catch (e) { // throw new EgldError(`Unexpected error occurred. Reason: ${e.message?.message || e.response?.data || e.message || e}`, 'egld.error'); // } // } }
the_stack
// This doesn't work when `@types/node` is present: declare const global: SnapchatLensStudio.Global; // // Instead, when `@types/node` is present, please add this shim will be needed to establish the typings `global`: // declare module NodeJS { // interface Global extends SnapchatLensStudio.Global {} // } /** Returns the time difference in seconds between the current frame and previous frame. */ declare function getDeltaTime(): number; /** Returns the time in seconds since the lens was started. */ declare function getTime(): number; /** Returns true if the passed in object is null or destroyed. Useful as a safe way to check if a SceneObject or Component has been destroyed. */ declare function isNull(reference: object): boolean; /** Prints out a message to the Logger window. */ declare function print(message: any): void; /** * Binds scripts to Events and executes them when triggered. Any script can access the ScriptComponent executing them through the variable script. See also: Scripting Overview, Script Events Guide. * ``` * // Bind a function to the MouthOpened event * function onMouthOpen(eventData) * { * print("mouth was opened"); * } * var event = script.createEvent("MouthOpenedEvent"); * event.bind(onMouthOpen); * ``` */ declare const script: Component.ScriptComponent; /** * A two dimensional vector. * Lens Studio v1.0.0+ */ declare class vec2 { constructor(x: number, y: number); /** Alternate name for the y component. */ g: number; /** Returns the length of the vector. */ length: number; /** Returns the squared length of the vector. */ lengthSquared: number; /** Alternate name for the x component. */ r: number; /** x component of the vec2. */ x: number; /** y component of the vec2. */ y: number; /** Returns the vector plus vec. */ add(vec: vec2): vec2; /** Returns the angle between the vector and vec. */ angleTo(vec: vec2): number; /** Returns a copy of the vector with its length clamped to length. */ clampLength(length: number): vec2; /** Returns the distance between the vector and the vector vec. */ distance(vec: vec2): number; /** Returns the division of the vector by the vector vec. */ div(vec: vec2): vec2; /** Returns the dot product of the vector and vec. */ dot(vec: vec2): number; /** Returns whether this is equal to vec. */ equal(vec: vec2): boolean; /** Returns a copy of the vector moved towards the point point by the amount magnitude. */ moveTowards(point: vec2, magnitude: number): vec2; /** Returns the component-wise multiplication product of the vector and vec. */ mult(vec: vec2): vec2; /** Returns a copy of the vector with its length scaled to 1. */ normalize(): vec2; /** Returns a copy of the vector projected onto the vector vec. */ project(vec: vec2): vec2; /** Projects the vector onto the plane represented by the normal normal. */ projectOnPlane(normal: vec2): vec2; /** Returns a copy of the vector reflected across the plane defined by the normal vec. */ reflect(vec: vec2): vec2; /** Returns the component-wise multiplication product of the vector and vec. */ scale(vec: vec2): vec2; /** Returns the vector minus vec. */ sub(vec: vec2): vec2; /** Returns a string representation of the vector. */ toString(): string; /** Multiplies the components by the number scale. */ uniformScale(scale: number): vec2; /** Returns the vector (0, -1). */ static down(): vec2; /** Returns the vector (-1, 0). */ static left(): vec2; /** Linearly interpolates between the two vectors vecA and vecB by the factor t. */ static lerp(vecA: vec2, vecB: vec2, t: number): vec2; /** Returns a new vector containing the largest value of each component in the two vectors. */ static max(vecA: vec2, vecB: vec2): vec2; /** Returns a new vector containing the smallest value of each component in the two vectors. */ static min(vecA: vec2, vecB: vec2): vec2; /** Returns the vector (1, 1). */ static one(): vec2; /** Returns the vector (1, 0). */ static right(): vec2; /** Returns the vector (0, 1). */ static up(): vec2; /** Returns the vector (0, 0). */ static zero(): vec2; } /** * A three dimensional vector. * Lens Studio v1.0.0+ */ declare class vec3 { constructor(x: number, y: number, z: number); /** Alternate name for the z component. */ b: number; /** Alternate name for the y component. */ g: number; /** Returns the length of the vector. */ length: number; /** Returns the squared length of the vector. */ lengthSquared: number; /** Alternate name for the x component. */ r: number; /** x component of the vec3. */ x: number; /** y component of the vec3. */ y: number; /** z component of the vec3. */ z: number; /** Returns the vector plus vec. */ add(vec: vec3): vec3; /** Returns the angle in radians between the vector and vec. */ angleTo(vec: vec3): number; /** Returns a copy of the vector with its length clamped to length. */ clampLength(length: number): vec3; /** Returns the cross product of the vector and vec */ cross(vec: vec3): vec3; /** Returns the distance between the vector and the vector vec. */ distance(vec: vec3): number; /** Returns the division of the vector by the vector vec. */ div(vec: vec3): vec3; /** Returns the dot product of the vector and vec. */ dot(vec: vec3): number; /** Returns whether this is equal to vec. */ equal(vec: vec3): boolean; /** Returns a copy of the vector moved towards the point point by the amount magnitude. */ moveTowards(point: vec3, magnitude: number): vec3; /** Returns the component-wise multiplication product of the vector and vec. */ mult(vec: vec3): vec3; /** Returns a copy of the vector with its length scaled to 1. */ normalize(): vec3; /** Returns a copy of the vector projected onto the vector vec. */ project(vec: vec3): vec3; /** Projects the vector onto the plane represented by the normal normal. */ projectOnPlane(normal: vec3): vec3; /** Returns a copy of the vector reflected across the plane defined by the normal vec. */ reflect(vec: vec3): vec3; /** Returns a copy of the vector rotated towards the point point by amount. */ rotateTowards(point: vec3, amount: number): vec3; /** Returns the component-wise multiplication product of the vector and vec. */ scale(vec: vec3): vec3; /** Returns the vector minus vec. */ sub(vec: vec3): vec3; /** Returns a string representation of the vector. */ toString(): string; /** Multiplies the components by the number scale. */ uniformScale(scale: number): vec3; /** Returns the vector (0, 0, -1). */ static back(): vec3; /** Returns the vector (0, -1, 0). */ static down(): vec3; /** Returns the vector (0, 0, 1). */ static forward(): vec3; /** Returns the vector (-1, 0, 0). */ static left(): vec3; /** Linearly interpolates between the two vectors vecA and vecB by the factor t. */ static lerp(vecA: vec3, vecB: vec3, t: number): vec3; /** Returns a new vector containing the largest value of each component in the two vectors. */ static max(vecA: vec3, vecB: vec3): vec3; /** Returns a new vector containing the smallest value of each component in the two vectors. */ static min(vecA: vec3, vecB: vec3): vec3; /** Returns the vector (1, 1, 1). */ static one(): vec3; /** Makes the vectors vecA and vecB normalized and orthogonal to each other. */ static orthonormalize(vecA: vec3, vecB: vec3): void; /** Returns the vector (1, 0, 0). */ static right(): vec3; /** Spherically interpolates between the two vectors vecA and vecB by the factor t. */ static slerp(vecA: vec3, vecB: vec3, t: number): vec3; /** Returns the vector (0, 1, 0). */ static up(): vec3; /** Returns the vector (0, 0, 0). */ static zero(): vec3; } /** * A four dimensional vector. * Lens Studio v1.0.0+ */ declare class vec4 { constructor(x: number, y: number, z: number, w: number); /** Alternate name for the w component. */ a: number; /** Alternate name for the z component. */ b: number; /** Alternate name for the y component. */ g: number; /** Returns the length of the vector. */ length: number; /** Returns the squared length of the vector. */ lengthSquared: number; /** Alternate name for the x component. */ r: number; /** w component of the vec4. */ w: number; /** x component of the vec4. */ x: number; /** y component of the vec4. */ y: number; /** z component of the vec4. */ z: number; /** Returns the vector plus vec. */ add(vec: vec4): vec4; /** Returns the angle between the vector and vec. */ angleTo(vec: vec4): number; /** Returns a copy of the vector with its length clamped to length. */ clampLength(length: number): vec4; /** Returns the distance between the vector and the vector vec. */ distance(vec: vec4): number; /** Returns the division of the vector by the vector vec. */ div(vec: vec4): vec4; /** Returns the dot product of the vector and vec. */ dot(vec: vec4): number; /** Returns whether this is equal to vec. */ equal(vec: vec4): boolean; /** Returns a copy of the vector moved towards the point point by the amount magnitude. */ moveTowards(point: vec4, magnitude: number): vec4; /** Returns the component-wise multiplication product of the vector and vec. */ mult(vec: vec4): vec4; /** Returns a copy of the vector with its length scaled to 1. */ normalize(): vec4; /** Returns a copy of the vector projected onto the vector vec. */ project(vec: vec4): vec4; /** Projects the vector onto the plane represented by the normal normal. */ projectOnPlane(normal: vec4): vec4; /** Returns a copy of the vector reflected across the plane defined by the normal vec. */ reflect(vec: vec4): vec4; /** Returns the component-wise multiplication product of the vector and vec. */ scale(vec: vec4): vec4; /** Returns the vector minus vec. */ sub(vec: vec4): vec4; /** Returns a string representation of the vector. */ toString(): string; /** Multiplies the components by the number scale. */ uniformScale(scale: number): vec4; /** Linearly interpolates between the two vectors vecA and vecB by the factor t. */ static lerp(vecA: vec4, vecB: vec4, t: number): vec4; /** Returns a new vector containing the largest value of each component in the two vectors. */ static max(vecA: vec4, vecB: vec4): vec4; /** Returns a new vector containing the smallest value of each component in the two vectors. */ static min(vecA: vec4, vecB: vec4): vec4; /** Returns the vector (1, 1, 1, 1). */ static one(): vec4; /** Returns the vector (0, 0, 0, 0). */ static zero(): vec4; } /** * A vector containing 4 boolean values. * Lens Studio v1.5.0+ */ declare class vec4b { /** Creates a new instance of a vec4b. */ constructor(x: boolean, y: boolean, z: boolean, w: boolean); /** Returns a string representation of the vector. */ toString(): string; /** Alternate name for the w component. */ a: boolean; /** Alternate name for the z component. */ b: boolean; /** Alternate name for the y component. */ g: boolean; /** Alternate name for the x component. */ r: boolean; /** w component of the vec4b. */ w: boolean; /** x component of the vec4b. */ x: boolean; /** y component of the vec4b. */ y: boolean; /** z component of the vec4b. */ z: boolean; } /** A 2x2 matrix. */ declare class mat2 { /** Creates a new mat2, defaulting to identity values. */ constructor(); /** The first column of the matrix. */ column0: vec2; /** The second column of the matrix. */ column1: vec2; /** Returns a string representation of the matrix. */ description: string; /** Returns the result of adding the two matrices together. */ add(mat: mat2): mat2; /** Returns the determinant of the matrix. */ determinant(): number; /** Returns the result of dividing the two matrices. */ div(mat: mat2): mat2; /** Returns whether the two matrices are equal. */ equal(mat: mat2): boolean; /** Returns the inverse of the matrix. */ inverse(): mat2; /** Returns the result of multiplying the two matrices. */ mult(mat: mat2): mat2; /** Returns the result of scalar multiplying the matrix. */ multiplyScalar(scalar: number): mat2; /** Returns the result of subtracting the two matrices. */ sub(mat: mat2): mat2; /** Returns a string representation of the matrix. */ toString(): string; /** Returns the transpose of this matrix. */ transpose(): mat2; /** Returns the identity matrix. */ static identity(): mat2; /** Returns a matrix with all zero values. */ static zero(): mat2; } /** A 3x3 matrix. */ declare class mat3 { /** Creates a new mat3, defaulting to identity values. */ constructor(); /** The first column of the matrix. */ column0: vec3; /** The second column of the matrix. */ column1: vec3; /** The third column of the matrix. */ column2: vec3; /** Returns a string representation of the matrix. */ description: string; /** Returns the result of adding the two matrices together. */ add(mat: mat3): mat3; /** Returns the determinant of the matrix. */ determinant(): number; /** Returns the result of dividing the two matrices. */ div(mat: mat3): mat3; /** Returns whether the two matrices are equal. */ equal(mat: mat3): boolean; /** Returns the inverse of the matrix. */ inverse(): mat3; /** Returns the result of multiplying the two matrices. */ mult(mat: mat3): mat3; /** Returns the result of scalar multiplying the matrix. */ multiplyScalar(scalar: number): mat3; /** Returns the result of subtracting the two matrices. */ sub(mat: mat3): mat3; /** Returns a string representation of the matrix. */ toString(): string; /** Returns the transpose of this matrix. */ transpose(): mat3; /** Returns the identity matrix. */ static identity(): mat3; /** Returns a matrix representing the specified rotation. */ static makeFromRotation(arg1: quat): mat3; /** Returns a matrix with all zero values. */ static zero(): mat3; } /** A 4x4 matrix. */ declare class mat4 { /** Creates a new mat4, defaulting to identity values. */ constructor(); /** The first column of the matrix. */ column0: vec4; /** The second column of the matrix. */ column1: vec4; /** The third column of the matrix. */ column2: vec4; /** The fourth column of the matrix. */ column3: vec4; /** Returns a string representation of the matrix. */ description: string; /** Returns the result of adding the two matrices together. */ add(mat: mat4): mat4; /** Returns the determinant of the matrix. */ determinant(): number; /** Returns the result of dividing the two matrices. */ div(mat: mat4): mat4; /** Returns whether the two matrices are equal. */ equal(mat: mat4): boolean; /** Returns an euler angle representation of this matrix’s rotation, in radians. */ extractEulerAngles(): vec3; /** Returns the inverse of the matrix. */ inverse(): mat4; /** Returns the result of multiplying the two matrices. */ mult(mat: mat4): mat4; /** Returns the direction vector multiplied by this matrix. */ multiplyDirection(direction: vec3): vec3; /** Returns the point point multiplied by this matrix. */ multiplyPoint(point: vec3): vec3; /** Returns the result of scalar multiplying the matrix. */ multiplyScalar(scalar: number): mat4; /** Returns the vector multiplied by this matrix. */ multiplyVector(vector: vec4): vec4; /** Returns the result of subtracting the two matrices. */ sub(mat: mat4): mat4; /** Returns a string representation of the matrix. */ toString(): string; /** Returns the transpose of this matrix. */ transpose(): mat4; /** Returns the two matrices multiplied component-wise. */ static compMult(arg1: mat4, arg2: mat4): mat4; /** Returns a new matrix with translation rotation: translation, rotation, and scale scale. */ static compose(translation: vec3, rotation: quat, scale: vec3): mat4; /** Returns a new matrix with the specified euler angles ( radians: in). */ static fromEulerAngles(euler: vec3): mat4; /** Returns a new matrix with x euler angle xAngle ( radians: in). */ static fromEulerX(xAngle: number): mat4; /** Returns a new matrix with y euler angle yAngle ( radians: in). */ static fromEulerY(yAngle: number): mat4; /** Returns a new matrix with z euler angle zAngle ( radians: in). */ static fromEulerZ(zAngle: number): mat4; /** Returns a new matrix with rotation rotation. */ static fromRotation(rotation: quat): mat4; /** Returns a new matrix with scale scale. */ static fromScale(scale: vec3): mat4; /** Returns a new matrix with the translation translation. */ static fromTranslation(translation: vec3): mat4; /** Returns the identity matrix. */ static identity(): mat4; /** Returns a new matrix generated using the provided arguments. */ static lookAt(eye: vec3, center: vec3, up: vec3): mat4; /** Returns a new matrix using the provided vectors. */ static makeBasis(x: vec3, y: vec3, z: vec3): mat4; /** Returns a new matrix generated using the provided arguments. */ static orthographic(left: number, right: number, bottom: number, top: number, zNear: number, zFar: number): mat4; /** Returns the outer product of the two matrices. */ static outerProduct(arg1: vec4, arg2: vec4): mat4; /** Returns a new matrix generated using the provided arguments. */ static perspective(fovY: number, aspect: number, zNear: number, zFar: number): mat4; /** Returns a matrix with all zero values. */ static zero(): mat4; } /** A quaternion, used to represent rotation. */ declare class quat { /** w component of the quat. */ w: number; /** x component of the quat. */ x: number; /** y component of the quat. */ y: number; /** z component of the quat. */ z: number; /** Creates a new quat. */ constructor(w: number, x: number, y: number, z: number); /** Returns the dot product of the two quats. */ dot(quat: quat): number; /** Returns whether this quat and b are equal. */ equal(b: quat): boolean; /** Returns the rotation angle of the quat. */ getAngle(): number; /** Returns the rotation axis of the quat. */ getAxis(): vec3; /** Returns an inverted version of the quat. */ invert(): quat; /** Returns the product of this quat and b. */ multiply(b: quat): quat; /** Returns the result of rotating direction vector vec3 by this quat. */ multiplyVec3(vec3: vec3): vec3; /** Normalizes the quat. */ normalize(): void; /** Returns an euler angle representation of the quat, in radians. */ toEulerAngles(): vec3; /** Returns a string representation of the quat. */ toString(): string; /** Returns a new quat with angle angle and axis axis. */ static angleAxis(angle: number, axis: vec3): quat; /** Returns the angle between a and b. */ static angleBetween(a: quat, b: quat): number; /** Returns a new quat using the euler angles x, y, z ( radians: in). */ static fromEulerAngles(x: number, y: number, z: number): quat; /** Returns a new quat using the euler angle eulerVec ( radians: in). */ static fromEulerVec(eulerVec: vec3): quat; /** Returns a new quat linearly interpolated between a and b. */ static lerp(a: quat, b: quat, t: number): quat; /** Returns a new quat with a forward vector forward and up vector up. */ static lookAt(forward: vec3, up: vec3): quat; /** Returns the identity quaternion. */ static quatIdentity(): quat; /** Returns a rotation quat between direction vectors from and to. */ static rotationFromTo(from: vec3, to: vec3): quat; /** Returns a new quat spherically linearly interpolated between a and b. */ static slerp(a: quat, b: quat, t: number): quat; } /** Types of weather returned by UserContextSystem’s requestWeatherCondition() callback. Lens Studio v2.1+ */ declare enum WeatherCondition { /** Unknown or unsupported weather condition */ Unknown, Lightning, LowVisibility, PartlyCloudy, ClearNight, Cloudy, Rainy, Hail, Snow, Windy, Sunny, } /** Data type used for color values. */ declare enum Colorspace { RGBA, RG, R, } /** Describes the current status of a VideoTextureProvider. Lens Studio v1.5.0+ */ declare enum VideoStatus { /** The video playback has stopped */ Stopped, /** The video is being prepared */ Preparing, /** The video is playing */ Playing, /** The video playback is paused */ Paused, } declare enum MeshClassificationFormat { /** Do not bake classifications to mesh */ None, /** Classifications are baked per vertex - vertices with multiple classes will use the value from the last face */ PerVertexFast, } declare enum MeshIndexType { /** No index data type */ None, /** Unsigned integer, this is the value normally used */ UInt16, } declare enum MeshTopology { /** Draws unconnected line segments. Each group of two vertices specifies a new line segment. */ Lines, /** Draws connected line segments. Starting with the second vertex, a line is drawn between each vertex and the preceding one. */ LineStrip, /** Draws individual points. Each vertex specifies a new point to draw. */ Points, /** Draws unconnected triangles. Each group of three vertices specifies a new triangle. */ Triangles, /** * Draws connected triangles sharing one central vertex. The first vertex is the shared one, or “hub” vertex. Starting with the third vertex, each vertex forms a triangle connecting with the * previous vertex and hub vertex. */ TriangleFan, /** Draws connected triangles in a strip. After the first two vertices, each vertex defines the third point on a new triangle extending from the previous one. */ TriangleStrip, } /** Used by the horizontalAlignment property in MeshVisual. When a ScreenTransform is attached to the same SceneObject, this determines how the mesh will be positioned horizontally. */ declare enum HorizontalAlignment { /** The mesh will be aligned to the left side. */ Left, /** The mesh will be centered. */ Center, /** The mesh will be aligned to the right side. */ Right, } /** * Options for stretching a mesh to fit a ScreenTransform’s bounding box. Used in MeshVisual’s stretchMode property, as long as the SceneObject has a ScreenTransform attached. Also used in TextFill’s * textureStretch property to control texture stretching when drawing text. */ declare enum StretchMode { /** Scale uniformly so that both width and height fit within the bounds. */ Fit, /** Scale uniformly so that both width and height meet or exceed the bounds. */ Fill, /** Scale non-uniformly to match the exact width and height of the bounds. */ Stretch, /** Scale uniformly to match the same height as the bounds. */ FitHeight, /** Scale uniformly to match the same width as the bounds. */ FitWidth, /** Same as Fill, but when used with the Image component any area outside of the bounds is cropped out. */ FillAndCut, } /** Used by the verticalAlignment property in MeshVisual. When a ScreenTransform is attached to the same SceneObject, this determines how the mesh will be positioned vertically. */ declare enum VerticalAlignment { /** The mesh will be aligned to the bottom side. */ Bottom, /** The mesh will be centered. */ Center, /** The mesh will be aligned to the top side. */ Top, } /** Tracking modes used by the DeviceTracking component to specify what type of tracking to use. */ declare enum DeviceTrackingMode { /** Use gyroscope tracking ( only: rotation) */ Rotation, /** Use surface tracking (position and rotation) */ Surface, /** Use native tracking (position and rotation) */ World, } /** Used by Head.setAttachmentPointType() to specify the type of attachment used with a Head binding. */ declare enum AttachmentPointType { HeadCenter, CandideCenter, TriangleBarycentric, LeftEyeballCenter, RightEyeballCenter, } /** * Enum values specifying each type of manipulation. See ManipulateComponent. * ``` * // Disables the scale functionality on a manipulate component when a user taps * //@input Component.ManipulateComponent manip * * function onTap(eventData) * { * script.manip.enableManipulateType(ManipulateType.Scale, false); * } * var tapEvent = script.createEvent("TapEvent"); * tapEvent.bind(onTap); * ``` */ declare enum ManipulateType { /** The object can be scaled by pinching with two fingers. */ Scale, /** The object can be rotated by swiveling with two fingers. */ Swivel, /** The object can be moved by touching and dragging. */ Drag, } /** * Used with FaceInsetVisual.faceRegion for setting the face region to draw. * ``` * //@input Component.FaceInsetVisual faceInset * // Sets the face inset to draw the mouth * script.faceInset.faceRegion = FaceInsetRegion.Mouth; * ``` */ declare enum FaceInsetRegion { /** Targets the left eye */ LeftEye, /** Targets the right eye */ RightEye, /** Targets the mouth */ Mouth, /** Targets the nose */ Nose, /** Targets the entire face */ Face, } /** * Result object returned from ManipulateComponent.intersectManipulateFrame(). * ``` * // Returns an intersectManipulateFrame based on user touch position * //@input Component.ManipulateComponent manip * * function onTap(eventData) * { * var touchPos = eventData.getTouchPosition(); * var intersectManipFrame = script.manip.intersectManipulateFrame(touchPos); * if(intersectManipFrame && intersectManipFrame.isValid()) * { * screenPoint = intersectManipFrame.getIntersectionPoint(); * * print(screenPoint.toString()); * } * } * var tapEvent = script.createEvent("TapEvent"); * tapEvent.bind(onTap); * ``` */ interface ManipulateFrameIntersectResult { /** If there was a valid intersection, returns the intersection point in world space. */ getIntersectionPoint(): vec3; /** Returns whether there was a valid intersection. */ isValid(): boolean; } /** * The base class for all components. Components are attached to SceneObjects. */ interface Component extends SerializableWithUID { /** If disabled, the Component will stop enacting its behavior. */ enabled: boolean; /** Destroys the component. */ destroy(): void; /** Returns the SceneObject the component is attached to. */ getSceneObject(): SceneObject; /** Returns the Transform this component is attached to. */ getTransform(): Transform; } declare namespace Component { /** Base class for all visual Components (e.g. MeshVisual). */ interface Visual extends Component { /** Returns the order of this Visual in the render queue. */ getRenderOrder(): number; /** Sets the order of this Visual in the render queue. */ setRenderOrder(value: number): void; } /** * The base class for all mesh rendering components. Comparable to the former class “MeshVisual”, which was split into the classes: BaseMeshVisual, MaterialMeshVisual, and RenderMeshVisual. Lens * Studio v2.3+ */ interface BaseMeshVisual extends Visual { /** * When a ScreenTransform is present on this SceneObject, and extentsTarget is a child of this SceneObject, extentsTarget will be repositioned to match the exact area this MeshVisual is being * rendered. Very useful for Image and Text components. */ extentsTarget: ScreenTransform; /** When a ScreenTransform is attached to the same SceneObject, this controls how the mesh will be positioned horizontally depending on stretchMode. */ horizontalAlignment: HorizontalAlignment; /** None = 0, Caster = 1, Receiver = 2 */ meshShadowMode: number; /** * Affects the color of shadows being cast by this MeshVisual. The color of the cast shadow is a mix between shadowColor and the material’s base texture color. The alpha value of shadowColor * controls the mixing of these two colors, with 0 = shadowColor and 1 = shadowColor * textureColor. */ shadowColor: vec4; /** Density of shadows cast by this MeshVisual. */ shadowDensity: number; /** When a ScreenTransform is attached to the same SceneObject, this controls how the mesh will be stretched relative to the ScreenTransform’s boundaries. */ stretchMode: StretchMode; /** When a ScreenTransform is attached to the same SceneObject, this controls how the mesh will be positioned vertically depending on stretchMode. */ verticalAlignment: VerticalAlignment; /** * Projects screen positions from camera’s view onto the mesh’s UVs. If the MeshVisual’s material uses the same texture as the camera input, the MeshVisual will look identical to the part of * the screen it covers. */ snap(camera: Camera): void; } /** * Renders the scene to a Render Target texture. A Camera will only render a SceneObject if the SceneObject’s render layer is enabled on the Camera. For more information, see the Camera and * Layers guide. */ interface Camera extends Component { /** The aspect ratio of the camera (width/height). */ aspect: number; /** When enableClearColor is true and inputTexture is null, this color is used to clear this Camera’s renderTarget before drawing to it. */ clearColor: vec4; /** Determines the way depth is handled on this Camera. Changing this can help sort objects at different distance ranges. */ depthBufferMode: Camera.DepthBufferMode; /** * Controls which Camera settings will be overridden by physical device properties. For example, this can be used to override the fov property to match the device camera’s actual field of * view. */ devicePropertyUsage: Camera.DeviceProperty; /** * If enabled, this Camera will clear the color on its renderTarget before drawing to it. inputTexture will be used to clear it unless it is null, in which case clearColor is used * instead. */ enableClearColor: boolean; /** If enabled, this Camera will clear the depth buffer on its renderTarget before drawing to it. */ enableClearDepth: boolean; /** The distance of the far clipping plane. */ far: number; /** The Camera’s field of view in radians. */ fov: number; /** When enableClearColor is true, this texture is used to clear this Camera’s renderTarget before drawing. If this texture is null, clearColor will be used instead. */ inputTexture: Asset.Texture; /** * A texture controlling which parts of the output texture the camera will draw to. The “red” value of each pixel determines how strongly the camera will draw to that part of the image. For * example, a completely black section will cause the camera to not draw there at all. A completely white ( red: or) section will cause the camera to draw normally. Colors in like: * between, gray, will be semitransparent. */ maskTexture: Asset.Texture; /** The distance of the near clipping plane. */ near: number; /** Controls the set of layers this Camera will render. */ renderLayer: LayerSet; /** The sorting order the Camera renders in. Every frame, Cameras render in ascending order determined by their renderOrder properties. */ renderOrder: number; /** The RenderTarget this Camera will draw to. */ renderTarget: Asset.Texture; /** The orthographic size of the camera. */ size: number; /** Read-only property describing which type of rendering the camera uses. */ type: Camera.Type; /** For orthographic cameras, returns the camera size as (width, height). */ getOrthographicSize(): vec2; /** Returns true if a sphere with the specified world space center position and radius is visible within the camera frustum, false otherwise. */ isSphereVisible(center: vec3, radius: number): boolean; /** * Converts a world space position to a raw screen space position. The screen space position will be returned as a vec3 with x,y representing normalized screen space, and z representing a raw * depth value not directly convertible to world units. This returned value will mostly be useful for passing into unproject(). */ project(worldSpacePoint: vec3): vec3; /** * Converts a screen space position to a world space position, given an absolute depth. The screen space position should be provided as a vec2 in the range ([0-1], [0-1]), (0,0) being the * top-left of the screen and (1,1) being the bottom-right. The returned world space position will be the point absoluteDepth units away from the Camera’s near plane at the point specified * in screen space. */ screenSpaceToWorldSpace(normalizedScreenSpacePoint: vec2, absoluteDepth: number): vec3; /** * Converts a raw screen space position to a world space position. clipSpacePoint should be a vec3 returned from a previous project() call, since the z value represents a raw depth value not * directly convertible to world units. */ unproject(clipSpacePoint: vec3): vec3; /** * Converts the world space position worldSpacePoint to a screen space position. Screen positions are represented in the range ([0-1], [0-1]), (0,0) being the top-left of the screen and (1,1) * being the bottom-right. */ worldSpaceToScreenSpace(worldSpacePoint: vec3): vec2; } /** Used for positioning objects in 2d screen space. It overrides the regular Transform component on the SceneObject it’s attached to. */ interface ScreenTransform extends Component { /** * The anchor rect positioning this ScreenTransform proportional to its parent’s bounds. For each field, a value of 0 equals the parent’s center point, and value of -1 or 1 (depending on the * side) equals the parent’s full boundary. * For example, a top value of 1.0 means this ScreenTransform’s top edge will be exactly at the top edge of its parent. * A bottom value of -0.5 means this ScreenTransform’s bottom edge will be halfway between its parent’s bottom edge and center. * A right value of 0 means this ScreenTransform’s right edge will be exactly at its parent’s center. * A left value of -2 means this ScreenTransform’s left edge will be twice as far from its parent’s center as its parent’s left edge is. */ anchors: Rect; /** * This rect is applied after anchors to determine the final boundaries of the ScreenTransform. It adds an offset in world units (based on the parent Camera’s size property) to each edge of * the ScreenTransform’s boundaries. * For example, a value of 0 for any side will have no effect on boundaries. * A value of 1.0 for any side will offset that edge by 1.0 world unit. */ offsets: Rect; /** Normalized (x, y) position of the center point used in rotation. (-1, -1) being bottom left, (0, 0) being center, and (1, 1) being top right of the image. */ pivot: vec2; /** Basic local position in world units relative to the parent’s center. Useful for animating screen elements with a simple offset. */ position: vec3; /** Basic local rotation applied to the SceneObject. */ rotation: quat; /** Basic local scaling applied to the SceneObject. */ scale: vec3; /** Returns true if the screen position is within the boundaries of this ScreenTransform. Useful for checking if a touch event overlaps with this object. */ containsScreenPoint(screenPoint: vec2): boolean; /** Returns true if the world position is within the boundaries of this ScreenTransform. The z value of the world position is ignored. */ containsWorldPoint(worldPoint: vec3): boolean; /** * Returns true if this ScreenTransform is in a valid screen hierarchy, which is required for anchoring to work. To be in a valid screen hierarchy there must be a Camera component upward in * the parent hierarchy, and every object between the Camera and this one must also have a ScreenTransform. */ isInScreenHierarchy(): boolean; /** Converts from a normalized (-1 to 1) position within this ScreenTransform’s bounds to a screen position. */ localPointToScreenPoint(relativeLocalPoint: vec2): vec2; /** Converts from a normalized (-1 to 1) position within this ScreenTransform’s bounds to a world position. */ localPointToWorldPoint(relativeLocalPoint: vec2): vec3; /** Converts from a screen position to a normalized (-1 to 1) position within this ScreenTransform’s bounds. */ screenPointToLocalPoint(screenPoint: vec2): vec2; /** * Converts from a screen position to a normalized (-1 to 1) position within the parent object’s bounds. This value is useful because it can be used directly for this ScreenTransform’s anchor * positioning. */ screenPointToParentPoint(screenPoint: vec2): vec2; /** Converts from a world position to a normalized (-1 to 1) position within this ScreenTransform’s bounds. */ worldPointToLocalPoint(worldPoint: vec3): vec2; /** * Converts from a world position to a normalized (-1 to 1) position within the parent object’s bounds. This value is useful because it can be used directly for this ScreenTransform’s anchor * positioning. */ worldPointToParentPoint(worldPoint: vec3): vec2; } /** Applies a face stretch effect. Face stretch features can be added to a FaceStretchVisual through the Inspector panel in Lens Studio. See the Face Stretch Guide for more information. */ interface FaceStretchVisual extends BaseMeshVisual { /** The index of the face the stretch will be applied to. */ faceIndex: number; /** Returns the weight of the face stretch feature named feature. */ getFeatureWeight(feature: string): number; /** Sets the weight of the face stretch feature named feature to intensity. The intensity must be greater than -0.5 and less than 2. */ setFeatureWeight(feature: string, intensity: number): void; } /** Applies a liquify effect to anything rendered behind it. */ interface LiquifyVisual extends BaseMeshVisual { /** How strong the liquify effect is. */ intensity: number; /** The radius of the liquify effect circle. */ radius: number; } /** * Base class for all MeshVisual components using Materials to render. Comparable to the former class “MeshVisual”, which was split into the classes: BaseMeshVisual, MaterialMeshVisual, and * RenderMeshVisual. * ``` * // @input Component.MaterialMeshVisual visual * * // Set the material's main color to red * script.visual.mainPass.baseColor = new vec4(1, 0, 0, 1); * ``` */ interface MaterialMeshVisual extends BaseMeshVisual { /** Returns the first Material. */ mainMaterial: Asset.Material; /** Returns the mainPass of the mainMaterial. */ mainPass: Pass; /** Adds a Material to use for rendering. */ addMaterial(material: Asset.Material): void; /** Clears all Materials. */ clearMaterials(): void; /** Returns the Material at index index. */ getMaterial(index: number): Asset.Material; /** Returns the number of Materials used for rendering. */ getMaterialsCount(): number; } /** * Applies an eye color effect to a face. * ``` * // Prints the eye property `faceIndex`, the face the eye color effect is applied to * var face = script.getSceneObject().getFirstComponent("Component.EyeColorVisual").faceIndex; * * print("faceIndex = " + face.toString()) * ``` */ interface EyeColorVisual extends MaterialMeshVisual { /** The index of the face this EyeColorVisual is attached to. */ faceIndex: number; } /** * Draws a section of a tracked face. */ interface FaceInsetVisual extends MaterialMeshVisual { /** The index of the face this FaceInsetVisual uses. */ faceIndex: number; /** The region of the face this FaceInsetVisual draws. */ faceRegion: FaceInsetRegion; /** Flips the drawn face region horizontally if enabled. */ flipX: boolean; /** Flips the drawn face region vertically if enabled. */ flipY: boolean; /** The amount of alpha fading applied from the border of the face inset inward. This value must be in the range 0-1. */ innerBorderRadius: number; /** The amount of alpha fading applied from the border of the face inset outward. This value must be in the range 0-1. */ outerBorderRadius: number; /** * The x and y scaling used to draw the face region. Think of scaling as meaning how many times the face region could fit into the drawing area. Higher values will zoom away from the face * region, and lower values will zoom into it. The normal, unzoomed scaling value is (1,1). */ sourceScale: vec2; /** Determines the quality of the face inset’s borders. A higher value means better looking borders but lower performance. This value must be greater than 10 and less than 100. */ subdivisionsCount: number; } /** * Applies a face mask effect. See the Face Mask Guide for more information. * ``` * // Run this in the "Frame Updated" event to switch between drawn faces twice a second * // Make sure "Use Orig. Face" is enabled on the FaceMask * * //@input Component.FaceMaskVisual faceMask * //@input Component.Head head * * var numFaces = script.head.getFacesCount(); * script.faceMask.originalFaceIndex = Math.floor(getTime() * 2.0) % numFaces; * ``` */ interface FaceMaskVisual extends MaterialMeshVisual { customMaskOnMouthClosed: Asset.Texture; /** The index of the face this effect is attached to. */ faceIndex: number; hidesMaskOnMouthClosed: boolean; /** If “Use Orig. Face” is enabled for this FaceMaskVisual in the Inspector panel, this property specifies the face index to use for drawing the mask. */ originalFaceIndex: number; swapsMaskOnMouthClosed: boolean; teethAlpha: number; } /** * A 2D visual used for drawing texture assets. Commonly used with ScreenTransform for drawing images on the screen. * ``` * //@input Component.Image image * //@input Asset.Texture texture * * // Set the Image component's texture * script.image.mainPass.baseTex = script.texture; * * // Set the Image's pivot point * script.image.pivot = new vec2(1, 1); * ``` */ interface Image extends MaterialMeshVisual { /** If enabled, the drawn image will be flipped horizontally. */ flipX: boolean; /** If enabled, the drawn image will be flipped vertically. */ flipY: boolean; /** The location of the Image’s pivot point relative to its boundaries. Where (-1, -1) is the bottom left corner, (0, 0) is the center, and (1, 1) is the top right corner of the Image. */ pivot: vec2; } /** * Uses an input color lookup table image to adjust the coloring of the Lens. See the Color Correction Post Effect guide for more information. * ``` * // Sets the post effects texture to a custom texture in script and sets the color to red * //@input Component.PostEffectVisual postEffect * //@input Asset.Texture texture * * script.postEffect.mainPass.baseTex = script.texture; * script.postEffect.mainPass.baseColor = new vec4(1.0,0.0,0.0,1.0); * ``` */ type PostEffectVisual = MaterialMeshVisual; /** * Writes video feed depth information to the depth buffer, which automatically sets up depth occlusion for 3D visuals. Only works in some cases, such as in Lenses for Spectacles 3. See the * Lenses for Spectacles guide for more information. */ type DepthSetter = PostEffectVisual; /** Renders a RenderMesh asset in the scene. Comparable to the former class “MeshVisual”, which was split into the classes: BaseMeshVisual, MaterialMeshVisual, and RenderMeshVisual. */ interface RenderMeshVisual extends MaterialMeshVisual { /** The BlendShapes component used for rendering this mesh. */ blendShape: BlendShapes; /** The RenderMesh asset to render. */ mesh: Asset.RenderMesh; /** Sets the Skin to use for rendering this mesh. */ setSkin(skin: Skin): void; } /** * Visual effect used to add subtle retouching effects to detected faces ( skin: soft, whitening: teeth, etc.). To learn more, visit the Retouch Guide. * ``` * // Sets a Retouch component's teeth whitening intensity * * //@input Component.RetouchVisual retouchVisual * * script.retouchVisual.teethWhiteningIntensity = 0.4; * ``` */ interface RetouchVisual extends MaterialMeshVisual { /** The strength of the eye whitening effect. */ eyeWhiteningIntensity: number; /** The index of the face the effect is being applied to. */ faceIndex: number; /** The strength of the eye sharpening effect. */ sharpenEyeIntensity: number; /** The strength of the soft-skin effect. */ softSkinIntensity: number; /** The strength of the teeth whitening effect. */ teethWhiteningIntensity: number; } /** * Represents a renderable 2D visual in Lens Studio. * ``` * // Flip the Sprite upside down * //@input Component.SpriteVisual sprite * script.sprite.flipY = true; * * // Change the Sprite's fill mode to "stretch" * //@input Component.SpriteVisual sprite * script.sprite.fillMode = 2; * * // Change the Sprite's pivot point to top right corner * //@input Component.SpriteVisual sprite * script.sprite.pivot = new vec2(1,1); * ``` */ interface SpriteVisual extends MaterialMeshVisual { /** * Which type of fill the sprite uses. Possible values: * ``` * Fit = 0 * Fill = 1 * Stretch = 2 * ``` */ fillMode: 0 | 1 | 2; /** Whether the sprite is flipped over the Y-axis (sideways). */ flipX: boolean; /** Whether the sprite is flipped over the X-axis (upside-down). */ flipY: boolean; /** * The location of the sprite’s pivot point relative to its boundaries. The pivot’s x value is a relative horizontal position, -1 being the sprite’s left border and 1 being the sprite’s right * border. Similarly, the y value is a relative vertical position, -1 being the sprite’s bottom border and 1 being the sprite’s top border. */ pivot: vec2; /** Returns the width and height of the mesh the SpriteVisual is applied to. */ getMeshSize(): vec2; } /** Visual component that renders dynamic text. See the Text guide for more information. */ interface Text extends BaseMeshVisual { /** Settings for drawing a background behind the text. */ backgroundSettings: BackgroundSettings; /** If enabled, the text material will use Depth Testing. Useful when Text exists in 3D space. */ depthTest: boolean; /** Settings for how dropshadow is used in text drawing. */ dropshadowSettings: DropshadowSettings; /** Font asset used. */ font: Asset.Font; /** Controls how text should be handled when it goes past the horizontal boundaries. */ horizontalOverflow: HorizontalOverflow; /** * Modifies the spacing between letters. Set to 0 by default, which uses the font’s normal letter spacing. Negative values will remove space between letters, and positive values will add more * space between letters. */ letterSpacing: number; /** Settings for how text outline is used in text drawing. */ outlineSettings: OutlineSettings; /** Font size used. */ size: number; /** If enabled, the rendered text will always scale to fit the boundaries. */ sizeToFit: boolean; /** Text string to be drawn. */ text: string; /** Settings for how the text is drawn, such as fill color or texture. */ textFill: TextFill; /** Controls how text should be handled when it goes past the vertical boundaries. */ verticalOverflow: VerticalOverflow; } /** * Transforms inputs (Textures or Float32Array) into outputs (Textures or Float32Array) using a neural network. The neural network is represented by an MLAsset, which is set as the model * property. For more information, see the MLComponent Overview. */ interface MLComponent extends Component { /** Controls the inference mode that MLComponent will run in. For example, GPU, CPU, etc. */ inferenceMode: MachineLearning.InferenceMode; /** Binary ML model supplied by the user. */ model: Asset.MLAsset; /** Function that gets called when model loading is finished. */ onLoadingFinished: () => void; /** Function that gets called when the model stops running. */ onRunningFinished: () => void; /** Render order of the MLComponent. */ renderOrder: number; /** Returns the current status of the neural network model. */ state: MachineLearning.ModelState; /** Builds the MLComponent model when all placeholders are determined. Config is an array of Input and Output placeholders. */ build(placeholders: BasePlaceholder[]): void; /** Stops running the MLComponent. The onRunningFinished callback will not be executed. */ cancel(): void; /** Returns the InputPlaceholder with the matching name. */ getInput(name: string): InputPlaceholder; /** Returns the OutputPlaceholder with the matching name. */ getOutput(name: string): OutputPlaceholder; /** Returns the end time of the scheduled MLComponent run. */ getScheduledEnd(): MachineLearning.FrameTiming; /** Returns the start time of the scheduled MLComponent run. */ getScheduledStart(): MachineLearning.FrameTiming; /** Returns true if running is requested on each frame. */ isRecurring(): boolean; /** Runs the MLComponent once. */ runImmediate(sync: boolean): void; /** Schedules the MLComponent to run at the start timing and terminate at the end timing. The scheduled running will recur if recurring is true. */ runScheduled( recurring: boolean, startTiming: MachineLearning.FrameTiming, endTiming: MachineLearning.FrameTiming, ): void; /** Stops running the MLComponent. */ stop(): void; /** If loading asynchronously, makes the entire system wait until loading is finished. */ waitOnLoading(): void; /** If running asynchronously, makes the entire system wait until the last run is finished. */ waitOnRunning(): void; } /** Used to track objects in the camera. Moves the local ScreenTransform to match the detected image. See the Object Tracking guide for more information. */ interface ObjectTracking extends Component { /** If true, child objects of this Component’s SceneObject will be disabled when the object is not being tracked. */ autoEnableWhenTracking: boolean; /** The index of the object being tracked. */ objectIndex: number; /** Function that gets called when the tracked object is found. */ onObjectFound: () => void; /** Function that gets called when the tracked object is lost. */ onObjectLost: () => void; /** Returns true if the object is currently being tracked on camera. */ isTracking(): boolean; /** Registers a callback to be executed when the passed in descriptor ends for this tracked object. */ registerDescriptorEnd(descriptor: string, callback: (descriptor: string) => void): void; /** Registers a callback to be executed when the passed in descriptor starts for this tracked object. */ registerDescriptorStart(descriptor: string, callback: (descriptor: string) => void): void; } /** Attaches the SceneObject to the mesh surface of a different SceneObject. See the Pin To Mesh guide for more information. */ interface PinToMeshComponent extends Component { /** The position offset to apply. */ offsetPosition: vec3; /** The euler angle offset to apply. Only has an effect when orientation is set to PositionAndDirection. */ offsetRotation: vec3; /** The orientation type to use. */ orientation: PinToMeshComponent.Orientation; /** The UV coordinates on the target mesh to attach to. */ pinUV: vec2; /** The preferred triangle index to attach to when multiple triangles contain the desired UV coordinate. */ preferredTriangle: number; /** Index of the UV coordinate set to use for pinning. */ preferredUVLayerIndex: number; /** The target mesh to attach to. */ target: BaseMeshVisual; /** If enabled, interpolated vertex normals will be used when calculating the attachment position. */ useInterpolatedVertexNormal: boolean; } /** Applies ScreenTransform positioning to match the cropped region of a texture. For more information, see the Crop Textures guide. */ interface RectangleSetter extends Component { /** Cropped texture to match the screen region of. Should be a texture using a RectCropTextureProvider, such as a Screen Crop Texture or Face Crop Texture. */ cropTexture: Asset.Texture; } /** Overrides the settings on a local ScreenTransform to fit a screen region on the device. See the Screen Transform guide for more information. */ interface ScreenRegionComponent extends Component { /** The region of the screen the local ScreenTransform will be fit to. */ region: ScreenRegionType; } /** * Used by AnimationMixer to animate a single object in the hierarchy. These are automatically added to SceneObjects when importing animated FBX files. See also: Playing 3D Animation Guide, * AnimationMixer, AnimationLayer. */ interface Animation extends Component { /** Returns the AnimationLayer under the name layerName. */ getAnimationLayerByName(layerName: string): Asset.AnimationLayer; /** Removes the AnimationLayer under the name layerName. */ removeAnimationLayerByName(layerName: string): void; /** Adds an AnimationLayer under the name layerName. */ setAnimationLayerByName(layerName: string, animationLayer: Asset.AnimationLayer): void; } /** Controls playback of animations on the attached SceneObject and its child objects. Please refer to the Playing 3D Animation Guide for setting up and playing animations. */ interface AnimationMixer extends Component { /** Whether this AnimationMixer is set to automatically play animations on start. */ autoplay: boolean; /** * A multiplying value for the speed of all animations being controlled by the AnimationMixer. For example, a value of 2.0 will double animation speed, while a value of 0.5 will cut the speed * in half. */ speedRatio: number; /** Makes a copy of the layer name and stores it as newName. */ cloneLayer(name: string, newName: string): AnimationMixerLayer; /** Adds a new AnimationMixerLayer to this AnimationMixer. */ createClip(name: string): AnimationMixerLayer; /** Returns a list of names of AnimationLayers in this AnimationMixer. */ getAnimationLayerNames(): string[]; /** Returns the AnimationMixerLayer with the name name. */ getLayer(name: string): AnimationMixerLayer; /** Returns a list of all AnimationMixerLayers controlled by the AnimationMixer. */ getLayers(): AnimationMixerLayer[]; /** Returns the current time ( seconds: in) of the layer named name. */ getLayerTime(name: string): number; /** Pauses animation layers named name, or all layers if name is empty. */ pause(name: string): void; /** Rebuild the animation hierarchy by finding all Animation components in the SceneObject and its children. */ resetAnimations(): void; /** Resumes any paused animation layer with name name, or all layers if name is empty. */ resume(name: string): void; /** * Starts playing animation layers named name, or all layers if name is empty. The animation will start with an offset of offset seconds. The animation will play cycles times, or loop forever * if cycles is -1. */ start(name: string, offset: number, cycles: number): void; /** * Starts playing animation layers named name, or all layers if name is empty. The animation will start with an offset of offset seconds. The animation will play cycles times, or loop forever * if cycles is -1. eventCallback will be called after any animation layer finishes playing. */ startWithCallback( name: string, offset: number, cycles: number, eventCallback: (name: string, animationMixer: AnimationMixer) => void, ): void; /** Stops any animation layer with name name, or all layers if name is empty. */ stop(name: string): void; } /** * Used to play audio in a Lens. You can assign an AudioTrackAsset to play through script or through the AudioComponent’s inspector in Lens Studio. See the Playing Audio guide for more * information. */ interface AudioComponent extends Component { /** The audio asset currently assigned to play. */ audioTrack: Asset.AudioTrackAsset; /** The length ( seconds: in) of the current sound assigned to play. */ duration: number; /** Length ( seconds: in) of a volume fade in applied to the beginning of sound playback. */ fadeInTime: number; /** Length ( seconds: in) of a volume fade out applied to the end of sound playback. */ fadeOutTime: number; /** The current playback time in seconds */ position: number; /** A volume multiplier for any sounds played by this AudioComponent. */ volume: number; /** Returns whether the sound is currently paused. */ isPaused(): boolean; /** Returns whether the AudioComponent is currently playing sound. */ isPlaying(): boolean; /** Pauses the sound. */ pause(): boolean; /** Plays the current sound loops number of times. If loops is -1, the sound will repeat forever. */ play(loops: number): void; /** Resumes a paused sound. */ resume(): boolean; /** Sets the callback function to be called whenever this sound stops playing. */ setOnFinish(eventCallback: (audioComponent: AudioComponent) => void): void; /** Stops the current sound if already playing. */ stop(fade: boolean): void; } /** Represents skinning data for rigged meshes. See also: MeshVisual. */ type Skin = Component; /** Represents transform data for screen-aligned 2D sprites. Use on SceneObjects with a SpriteVisual Component. See also: SpriteVisual. */ interface SpriteAligner extends Component { /** The location of the point this sprite is bound to. */ bindingPoint: vec2; /** The width and height of the SpriteVisual. */ size: vec2; } /** * Allows the MeshVisual provided to this component to handle touches on the screen (blocking Snapchat from receiving the touches), and optionally let certain touch types to pass through (let * Snapchat handle the touch). */ interface TouchComponent extends Component { /** Adds a MeshVisual as a target for touch detection. */ addMeshVisual(meshVisual: BaseMeshVisual): void; /** Adds a touch type that this component will ignore. */ addTouchBlockingException( exception: | 'TouchTypeNone' | 'TouchTypeTouch' | 'TouchTypeTap' | 'TouchTypeDoubleTap' | 'TouchTypeScale' | 'TouchTypePan' | 'TouchTypeSwipe', ): void; /** Returns the minimum bounding box size used for detecting touches. Value range is from 0-1, relative to screen width. */ getMinimumTouchSize(): number; /** Removes a MeshVisual as a target for touch detection. */ removeMeshVisual(meshVisual: BaseMeshVisual): void; /** Sets the camera that will be used for touch detection. */ setCamera(cameraValue: Camera): void; /** Sets the minimum bounding box size used for detecting touches. Value range is from 0-1, relative to screen width. */ setMinimumTouchSize(minimumSize: number): void; } /** Used to help control vertex animations on the SceneObject. */ interface VertexCache extends Component { /** The current time of vertex animations on this SceneObject. */ currentTime: number; /** The weight applied to vertex animations on this SceneObject. */ weight: number; } /** * Used to add an audio effect to a Lens. When present in the scene, it will automatically apply the selected audio effect to recordings made with the Lens. See the Audio Effect guide for more * information. */ type AudioEffectComponent = Component; /** Controls blend shapes connected to imported animation content. */ interface BlendShapes extends Component { /** If enabled, normal directions are also blended by blend shapes. */ blendNormals: boolean; /** Removes all blend shapes from the BlendShapesVisual. */ clearBlendShapes(): void; /** Returns the weight of blend shape name. */ getBlendShape(name: string): number; /** Returns whether this BlendShapesVisual has a blend shape named name. */ hasBlendShape(name: string): boolean; /** Sets the weight of blend shape name. */ setBlendShape(name: string, weight: number): void; /** Clears the blendshape with the matching name from the BlendShapes component. */ unsetBlendShape(name: string): void; } /** Used to track a landmarker in the camera. Moves the SceneObject’s transform to match the detected landmarker scene. See the Landmarker guide for more information. */ interface DeviceLocationTrackingComponent extends Component { /** Returns the in: distance, meters, to the location. If the distance is unavailable, -1 is returned. */ distanceToLocation: number; /** Returns the user’s current LocationProximityStatus. Useful for telling if a user is close enough to the location to track it. */ locationProximityStatus: LocationProximityStatus; /** A function that gets called when location data is downloaded. */ onLocationDataDownloaded: () => void; /** A function that gets called when location data fails to download. */ onLocationDataDownloadFailed: () => void; /** A function that gets called when location is found. */ onLocationFound: () => void; /** A function that gets called when location is lost. Note this will also happen when the user flips the camera. */ onLocationLost: () => void; /** Returns whether the location landmarker is currently being tracked. */ isTracking(): boolean; } /** * Moves or rotates the SceneObject to match device orientation. * * If using “Surface” tracking mode, adding this to a SceneObject enables surface * tracking for the scene, and moves the object to a position and rotation that * matches the physical camera’s pose in the world. Surface tracking can also be * enhanced with native AR by enabling the “Use Native AR” option in the * Inspector panel, or through script by setting the component’s * surfaceOptions.enhanceWithNativeAR property. * * If using “Rotation” tracking mode, adding this to a SceneObject will apply the * device’s real world rotation to the object. * * If using “World” tracking mode, adding this to a SceneObject enables native AR * tracking for the scene, and moves the object to a position and rotation that * matches the physical camera’s pose in the world. * * See the Tracking Modes guide for more information. * * Note: This component was named “WorldTracking” in previous versions of Lens * Studio. */ interface DeviceTracking extends Component { /** Used to access rotation tracking settings. */ rotationOptions: RotationOptions; /** Used to access surface tracking settings. */ surfaceOptions: SurfaceOptions; /** Helps to improve surface tracking accuracy while the target SceneObject is being moved. */ surfaceTrackingTarget: SceneObject; /** Returns the WorldOptions object of this component, which can be used to control World Tracking settings. */ worldOptions: WorldOptions; /** Returns the World Tracking Capabilities of the current device. */ worldTrackingCapabilities: WorldTrackingCapabilities; /** Calculates a histogram of world mesh surfaces within a sphere at the given world position and radius. Only available when world mesh tracking is supported and enabled. */ calculateWorldMeshHistogram(center: vec3, radius: number): TrackedMeshHistogramResult; /** Returns the actual DeviceTrackingMode being used. This may be different from the requested DeviceTrackingMode. */ getActualDeviceTrackingMode(): DeviceTrackingMode; /** * Returns an array of BasicTransform objects describing each point that the camera travels through. Each item in the array matches the camera’s basic transform in the corresponding frame of * the video feed that the Lens is applied to. Only available in some cases, such as in Lenses for Spectacles 3. When not available, it will return an empty array. See the Lenses * for Spectacles guide for more information. */ getDevicePath(): BasicTransform[]; /** * Returns the current frame index of the video feed that the Lens is being applied to. This can be used as an index to access the current BasicTransform in getDevicePath(). Only available in * some cases, such as in Lenses for Spectacles 3. When not available, it will return -1. See the Lenses for Spectacles guide for more information. */ getDevicePathIndex(): number; /** Returns the DeviceTrackingMode currently requested to be used. This may be different from the actual DeviceTrackingMode being used. */ getRequestedDeviceTrackingMode(): DeviceTrackingMode; /** Returns an array of TrackedMeshHitTestResult that intersect with a ray cast from screen position screenPos. Only available when world mesh tracking is supported and enabled. */ hitTestWorldMesh(screenPos: vec2): TrackedMeshHitTestResult[]; /** Returns whether the DeviceTrackingMode is supported. */ isDeviceTrackingModeSupported(mode: DeviceTrackingMode): boolean; /** * Returns an array of TrackedMeshHitTestResult that intersect with a ray cast from the world position from and continuing through the world position to. Only available when world mesh * tracking is supported and enabled. */ raycastWorldMesh(from: vec3, to: vec3): TrackedMeshHitTestResult[]; /** Requests that a DeviceTrackingMode be used. This requested change may not happen immediately. */ requestDeviceTrackingMode(val: DeviceTrackingMode): void; /** * Resets the World Tracking origin to the point on the surface plane aligned with the screen position position. Screen positions are represented in the range ([0-1], [0-1]), (0,0) being the * top-left of the screen and (1,1) being the bottom-right. */ resetTracking(position: vec2): void; /** * Offsets the default position of the World Tracking surface origin by offset. Avoid using a y value of zero in offset, because it may cause problems with tracking. If used outside of * Initialized or TurnOnEvent, you will need to call resetTracking() to apply the offset. Note: calling resetTracking() will overwrite the x and z components of the offset. */ setWorldOriginOffset(offset: vec3): void; } /** * @deprecated * This class has been Deprecated. Please instead use the DeviceTracking component with Tracking Mode set to Rotation. See the Tracking Modes guide for more information. Applies the device’s * gyroscope rotation to the SceneObject it is attached to. */ type Gyroscope = Component; /** Binds the SceneObject to a tracked face. See the Head Attached 3D Objects Guide for more information. */ interface Head extends Component { /** The index of the face this head is attached to. */ faceIndex: number; /** Returns the total number of faces currently being tracked. */ getFacesCount(): number; /** Returns the screen position of the face landmark at the passed in index. */ getLandmark(index: number): vec2; /** Returns the number of face landmarks being tracked. */ getLandmarkCount(): number; /** Returns a list of screen positions of all tracked landmarks. */ getLandmarks(): vec2[]; /** Changes the attachment point type used to anchor this object to a face. */ setAttachmentPointType(attachmentPointType: AttachmentPointType): void; } /** Used to show and hide hints to the user. For more information and useful helper scripts, see the Scripting Hints Guide. */ interface HintsComponent extends Component { /** Hides the hint with id hintID. */ hideHint(hintID: Parameters<HintsComponent['showHint']>[0]): boolean; /** Shows the hint with id hintID for a duration of duration seconds. Use a duration of -1 to keep the hint onscreen forever. */ showHint( hintID: `lens_hint_${ | 'blow_a_kiss' | 'come_closer' | `do_not_${'smile' | 'try_with_a_friend'}` | 'find_face' | 'keep_raising_your_eyebrows' | 'kiss' | 'kiss_again' | `look_${'around' | 'down' | 'left' | 'right' | 'up'}` | 'make_some_noise' | 'nod_your_head' | `now_${'kiss' | 'open_your_mouth' | 'raise_your_eyebrows' | 'smile'}` | `open_your_${'mouth' | 'mouth_again'}` | `raise_${'eyebrows_or_open_mouth' | 'your_eyebrows' | 'your_eyebrows_again'}` | 'smile' | 'smile_again' | 'swap_camera' | 'tap' | `tap_${'a_surface' | 'ground' | 'ground_to_place' | 'surface_to_place'}` | `try_${'friend' | 'rear_camera'}` | 'turn_around' | 'walk_through_the_door'}`, time: number, ): boolean; } /** Acts as a source of light in the scene. See the Light and Shadows guide for more information about lighting. */ interface LightSource extends Component { /** If enabled, the LightSource will be automatically positioned based on its orientation relative to any shadow casting meshes in the scene. */ autoLightSourcePosition: boolean; /** If enabled, shadowFrustumSize will be automatically updated based on its orientation relative to any shadow casting meshes in the scene. */ autoShadowFrustumSize: boolean; /** If enabled, the LightSource will be able to cast shadows. */ castsShadows: boolean; /** The color of the light. */ color: vec3; /** A color image applied to an imaginary skybox the LightSource will use for color information. */ diffuseEnvmapTexture: Asset.Texture; /** A value used to increase the intensity of light information derived from the diffuseEnvmapTexture exponentially. */ envmapExposure: number; /** Controls the amount of rotation applied to the diffuseEnvmapTexture. */ envmapRotation: number; /** The strength of the light on a scale of 0.0 – 1.0. */ intensity: number; /** The set of layers this LightSource will affect. */ renderLayer: LayerSet; /** Controls the blurring size used when casting shadows from this LightSource. */ shadowBlurRadius: number; /** Controls the color used when casting shadows from this LightSource. */ shadowColor: vec4; /** The lightness and darkness value of the shadow cast by objects from this light source. */ shadowDensity: number; /** The maximum distance at which shadows will be calculated for this LightSource. */ shadowFrustumFarClipPlane: number; /** The minimum distance at which shadows will be calculated for this LightSource. */ shadowFrustumNearClipPlane: number; /** The simulated distance of the light source from objects to calculate the softness of the shadow. */ shadowFrustumSize: number; /** A color image applied to an imaginary skybox the light source will use for specular and reflection information. */ specularEnvmapTexture: Asset.Texture; /** Enable if you would like the LightSource to use information from the diffuseEnvmapTexture for light color information. */ useEnvmap: boolean; } /** Every frame, LookAtComponent rotates its SceneObject to face towards a target SceneObject. */ interface LookAtComponent extends Component { /** * The “aim” and “up” vectors used when determining rotation. LookAtComponent will try to point the Aim axis of the SceneObject towards the target, while keeping the Up axis of the * SceneObject pointing towards worldUpVector. */ aimVectors: LookAtComponent.AimVectors; /** Controls the method of rotation being used. */ lookAtMode: LookAtComponent.LookAtMode; /** Adds an additional rotation offset. */ offsetRotation: quat; /** The SceneObject this LookAtComponent targets. */ target: SceneObject; /** The vector to be considered the “up” vector when determining rotation. */ worldUpVector: LookAtComponent.WorldUpVector; } /** * Handles input information from user touch input via the TouchComponent to control Scale, Rotation, and Translation of objects. * ``` * // Disables the scale functionality on a manipulate component when a user taps * //@input Component.ManipulateComponent manip * * function onTap(eventData) * { * script.manip.enableManipulateType(ManipulateType.Scale, false); * } * var tapEvent = script.createEvent("TapEvent"); * tapEvent.bind(onTap); * ``` */ interface ManipulateComponent extends Component { /** Changes swivel behavior based on the object’s height relative to the camera. */ isContextualSwivel: boolean; /** The maximum distance the object can travel from the user. */ maxDistance: number; /** The maximum height of the object. */ maxHeight: number; /** The maximum size the object can scale to. */ maxScale: number; /** The minimum distance the object can be from the user. */ minDistance: number; /** The minimum height of the object. */ minHeight: number; /** The minimum size the object can shrink to. */ minScale: number; /** Multiplier for swivel rotation speed. For example, a value of 0.5 will cut rotation speed in half, and a value of 2.0 will double rotation speed. */ rotationScale: number; /** Repositions the object to be within the bounds of minDistance, maxDistance. */ clampWorldPosition(): void; /** Enables or disables the specified ManipulateType for this ManipulateComponent. */ enableManipulateType(type: ManipulateType, enable: boolean): void; /** * Checks for an intersection point between the manipulation plane and a line extending from the camera through the specified screen space point. The screen point is passed in as (x, y) with * both values ranging from ([0-1], [0-1]), (0,0) being left-top and (1,1) being right-bottom. The result is returned as a ManipulateFrameIntersectResult object. */ intersectManipulateFrame(screenSpacePoint: vec2): ManipulateFrameIntersectResult; /** Returns whether the specified ManipulateType is enabled for this ManipulateComponent. */ isManipulateTypeEnabled(type: ManipulateType): boolean; } /** * Used to track images in the camera. Moves the containing object’s transform to match the detected image. For more information, see the Marker Tracking guide. * ``` * //@input Component.MarkerTrackingComponent markerTrackingComponent * * // Get whether or not the marker image is being tracked * var isMarkerTracking = markerTrackingComponent.isTracking(); * * // Print current status. * if (isMarkerTracking) { * print("Image is in Camera feed."); * } else { * print("Image is NOT in Camera feed."); * } * ``` */ interface MarkerTrackingComponent extends Component { /** If true, child objects of this Component’s SceneObject will be disabled when the marker image is not being tracked. */ autoEnableWhenTracking: boolean; /** The marker asset describing the tracking target. */ marker: Asset.MarkerAsset; /** A function that gets called when marker tracking begins. */ onMarkerFound: () => void; /** A function that gets called when marker tracking is lost. */ onMarkerLost: () => void; /** Returns whether the marker image is currently being tracked in camera. */ isTracking(): boolean; } /** * Binds scripts to Events and executes them when triggered. Any script can access the ScriptComponent executing them through the variable script. See also: Scripting Overview, Script Events * Guide. Lens Studio v1.0.0+ * * Instead of doing the following: * ``` * const typedScript = script as Component.ScriptComponent<{ anInput: number }, { anApiProp: 'some' | 'thing' }> * ``` * Use the following to type your script's inputs and/or api properties by extending the interfaces of `ScriptInputs` and/or `ScriptApi`: * ``` * declare namespace SnapchatLensStudio { * interface ScriptApi { * some?: 'thing' | 'other-thing' * } * } * ``` */ type ScriptComponent< Inputs extends object = SnapchatLensStudio.ScriptInputs, Api extends object = SnapchatLensStudio.ScriptApi > = { /** Adds a new SceneEvent, triggered by eventType events, to the ScriptComponent. */ createEvent<T extends keyof EventMapping>(eventType: T): EventMapping[T]; /** Removes a previously added SceneEvent from the ScriptComponent. */ removeEvent(event: SceneEvent): void; /** Generic object accessible by other instances of ScriptComponent. Use this object to store references to properties and methods that need to be accessible from other ScriptComponents. */ api: Api; } & Component & Inputs; } /** * Controls animation playback for a single animation layer. See also: AnimationMixer. */ interface AnimationMixerLayer extends ScriptObject { /** The name of the animation layer being used for this animation. */ animationLayerName: string; /** The number of times this animation will play. If -1, the animation will loop forever. */ cycles: number; /** If true, the animation will stop having an effect. */ disabled: boolean; /** The framerate (frames per second) of the animation. */ fps: number; /** The starting point for this animation clip. If rangeType is set to Time, this is the point to start at in seconds. If rangeType is set to Frames, this is the frame number to start at. */ from: number; /** The name of the AnimationMixerLayer. */ name: string; /** * Defines the animation’s looping behavior. If set to AnimationClip.PostInfinity.Cycle, the animation will restart from the beginning each time it loops. If set to AnimationClip.PostInfinity. * Oscillate, the animation will switch between normal and reverse playback each time it loops. This is set to Cycle by default. */ postInfinity: AnimationClip.PostInfinity; /** * The range type used for defining the animation clip. If set to AnimationClip.RangeType.Time, to and from represent times in seconds. If set to AnimationClip.RangeType.Frames, to and from * represent frame numbers. */ rangeType: AnimationClip.RangeType; /** If true, the animation will play play in reverse. */ reversed: boolean; /** A multiplying value for the speed of this animation. For example, a value of 2.0 will double animation speed, while a value of 0.5 will cut the speed in half. */ speedRatio: number; /** The ending point for this animation clip. If rangeType is set to Time, this is the point to end at in seconds. If rangeType is set to Frames, this is the frame number to end at. */ to: number; /** The weight of this animation layer. Range is from [0-1], 0 being no animation strength and 1 being full animation strength. */ weight: number; /** Returns a copy of this AnimationMixerLayer, with the name changed to newName. */ clone(newName: string): AnimationMixerLayer; /** Returns the length of the animation in seconds. */ getDuration(): number; /** Returns the current playback position of the animation in seconds. */ getTime(): number; /** Returns whether the animation is currently playing. */ isPlaying(): boolean; /** Pauses the animation. */ pause(): void; /** Resumes the animation if it has been paused. */ resume(): void; /** Starts playing the animation with an offset of offsetArg seconds. The animation will play cycles times, or loop forever if cycles is -1. */ start(offset: number, cycles: number): void; /** Starts the animation with an offset of offsetArg seconds. The animation will play cycles times, or loop forever if cycles is -1. eventCallback will be called after the animation finishes. */ startWithCallback( offset: number, cycles: number, eventCallback: (name: string, animationMixer: Component.AnimationMixer) => void, ): void; /** Stops the animation from playing and jumps to the animation’s end. */ stop(): void; } declare namespace AnimationClip { /** * Used by AnimationMixerLayer for setting animation looping behavior. * ``` * // Set an AnimationMixerLayer to oscillate when looping * //@input Component.AnimationMixer mixer * * var layer = script.mixer.getLayers()[0]; * layer.postInfinity = AnimationClip.PostInfinity.Oscillate; * ``` */ enum PostInfinity { /** The animation will restart from the beginning each time it loops. */ Cycle, /** The animation will switch between normal and reverse playback each time it loops. */ Oscillate, } /** * Used by AnimationMixerLayer for setting animation clip range type. * ``` * // Set an AnimationMixerLayer's range using start and end time * //@input Component.AnimationMixer mixer * * var layer = script.mixer.getLayers()[0]; * layer.rangeType = AnimationClip.RangeType.Time; * layer.from = 1.0; * layer.to = 2.0; * ``` */ enum RangeType { /** Range is specified by start and end time, in seconds */ Time, /** Range is specified by start and end frame numbers */ Frames, } } /** Types of screen regions that can be used with ScreenRegionComponent. */ declare enum ScreenRegionType { /** The entire screen area of the device. */ FullFrame, /** The screen area shown to the user when recording. On some devices, this region is a subset of FullFrame region. */ Capture, /** The screen area shown to the user when previewing a Snap. On some devices, this region is a subset of Capture region. */ Preview, /** A screen area that will be visible on all devices and won’t overlap Snapchat UI. Safe area to place any UI elements. */ SafeRender, /** The screen area where the round “Snap” button is drawn. */ RoundButton, } /** Used by DeviceLocationTrackingComponent to indicate the user’s distance from the landmarker location. See the Landmarker guide for more information. */ declare enum LocationProximityStatus { /** User’s distance cannot be determined or has not been determined yet. */ Unknown, /** User is close enough to the landmarker location to begin tracking. */ WithinRange, /** User is too far away from the landmarker location to track it. */ OutOfRange, } /** Namespace for Machine Learning related classes and methods. For more information, see the Machine Learning Overview. */ declare namespace MachineLearning { /** Creates a new InputBuilder object. */ function createInputBuilder(): InputBuilder; /** Creates a new OutputBuilder object. */ function createOutputBuilder(): OutputBuilder; /** Creates a new TransformerBuilder object. */ function createTransformerBuilder(): TransformerBuilder; /** Inference modes used by MLComponent.inferenceMode. Each mode describes how the neural network will be run. */ enum InferenceMode { /** MLComponent will run the neural network on CPU. Available on all devices. */ CPU, /** MLComponent will attempt to run the neural network on GPU. If the device doesn’t support it, CPU mode will be used instead. */ GPU, /** MLComponent will attempt to use a dedicated hardware accelerator to run the neural network. If the device doesn’t support it, GPU mode will be used instead. */ Accelerator, /** MLComponent will automatically decide how to run the neural network based on what is supported. It will start with Accelerator, then fall back to GPU, then CPU. */ Auto, } /** Describes the current state of the MLComponent model. For more information, see the MLComponent Scripting guide. */ enum ModelState { /** Model is running */ Running, /** Model is loading */ Loading, /** Model is built and ready to run */ Idle, /** Model is not ready to run */ NotReady, } /** Timing options for when MLComponent should start or stop running. Used with MLComponent.runScheduled(). For more information, see the MLComponent Scripting guide. */ enum FrameTiming { /** Only valid as an end timing. There is no exact time specified when MLComponent should finish its run. */ None, /** Run during MLComponent update, before script update. */ Update, /** Run in MLComponent LateUpdate, after all scripts update, but before they get LateUpdate. */ LateUpdate, /** Run at a specific point during frame rendering. */ OnRender, } /** * Types of output used by OutputPlaceholder. * ``` * //@input Component.MLComponent mlComponent * //@input string outputName * //@input Component.Image outputImage * * script.mlComponent.onLoadingFinished = onLoadingFinished; * * function onLoadingFinished() { * var output = script.mlComponent.getOutput(script.outputName); * if (output.mode == MachineLearning.OutputMode.Data) { * var outputData = output.data; * for (var i = 0; i < outputData.length; i++) { * print(outputData[i]); * } * } else { * var texture = output.texture; * script.outputImage.mainPass.baseTex = texture; * } * } * //@input vec2 outputSize = {1, 1} * //@input string outputName = "probs" * * var outputChannels = 200; * * var outputBuilder = MachineLearning.createOutputBuilder(); * outputBuilder.setName(script.outputName); * outputBuilder.setShape(new vec3(script.outputSize.x, script.outputSize.y, outputChannels)); * outputBuilder.setOutputMode(MachineLearning.OutputMode.Data); * var outputPlaceholder = outputBuilder.build(); * ``` */ enum OutputMode { /** The output will be in the form of a Texture. */ Texture, /** The output will be in the form of a Float32Array. */ Data, } } /** Builds InputPlaceHolders for MLComponent. */ interface InputBuilder extends ScriptObject { /** Builds and returns a new InputPlaceholder. */ build(): InputPlaceholder; /** Sets the input texture of the InputPlaceholder to be built. */ setInputTexture(texture: Asset.Texture): InputBuilder; /** Sets the name of the InputPlaceholder to be built. */ setName(name: string): InputBuilder; /** Sets the shape of the InputPlaceholder to be built. */ setShape(shape: vec3): InputBuilder; /** Sets the Transformer of the InputPlaceholder to be built. */ setTransformer(transformer: Transformer): InputBuilder; } /** Builds OutputPlaceholders for MLComponent. */ interface OutputBuilder extends ScriptObject { /** Builds and returns a new OutputPlaceholder. */ build(): OutputPlaceholder; /** Sets the name of the OutputPlaceholder to be built. */ setName(name: string): OutputBuilder; /** Sets the OutputMode of the OutputPlaceholder to be built. */ setOutputMode(outputMode: MachineLearning.OutputMode): OutputBuilder; /** Sets the shape of the OutputPlaceholder to be built. */ setShape(shape: vec3): OutputBuilder; /** Sets the Transformer of the OutputPlaceholder to be built. */ setTransformer(transformer: Transformer): OutputBuilder; } /** Builds Transformer objects for MLComponent. */ interface TransformerBuilder extends ScriptObject { /** Builds and returns a Transformer object based on the current settings. */ build(): Transformer; /** Sets the fill value used. */ setFillColor(color: vec4): TransformerBuilder; /** Enables or disables horizontal flipping. */ setFlipX(value: boolean): TransformerBuilder; /** Enables or disables vertical flipping. */ setFlipY(value: boolean): TransformerBuilder; /** Sets the horizontal alignment type used. */ setHorizontalAlignment(mode: HorizontalAlignment): TransformerBuilder; /** Sets the rotation type used. */ setRotation(mode: TransformerRotation): TransformerBuilder; /** Sets the stretching type used. */ setStretch(value: boolean): TransformerBuilder; /** Sets the vertical alignment type used. */ setVerticalAlignment(mode: VerticalAlignment): TransformerBuilder; } /** Rotation types used by TransformBuilder. */ declare enum TransformerRotation { /** No rotation */ None, /** Rotates by 90 degrees */ Rotate90, /** Rotates by 180 degrees */ Rotate180, /** Rotates by 270 degrees */ Rotate270, } /** Applies additional transform processing on data for InputPlaceholders and OutputPlaceholders used with MLComponent. For more information, see the MLComponent Overview. */ interface Transformer extends ScriptObject { /** Inverse transformation matrix of this Transformer. */ inverseMatrix: mat3; /** Transformation matrix of this Transformer. */ matrix: mat3; } /** Base class for Input and Output Placeholders used by MLComponent. */ interface BasePlaceholder extends ScriptObject { /** The name of the Placeholder. */ name: string; /** The shape of the Placeholder’s data. */ shape: vec3; /** Transformer object for applying transformations on the PlaceHolder’s data. */ transformer: Transformer; } /** Provides output data from the neural network used by an MLComponent. For more information, see the MLComponent Scripting guide. */ interface OutputPlaceholder extends BasePlaceholder { /** Output as a Float32Array. Usable when mode is set to MachineLearning.OutputMode.Data. */ data: Float32Array; /** Which type of data the output is provided as. For example, Texture or Data. */ mode: MachineLearning.OutputMode; /** Output as a Texture. Usable when mode is set to MachineLearning.OutputMode.Texture. */ texture: Asset.Texture; } /** Controls input data for a neural network used by an MLComponent. For more information, see the MLComponent Scripting guide. */ interface InputPlaceholder extends BasePlaceholder { /** Data used as input. */ data: Float32Array; /** Texture used as input. */ texture: Asset.Texture; } /** Provides histogram information about tracked world mesh faces in a given area. Returned by DeviceTracking.calculateWorldMeshHistogram(). Lens Studio v3.2+ */ interface TrackedMeshHistogramResult extends ScriptObject { /** Average normal direction, in world space, of the mesh faces. */ avgNormal: vec3; /** * Array of relative proportions for each classification, in the order described below. The values all add up to a total of 1.0. The classification value order is: * 0: None * 1: Wall * 2: Floor * * 3: Ceiling * 4: Table * 5: Seat * 6: Window * 7: Door */ histogram: number[]; } /** Used with DeviceTracking.rotationOptions to change settings for Rotation tracking mode. */ interface RotationOptions extends ScriptObject { /** If enabled, rotation will be inverted. */ invertRotation: boolean; } /** Used with DeviceTracking.surfaceOptions to change settings for Surface tracking mode. */ interface SurfaceOptions extends ScriptObject { /** If enabled, surface tracking will be improved using native AR tracking. */ enhanceWithNativeAR: boolean; } /** Holds settings for world mesh tracking in DeviceTracking component. Accessible through DeviceTracking.worldOptions. */ interface WorldOptions extends ScriptObject { /** Enables or disables world mesh classification gathering. */ enableWorldMeshesClassificationTracking: boolean; /** Enables or disables the generation of world meshes. */ enableWorldMeshesTracking: boolean; } /** Provides information about whether certain world tracking features are supported by the device. */ interface WorldTrackingCapabilities extends ScriptObject { /** Returns true if the device supports scene reconstruction. */ sceneReconstructionSupported: boolean; } /** Provides information about a TrackedMesh surface hit during a raycast. Is returned in an array when calling DeviceTracking.hitTestWorldMesh() or DeviceTracking.raycastWorldMesh(). */ interface TrackedMeshHitTestResult extends ScriptObject { /** Returns the classification of the mesh face at the intersection point. The classification values are: * 0: None * 1: Wall * 2: Floor * 3: Ceiling * 4: Table * 5: Seat * 6: Window * 7: Door */ classification: number; /** Returns the TrackedMesh that was hit. */ mesh: TrackedMesh; /** Returns the world space normal direction of the intersection point. */ normal: vec3; /** Returns the world space position of the intersection point. */ position: vec3; } /** Provides basic information about a transformation. See also: DeviceTracking */ interface BasicTransform extends ScriptObject { /** Returns the inverted world matrix of the BasicTransform. */ getInvertedMatrix(): mat4; /** Returns the world matrix of the BasicTransform. */ getMatrix(): mat4; /** Returns the world position of the BasicTransform. */ getPosition(): vec3; /** Returns the world rotation of the BasicTransform. */ getRotation(): quat; /** Returns the world scale of the BasicTransform. */ getScale(): vec3; } declare namespace Camera { /** Used in Camera’s depthBufferMode property. Each mode is suited for handling objects at a certain distance range. For more information on depth modes, see the Camera and Layers guide. */ enum DepthBufferMode { /** Gives higher depth precision on nearby objects, so is better suited for scenes near to the camera. */ Regular, /** Gives higher depth precision on far away objects, so is better suited for scenes far away from the camera. */ Logarithmic, } /** Used in Camera’s devicePropertyUsage property. Specifies which camera properties should be overridden by device properties. */ enum DeviceProperty { /** No Camera properties are overridden with device properties. */ None, /** Overrides the Camera’s aspect property to use the device’s aspect ratio instead. */ Aspect, /** Overrides the Camera’s fov property to use the device’s field of view instead. */ Fov, /** Overrides both aspect and fov with the device’s properties. */ All, } /** Returned from Camera’s type property. */ enum Type { /** Simulates how perspective and depth perception work in the real world. Useful for rendering objects in 3D space. */ Perspective, /** Does not simulate perspective distortion. Useful for 2D effects like Images and Text. */ Orthographic, } } declare namespace PinToMeshComponent { enum Orientation { /** Pins only the position. Rotation is independent from the target mesh. */ OnlyPosition, /** Pins both the position and direction. The normal of the target mesh is the Y axis. The U texture coordinate of the target mesh’s UV is the X axis. */ PositionAndDirection, } } declare namespace LookAtComponent { /** * The “aim” and “up” vectors used with LookAtComponent when determining rotation. LookAtComponent will try to point the Aim axis of the SceneObject towards the target, while keeping the Up axis * of the SceneObject pointing towards worldUpVector. */ enum AimVectors { /** X Aim, Y Up */ XAimYUp, /** X Aim, Z Up */ XAimZUp, /** Y Aim, X Up */ YAimXUp, /** Y Aim, Z Up */ YAimZUp, /** Z Aim, X Up */ ZAimXUp, /** Z Aim, Y Up */ ZAimYUp, /** X Aim, -Y Up */ XAimNegativeYUp, /** X Aim, -Z Up */ XAimNegativeZUp, /** Y Aim, -X Up */ YAimNegativeXUp, /** Y Aim, -Z Up */ YAimNegativeZUp, /** Z Aim, -X Up */ ZAimNegativeXUp, /** Z Aim, -Y Up */ ZAimNegativeYUp, /** -X Aim, Y Up */ NegativeXAimYUp, /** -X Aim, Z Up */ NegativeXAimZUp, /** -Y Aim, X Up */ NegativeYAimXUp, /** -Y Aim, Z Up */ NegativeYAimZUp, /** -Z Aim, X Up */ NegativeZAimXUp, /** -Z Aim, Y Up */ NegativeZAimYUp, /** -X Aim, -Y Up */ NegativeXAimNegativeYUp, /** -X Aim, -Z Up */ NegativeXAimNegativeZUp, /** -Y Aim, -X Up */ NegativeYAimNegativeXUp, /** -Y Aim, -Z Up */ NegativeYAimNegativeZUp, /** -Z Aim, -X Up */ NegativeZAimNegativeXUp, /** -Z Aim, -Y Up */ NegativeZAimNegativeYUp, } /** * Modes used in LookAtComponent.lookAtMode to determine the rotation method being used. * ``` * // @input Component.LookAtComponent lookAt * * script.lookAt.lookAtMode = LookAtComponent.LookAtMode.LookAtPoint; * script.lookAt.target = script.getSceneObject(); * ``` */ enum LookAtMode { /** Rotation is based on the target object’s position */ LookAtPoint, /** Rotation is based on the target object’s rotation */ LookAtDirection, } /** * Used with LookAtComponent to set the “up” vector when determining rotation. * ``` * // Set the LookAtComponent's WorldUpVector to SceneY * // @input Component.LookAtComponent lookAtComponent * script.lookAtComponent.worldUpVector = LookAtComponent.WorldUpVector.SceneY; * ``` */ enum WorldUpVector { /** Scene’s X vector */ SceneX, /** Scene’s Y vector */ SceneY, /** Scene’s Z vector */ SceneZ, /** Target object’s X vector */ TargetX, /** Target object’s Y vector */ TargetY, /** Target object’s Z vector */ TargetZ, /** Current object’s X vector */ ObjectX, /** Current object’s Y vector */ ObjectY, /** Current object’s Z vector */ ObjectZ, } } /** Represents the Lens scene. Accessible through global.scene. */ interface ScriptScene extends ScriptObject { /** Creates a new Render Target texture with a RenderTargetProvider as its control property. */ createRenderTargetTexture(): Asset.Texture; /** Adds a new SceneObject named name to the scene. */ createSceneObject(name: string): SceneObject; /** * Returns a string describing the currently active device camera. Returns “back” if the rear-facing ( World: aka) camera is active. Returns “front” if the front-facing ( Selfie: aka) camera is * active. Otherwise, the camera is not initialized. */ getCameraType(): string; /** Returns the root SceneObject at index index in the current scene. */ getRootObject(index: number): SceneObject; /** Returns the number of SceneObjects in the current scene. */ getRootObjectsCount(): number; /** Returns whether or not the scene is currently being recorded. */ isRecording(): boolean; } /** * Low-level data class. */ interface SerializableWithUID extends ScriptObject { /** Returns true if this object is the same as other. Useful for checking if two references point to the same thing. */ isSame(other: SerializableWithUID): boolean; } /** An object in the scene hierarchy, containing a Transform and possibly Components. A script can access the SceneObject holding it through the method script.getSceneObject(). */ interface SceneObject extends SerializableWithUID { /** Whether the SceneObject, including its components and children, is enabled or disabled. */ enabled: boolean; /** Gets or sets the LayerSet of layers this SceneObject belongs to. This is used to determine which Cameras will render the SceneObject. */ layer: LayerSet; /** The name of the SceneObject. */ name: string; /** Copies component and adds it to the SceneObject, then returns it. */ copyComponent(component: Component): Component; /** Creates a shallow copy of the passed in sceneObject (not including its hierarchy), and parents it to this SceneObject. */ copySceneObject(sceneObject: SceneObject): SceneObject; /** Creates a deep copy of the passed in sceneObject (including its hierarchy), and parents it to this SceneObject. */ copyWholeHierarchy(sceneObject: SceneObject): SceneObject; /** Adds a new component of type typeName to the SceneObject. */ createComponent(typeName: string): Component; /** Destroys the SceneObject. */ destroy(): void; /** Returns this SceneObject’s child at index index. */ getChild(index: number): SceneObject; /** Returns the number of children the SceneObject has. */ getChildrenCount(): number; /** Returns the first attached Component with type matching or deriving from componentType. */ getComponent<T extends keyof SnapchatLensStudio.ComponentMapping>( componentType: T, ): SnapchatLensStudio.ComponentMapping[T]; /** Returns the first attached Component with type matching or deriving from componentType. */ getComponent(componentType: string): Component; /** Returns a list of attached components with types matching or deriving from componentType. */ getComponents<T extends keyof SnapchatLensStudio.ComponentMapping>( componentType: T, ): Array<SnapchatLensStudio.ComponentMapping[T]>; /** Returns a list of attached components with types matching or deriving from componentType. */ getComponents(componentType: string): Component[]; /** Returns the SceneObject’s parent in the hierarchy, or null if there isn’t one. */ getParent(): SceneObject; /** Returns the Transform attached to the SceneObject. */ getTransform(): Transform; /** Returns whether the SceneObject has a parent in the scene hierarchy. */ hasParent(): boolean; /** Unparents the SceneObject in the hierarchy, making it an orphan. */ removeParent(): void; /** Sets the SceneObject’s parent to newParent in the scene hierarchy. */ setParent(newParent: SceneObject): void; /** Changes the parent of the SceneObject without altering its world position, rotation, or scale. */ setParentPreserveWorldTransform(newParent: SceneObject): void; } /** Used to describe a set of layers that an object belongs to or interacts with. See SceneObject’s layer property, Camera’s renderLayer property, and LightSource’s renderLayer property. */ interface LayerSet { /** Returns true if all layers in the other LayerSet are also present in this one. */ contains(other: LayerSet): boolean; /** Returns a new LayerSet that contains layers present in this LayerSet but not present in other. */ except(other: LayerSet): LayerSet; /** Returns a new LayerSet that only contains layers present in both this LayerSet and other. */ intersect(other: LayerSet): LayerSet; /** Returns true if this LayerSet contains no layers. */ isEmpty(): boolean; /** Returns a string representation of this LayerSet. */ toString(): string; /** Returns a new LayerSet combining this LayerSet and other. */ union(other: LayerSet): LayerSet; } declare namespace LayerSet { /** Returns a new LayerSet based on the passed in number. */ function fromNumber(layers: number): LayerSet; } /** * Controls the position, rotation, and scale of a SceneObject. Every SceneObject automatically has a Transform attached. * Lens Studio v1.0.0+ */ interface Transform extends ScriptObject { /** Returns the Transform’s back directional vector. */ back: vec3; /** Returns the Transform’s down directional vector. */ down: vec3; /** Returns the Transform’s forward directional vector. */ forward: vec3; /** Returns the Transform’s left directional vector. */ left: vec3; /** Returns the Transform’s right directional vector. */ right: vec3; /** Returns the Transform’s up directional vector. */ up: vec3; /** Returns the Transform’s world-to-local transformation matrix. */ getInvertedWorldTransform(): mat4; /** Returns the Transform’s position relative to its parent. */ getLocalPosition(): vec3; /** Returns the Transform’s rotation relative to its parent. */ getLocalRotation(): quat; /** Returns the Transform’s scale relative to its parent. */ getLocalScale(): vec3; /** Returns the SceneObject the Transform is attached to. */ getSceneObject(): SceneObject; /** Returns the Transform’s position relative to the world. */ getWorldPosition(): vec3; /** Returns the Transform’s rotation relative to the world. */ getWorldRotation(): quat; /** Returns the Transform’s scale relative to the world. */ getWorldScale(): vec3; /** Returns the Transform’s local-to-world transformation matrix. */ getWorldTransform(): mat4; /** Sets the Transform’s position relative to its parent. */ setLocalPosition(pos: vec3): void; /** Sets the Transform’s rotation relative to its parent. */ setLocalRotation(rotation: quat): void; /** Sets the Transform’s scale relative to its parent. */ setLocalScale(scale: vec3): void; /** Sets the Transform’s position relative to the world. */ setWorldPosition(pos: vec3): void; /** Sets the Transform’s rotation relative to the world. */ setWorldRotation(rotation: quat): void; /** Sets the Transform’s scale relative to the world. This may produce lossy results when parent objects are rotated, so use setLocalScale( instead: ) if possible. */ setWorldScale(scale: vec3): void; } /** The base class for animation tracks. */ type AnimationTrack = ScriptObject; /** The base class for animation tracks using float values. */ type FloatAnimationTrack = AnimationTrack; /** Represents an animation track using vec2 value keyframes. */ type Vec2AnimationTrack = AnimationTrack; /** Represents an animation track using vec2 value keyframes. */ interface Vec2AnimationTrackKeyFramed extends Vec2AnimationTrack { /** Adds a keyframe value value at time time. */ addKey(time: number, value: vec2): void; /** Removes all keyframes. */ removeAllKeys(): void; /** Removes the keyframe at index. */ removeKeyAt(index: number): void; } /** Represents an animation track using float value keyframes. */ interface FloatAnimationTrackKeyFramed extends FloatAnimationTrack { /** Adds a key with value value at time time. */ addKey(time: number, value: number): void; /** Removes all keys. */ removeAllKeys(): void; /** Removes key at index index. */ removeKeyAt(index: number): void; } /** Represents an animation track using vec3 value keyframes for a bezier curve. */ interface FloatBezierAnimationTrackKeyFramed extends FloatAnimationTrack { /** Adds a key with value value at time time. */ addKey(time: number, value: vec3): void; /** Removes all keys. */ removeAllKeys(): void; /** Removes key at index index. */ removeKeyAt(index: number): void; } /** Represents an animation track using vec3 value keyframes. */ type Vec3AnimationTrack = AnimationTrack; /** Represents an animation track using vec3 value keyframes. */ interface Vec3AnimationTrackKeyFramed extends Vec3AnimationTrack { /** Adds a keyframe value value at time time. */ addKey(time: number, value: vec3): void; /** Removes all keyframes. */ removeAllKeys(): void; /** Removes the keyframe at index. */ removeKeyAt(index: number): void; } /** Represents an animation track using vec3 animation tracks. */ interface Vec3AnimationTrackXYZ extends Vec3AnimationTrack { /** Returns the child track at index index */ getChildTrackByIndex(index: number): AnimationTrack; /** Sets the child track at index index to track */ setChildTrackByIndex(index: number, track: AnimationTrack): void; } /** The base class for animation tracks using quaternion values. */ type QuaternionAnimationTrack = AnimationTrack; /** Represents an animation track using quaternion value keyframes. */ interface QuaternionAnimationTrackKeyFramed extends QuaternionAnimationTrack { /** Adds a key with value value at time time. */ addKey(time: number, value: quat): void; /** Removes all keys. */ removeAllKeys(): void; /** Removes key at index index. */ removeKeyAt(index: number): void; } /** Represents a rotation animation track using euler angles. */ interface QuaternionAnimationTrackXYZEuler extends QuaternionAnimationTrack { /** Returns child track at index index. */ getChildTrackByIndex(index: number): AnimationTrack; /** Sets child track at index index to track track. */ setChildTrackByIndex(index: number, track: AnimationTrack): void; } /** The base class for animation tracks using integer values. */ type IntAnimationTrack = AnimationTrack; /** Represents an animation track using stepped integer value keyframes. */ interface IntStepAnimationTrackKeyFramed extends IntAnimationTrack { /** Adds a key with value value at time time. */ addKey(time: number, value: number): void; /** Removes all keys. */ removeAllKeys(): void; /** Removes key at index index. */ removeKeyAt(index: number): void; } /** Represents an animation track using stepped integer value keyframes. */ interface IntStepNoLerpAnimationTrackKeyFramed extends IntAnimationTrack { /** Adds a key with value value at time time. */ addKey(time: number, value: number): void; /** Removes all keys. */ removeAllKeys(): void; /** Removes key at index index. */ removeKeyAt(index: number): void; } /** Base class for all assets used in the engine. */ interface Asset extends SerializableWithUID { /** * The name of the Asset in Lens Studio. */ name: string; } declare namespace Asset { /** File based asset. */ type BinAsset = Asset; /** * Binary ML model supplied by the user. * ``` * //@input Asset.MLAsset model * var mlComponent = script.sceneObject.createComponent('MLComponent'); * mlComponent.model = script.model; * ``` */ type MLAsset = BinAsset; /** Segmentation model used for SegmentationTextureProvider. */ type SegmentationModel = BinAsset; type AudioEffectAsset = Asset; /** Represents an audio file asset. See also: AudioComponent. */ type AudioTrackAsset = Asset; type Font = Asset; /** * Defines a marker to use for Marker Tracking with MarkerTrackingComponent. For more information, see the Marker Tracking guide. * ``` * // Set the MarkerAsset on a MarkerTracking component * * //@input Component.MarkerTrackingComponent markerTracker * //@input Asset.MarkerAsset marker * * script.markerTracker.marker = script.marker; * ``` */ interface MarkerAsset extends Asset { /** Returns the aspect ratio (width / height) of the texture used by the marker asset. */ getAspectRatio(): number; } /** * An asset that describes how visual objects should appear. Each Material is a collection of Passes which define the actual rendering passes. Materials are used by MeshVisuals for drawing meshes * in the scene. * ``` * // Gets the first pass of a material on a sprite and plays the animation from its texture * var sprite = script.getSceneObject().getFirstComponent("Component.SpriteVisual"); * var material = sprite.getMaterial(0); * material.getPass(0).baseTex.control.play(-1,0.0); * // Print number of passes * print("Pass count = " + material.getPassCount().toString()); * ``` */ interface Material extends Asset { /** The first Pass of the Material. */ mainPass: Pass; /** Returns a copy of the Material. */ clone(): Material; /** Returns the Pass of the Material at index index. */ getPass(index: number): Pass; /** Returns the number of Passes for the Material. */ getPassCount(): number; } type ObjectPrefab = Asset; /** Represents a mesh asset. See also: Asset.RenderMeshVisual. */ interface RenderMesh extends Asset { /** Returns the maximum value in each dimension of the axis-aligned bounding box containing this mesh. */ aabbMax: vec3; /** Returns the minimum value in each dimension of the axis-aligned bounding box containing this mesh. */ aabbMin: vec3; /** The RenderObjectProvider for this RenderMesh, which can provide more controls depending on the mesh type. See also: FaceRenderObjectProvider */ control: RenderObjectProvider; /** The index data type used by this mesh. */ indexType: MeshIndexType; /** The topology type used by this mesh. */ topology: MeshTopology; } /** Represents a texture file asset. */ interface Texture extends Asset { /** The TextureProvider for the texture, which may control things like animation depending on the texture type. See also: AnimatedTextureFileProvider. */ control: TextureProvider; /** Returns a Texture that captures the current state of this Texture Asset. */ copyFrame(): Texture; /** Returns the Colorspace of the Texture. */ getColorspace(): Colorspace; /** Returns the height of the texture. */ getHeight(): number; /** Returns the width of the texture. */ getWidth(): number; } /** * Configures an animation layer for a single SceneObject. Gives access to position, rotation, scale and blend shape animation tracks. See also: Playing 3D Animation Guide, AnimationMixer, * Animation. * */ interface AnimationLayer extends Asset { /** The Vec3AnimationTrack controlling position in this AnimationLayer. */ position: Vec3AnimationTrack; /** The QuaternionAnimationTrack controlling rotation in this AnimationLayer. */ rotation: QuaternionAnimationTrack; /** The Vec3AnimationTrack controlling scale in this AnimationLayer. */ scale: Vec3AnimationTrack; /** The IntAnimationTrack controlling visibility in this AnimationLayer. */ visibility: IntAnimationTrack; /** Returns a FloatAnimationTrack from this AnimationLayer’s blend shapes. */ getBlendShapeTrack(shapeName: string): FloatAnimationTrack; /** Sets or adds a FloatAnimationTrack to this AnimationLayer’s blend shapes. */ setBlendShapeTrack(shapeName: string, track: FloatAnimationTrack): void; } } /** Provider for RenderMesh data. */ type RenderObjectProvider = Provider; /** Mesh provider for a Face Mesh. Accessible through the control property on a Face Mesh RenderMesh. */ interface FaceRenderObjectProvider extends RenderObjectProvider { /** When true, a small area in the corners of the eyes will be included in the Face Mesh geometry. */ eyeCornerGeometryEnabled: boolean; /** When true, eyes will be included in the Face Mesh geometry. */ eyeGeometryEnabled: boolean; /** When true, the general face (not including eyes and mouth) will be included in the Face Mesh geometry. */ faceGeometryEnabled: boolean; /** Index of the face this FaceRenderObjectProvider mirrors. */ faceIndex: number; /** When true, the mouth will be included in the Face Mesh geometry. */ mouthGeometryEnabled: boolean; /** When true, the skull will be included in the Face Mesh geometry. */ skullGeometryEnabled: boolean; /** Returns a list of all expression names being tracked. */ getExpressionNames(): Array<keyof Expressions>; /** Returns the weight of the expression with the passed in name. See Expressions for valid expression names. */ getExpressionWeightByName(expressionName: keyof Expressions): number; /** Returns a Float32Array of all expression weights being tracked. */ getExpressionWeights(): Float32Array; } /** * Expression names used with FaceRenderObjectProvider.getExpressionWeightByName() and returned by FaceRenderObjectProvider.getExpressionNames(). * ``` * // @input Asset.RenderMesh faceMesh * var mouthCloseWeight = script.faceMesh.control.getExpressionWeightByName(Expressions.MouthClose); * ``` */ type Expressions = { [E in | `Brows${`Down${'Left' | 'Right'}` | `Up${'Center' | 'Left' | 'Right'}`}` | `CheekSquint${'Left' | 'Right'}` | `Eye${'Blink' | 'Down' | 'In' | 'Open' | 'Out' | 'Squint' | 'Up'}${'Left' | 'Right'}` | `Jaw${'Forward' | 'Left' | 'Right' | 'Open'}` | `${ | `Lips${'Funnel' | 'Pucker'}` | `LowerLip${`Down${'Left' | 'Right'}` | 'Raise'}` | `UpperLip${'Close' | 'Raise' | `Up${'Left' | 'Right'}`}`}` | `Mouth${`Close` | `${'Dimple' | 'Frown' | '' | 'Smile' | 'Stretch' | 'Up'}${'Left' | 'Right'}`}` | 'Puff' | `Sneer${'Left' | 'Right'}`]: E; }; /** RenderObjectProvider for mesh objects generated procedurally. */ type ProceduralMeshRenderObjectProvider = RenderObjectProvider; /** * Provider for RenderMesh data representing the estimated shape of real world objects generated from depth information. Only available when world mesh tracking is supported and enabled. Lens Studio * v3.2+ */ interface WorldRenderObjectProvider extends RenderObjectProvider { /** Enable or disable world mesh tracking. */ enableWorldMeshesTracking: boolean; /** Returns the number of faces of the mesh. */ faceCount: number; /** Mesh classification format being used. */ meshClassificationFormat: MeshClassificationFormat; /** Enable or disable normal direction usage. */ useNormals: boolean; /** Returns the number of vertices of the mesh. */ vertexCount: number; } /** Provider for AudioEffectAsset. */ type AudioEffectProvider = Provider; /** Base class for marker providers. For more information, see the Marker Tracking guide. */ type MarkerProvider = Provider; /** The base class for specialized Texture providers. Can be accessed through Texture.control. */ interface TextureProvider extends Provider { /** Returns the texture’s aspect ratio, which is calculated as width / height. */ getAspect(): number; /** Returns the height of the texture in pixels. */ getHeight(): number; /** Returns the width of the texture in pixels. */ getWidth(): number; } /** Controls an animated texture resource. Can be accessed from Texture.control on an animated texture. See also: 2D Animation Guide. */ interface AnimatedTextureFileProvider extends TextureProvider { /** Returns whether the animation was set to automatically play and loop. */ isAutoplay: boolean; /** If enabled, the animation will alternate between normal and reverse each time it loops. */ isPingPong: boolean; /** Whether the animation plays in reverse. */ isReversed: boolean; /** The animation track used to control the frame animation. */ track: IntStepAnimationTrackKeyFramed; /** Returns the index of the frame that is currently playing. */ getCurrentPlayingFrame(): number; /** Returns how long the animation is in seconds. */ getDuration(): number; /** Returns the number of frames in the animation. */ getFramesCount(): number; /** Returns whether the animation is finished playing. */ isFinished(): boolean; /** Returns whether the animation is currently paused. */ isPaused(): boolean; /** Returns whether the animation is currently playing. */ isPlaying(): boolean; /** Pauses the animation. */ pause(): void; /** Pauses the animation at frame frameIndex. */ pauseAtFrame(frameIndex: number): void; /** Plays the animation loops times, starting with an offset of offset seconds. */ play(loops: number, offset: number): void; /** Start playing the animation from frame frameIndex, loops times. */ playFromFrame(frameIndex: number, loops: number): void; /** Resumes a paused animation from the frame that was last played. */ resume(): void; /** Sets the callback function to be called whenever the animation stops playing. */ setOnFinish(eventCallback: (animatedTexture: AnimatedTextureFileProvider) => void): void; /** Stops the animation. */ stop(): void; } /** Base class for Texture Providers that crop an input texture. */ interface CropTextureProvider extends TextureProvider { /** Input texture to crop. */ inputTexture: Asset.Texture; } /** * Texture Provider giving a cropped region of the input texture, calculated based on face position. Can be accessed using Texture.control on a FaceCropTexture asset. For more information, see the * Crop Textures guide. */ interface FaceCropTextureProvider extends CropTextureProvider { /** Ratio of the mouth position on the cropped texture. Value ranges from 0 to 1, with 0 having no effect and 1 centering the image on the mouth. */ faceCenterMouthWeight: number; /** Index of the face being tracked. */ faceIndex: number; /** Scaling of the cropped texture. */ textureScale: vec2; } /** * Texture Provider providing a cropped region of the input texture. The region is specified by the cropRect in local space and rotation. Can be accessed using Texture.control on a RectCropTexture * asset, such as a Screen Crop Texture. For more information, see the Crop Textures guide. */ interface RectCropTextureProvider extends CropTextureProvider { /** The cropped region to draw. */ cropRect: Rect; /** in: Angle, radians, the cropped region is rotated by. */ rotation: number; } /** An axis aligned rectangle. Used by anchors and offsets in ScreenTransform to represent screen boundaries. */ interface Rect extends ScriptObject { /** The y position of the rectangle’s bottom side. */ bottom: number; /** The x position of the rectangle’s left side. */ left: number; /** The x position of the rectangle’s right side. */ right: number; /** The y position of the rectangle’s top side. */ top: number; /** Returns the rectangle’s center position as (x, y). */ getCenter(): vec2; /** Returns the size of the rectangle as (width, height). */ getSize(): vec2; /** Sets the rectangle’s center position while maintaining its size. */ setCenter(value: vec2): void; /** Sets the rectangle’s size while maintaining its center position. */ setSize(value: vec2): void; /** Returns a string representation of the Rect. */ toString(): string; } declare namespace Rect { /** Creates a new Rect with the given properties. */ function create(left: number, right: number, bottom: number, top: number): Rect; } /** * Provides depth information of the video feed that the Lens is being applied to when available, such as in Lenses for Spectacles 3. Can be accessed from mainPass.baseTex.control of a Spectacles * Depth material. */ interface DepthTextureProvider extends TextureProvider { /** * Returns the depth at the screen space position “point”. The value returned is between 0 and 6,550, which corresponds to the distance the point is from the camera in centimeters, or world-space * units. If depth data is not available, -1 will be returned. Note that depth data isn’t available during the very first Initialize event, before TurnOn event fires. */ getDepth(point: vec2): number; } /** TextureProvider for face textures. See the Face Texture Guide for more information. Can be accessed using Texture.control on a face texture asset. */ interface FaceTextureProvider extends TextureProvider { /** The source texture being drawn. This is useful for controlling which effects are visible on the face texture, based on which camera output texture is being used. */ inputTexture: Asset.Texture; /** * The x and y scale used to draw the face within the texture region. A lower scale will be more zoomed in on the face, and a higher scale will be more zoomed out. The default scale is * (1, 1). */ scale: vec2; } /** A TextureProvider for textures originating from files. */ type FileTextureProvider = TextureProvider; /** Controls an image picker texture and UI. Can be accessed through Texture.control on an Image Picker texture. For more information, see the Image Picker Texture guide. */ interface ImagePickerTextureProvider extends TextureProvider { /** If enabled, the image picker UI will be shown automatically when the Lens starts. */ autoShowImagePicker: boolean; /** Hides the image picker UI. */ hideImagePicker(): void; /** Binds a callback function for when the user selects or changes an image from the picker. */ setImageChangedCallback(callback: () => void): void; /** Shows the image picker UI. */ showImagePicker(): void; } /** Controls the face image picker texture resource. Can be accessed through Texture.control on a Face Image Picker texture. For more information, see the Face Image Picker Texture guide. */ interface FaceImagePickerTextureProvider extends ImagePickerTextureProvider { /** If enabled, the selected image will be cropped to only show the face region. */ cropToFace: boolean; /** The FaceTextureProvider used to provide the face texture. */ faceControl: FaceTextureProvider; } /** Controls a segmentation texture and its placement using information provided by Object tracking. */ interface ObjectTrackingTextureProvider extends TextureProvider { /** Index of the tracked object to use for segmentation. */ objectIndex: number; } /** Provides a texture that can be written to or read from. Can be accessed using Texture.control on a Procedural Texture. */ interface ProceduralTextureProvider extends TextureProvider { /** * Returns a Uint8 array containing the pixel values in a region of the texture. The region starts at the pixel coordinates x, y, and extends rightward by width and upward by height. Values * returned are integers ranging from 0 to 255. */ getPixels(x: number, y: number, width: number, height: number, data: Uint8Array): void; /** * Sets a region of pixels on the texture. The region starts at the pixel coordinates x, y, and extends rightward by width and upward by height. Uses the values of the passed in Uint8Array data, * which should be integer values ranging from 0 to 255. */ setPixels(x: number, y: number, width: number, height: number, data: Uint8Array): void; } declare namespace ProceduralTextureProvider { /** Creates a new, blank Texture Provider using the passed in dimensions and Colorspace. The ProceduralTextureProvider can be accessed through the control property on the returned texture. */ function create(width: number, height: number, colorspace: Colorspace): Asset.Texture; /** Creates a new Procedural Texture based on the passed in texture. The ProceduralTextureProvider can be accessed through the control property on the returned texture. */ function createFromTexture(texture: Asset.Texture): Asset.Texture; } /** Controls a camera texture resource. Can be accessed through Texture.control on a Camera texture. For more information, see the Camera and Layers guide. */ interface RenderTargetProvider extends TextureProvider { /** When clearColorEnabled is true and inputTexture is null, this color is used to clear this RenderTarget the first time it is drawn to each frame. */ clearColor: vec4; /** * If true, the color on this RenderTarget will be cleared the first time it is drawn to each frame. inputTexture will be used to clear it unless it is null, in which case clearColor is used * instead. */ clearColorEnabled: boolean; /** If true, the depth buffer will be cleared on this RenderTarget the first time it is drawn to each frame. */ clearDepthEnabled: boolean; /** When clearColorEnabled is true, this texture is used to clear this RenderTarget the first time it is drawn to each frame. If this texture is null, clearColor will be used instead. */ inputTexture: Asset.Texture; /** When useScreenResolution is false, controls the horizontal and vertical resolution of the Render Target. */ resolution: vec2; /** If true, the Render Target’s resolution will match the device’s screen resolution. */ useScreenResolution: boolean; } /** Texture providing the current Render Target being rendered. Lens Studio v3.0+ */ interface ScreenTextureProvider extends TextureProvider { /** Returns the texture’s aspect ratio, which is calculated as width / height. */ getAspect(): number; /** Returns the height of the texture in pixels. */ getHeight(): number; /** Returns the width of the texture in pixels. */ getWidth(): number; /** Returns the name of this object’s type. */ getTypeName(): string; /** Returns true if the object matches or derives from the passed in type. */ isOfType(type: string): boolean; } /** Controls a segmentation texture resource. Can be accessed through Texture.control on a Segmentation texture. For more information, see the Segmentation guide. Lens Studio v1.7.0+ */ type SegmentationTextureProvider = TextureProvider; /** Controls a text rendering texture. Can be accessed through the main rendering pass on a Label component. The properties here mirror those on Label. Lens Studio v1.7.0+ */ interface TextProvider extends TextureProvider { /** The font used for rendering text. */ fontAsset: Asset.Font; /** The color used for the outline effect. */ outlineColor: vec4; /** The strength of the outline effect. */ outlineSize: number; /** The color used for dropshadow. */ shadowColor: vec4; /** The horizontal and vertical offset used for dropshadow. */ shadowOffset: vec2; /** The font size being used. */ size: number; /** The text being rendered. */ text: string; /** The color for rendering text. */ textColor: vec4; /** If enabled, adds a dropshadow to the text. */ useDropshadow: boolean; /** If enabled, renders an outline around the text. */ useOutline: boolean; } /** Controls a video texture resource. Can be accessed through Texture.control. Lens Studio v1.5.0+ */ interface VideoTextureProvider extends TextureProvider { /** The audio volume of the video resource, normalized from 0 to 1. */ volume: number; /** Returns the number of times the video has played consecutively. */ getCurrentPlayCount(): number; /** Returns the status of the video resource. */ getStatus(): VideoStatus; /** Pauses the video playback. */ pause(): void; /** Plays the video playCount times. If playCount is less than 0, it loops infinitely. */ play(playCount: number): void; /** Resumes the video playback. */ resume(): void; /** Sets callback as the function invoked when the video resource stops playing. */ setOnFinish(callback: () => void): void; /** Sets callback as the function invoked when the video resource is ready to be played. */ setOnReady(onReadyCallback: () => void): void; /** Stops the video playback. */ stop(): void; } /** Base class for all resource providers. */ type Provider = ScriptObject; interface EventMapping { BrowsLoweredEvent: BrowsLoweredEvent; BrowsRaisedEvent: BrowsRaisedEvent; BrowsReturnedToNormalEvent: BrowsReturnedToNormalEvent; CameraBackEvent: CameraBackEvent; CameraFrontEvent: CameraFrontEvent; DelayedCallbackEvent: DelayedCallbackEvent; FaceFoundEvent: FaceFoundEvent; FaceLostEvent: FaceLostEvent; FaceTrackingEvent: FaceTrackingEvent; KissFinishedEvent: KissFinishedEvent; KissStartedEvent: KissStartedEvent; LateUpdateEvent: LateUpdateEvent; ManipulateEndEvent: ManipulateEndEvent; ManipulateStartEvent: ManipulateStartEvent; MouthClosedEvent: MouthClosedEvent; MouthOpenedEvent: MouthOpenedEvent; SceneEvent: SceneEvent; SceneObjectEvent: SceneObjectEvent; SmileFinishedEvent: SmileFinishedEvent; SmileStartedEvent: SmileStartedEvent; SurfaceTrackingResetEvent: SurfaceTrackingResetEvent; TapEvent: TapEvent; TouchEndEvent: TouchEndEvent; TouchMoveEvent: TouchMoveEvent; TouchStartEvent: TouchStartEvent; TurnOffEvent: TurnOffEvent; TurnOnEvent: TurnOnEvent; UpdateEvent: UpdateEvent; } /** Triggered when the device’s back facing camera becomes active. */ interface CameraBackEvent extends SceneEvent<CameraBackEvent> {} /** Triggered when the device’s front facing camera becomes active. */ interface CameraFrontEvent extends SceneEvent<CameraFrontEvent> {} /** An event that gets triggered after a delay. */ interface DelayedCallbackEvent extends SceneEvent<DelayedCallbackEvent> { /** Returns the total delay time in seconds set on the event. */ getDelayTime(): number; /** Returns the current time in seconds left in the event’s delay. */ getTimeLeft(): number; /** Calling this will cause the event to trigger in time seconds. */ reset(time: number): void; } /** This is the base class for all face tracking events. This event won’t actually get triggered itself, so use one of the child classes instead. */ interface FaceTrackingEvent extends SceneEvent<FaceTrackingEvent> { /** The index of the face this event is tracking. Change this value to control which face the event tracks. */ faceIndex: number; } /** Triggered when eyebrows are lowered on the tracked face. */ type BrowsLoweredEvent = FaceTrackingEvent; /** Triggered when eyebrows are raised on the tracked face. */ type BrowsRaisedEvent = FaceTrackingEvent; /** Triggered when eyebrows are returned to normal on the tracked face. */ type BrowsReturnedToNormalEvent = FaceTrackingEvent; /** Triggered when a new face is detected and starts being tracked. */ type FaceFoundEvent = FaceTrackingEvent; /** Triggered when a face can no longer be tracked. For example, if a face gets blocked from the camera’s view, or gets too far away. */ type FaceLostEvent = FaceTrackingEvent; /** Triggered when the tracked face ends a kiss. */ type KissFinishedEvent = FaceTrackingEvent; /** Triggered when the tracked face starts a kiss. */ type KissStartedEvent = FaceTrackingEvent; /** Triggered when the tracked face’s mouth closes. */ type MouthClosedEvent = FaceTrackingEvent; /** Triggered when the tracked face’s mouth opens. */ type MouthOpenedEvent = FaceTrackingEvent; /** Triggered when a smile ends on the tracked face. */ type SmileFinishedEvent = FaceTrackingEvent; /** Triggered when a smile begins on the tracked face. */ type SmileStartedEvent = FaceTrackingEvent; /** This event is triggered at the end of every frame, after normal UpdateEvents trigger but before rendering occurs. */ interface LateUpdateEvent extends SceneEvent<LateUpdateEvent> { /** Returns the time elapsed ( seconds: in) between the current frame and previous frame. */ getDeltaTime(): number; } /** Base class for all object-based Event types in Lens Studio (ManipulateStartEvent, TapEvent, etc.). */ interface SceneObjectEvent extends SceneEvent<SceneObjectEvent> { /** Returns the SceneObject this Event is associated with. */ getSceneObject(): SceneObject; } /** This event is triggered when manipulation on the object ends. */ type ManipulateEndEvent = SceneObjectEvent; /** This event is triggered when manipulation on the object begins. */ type ManipulateStartEvent = SceneObjectEvent; /** This event is triggered when the user taps on the screen. */ interface TapEvent extends SceneObjectEvent { /** Returns the normalized 2D screen position of the user’s tap. The normalized coordinates range from ([0-1], [0-1]), (0,0) being top-left and (1,1) being bottom-right. */ getTapPosition(): vec2; } interface _TouchEvent extends SceneObjectEvent { /** Returns the ID of this specific touch. Useful for distinguishing between touches when multiple are occurring simultaneously. */ getTouchId(): number; /** Returns the normalized 2D screen position of the user’s touch. The normalized coordinates range from ([0-1], [0-1]), (0,0) being top-left and (1,1) being bottom-right. */ getTouchPosition(): vec2; } /** Triggered when a touch event ends. */ type TouchEndEvent = _TouchEvent; /** Triggered when a touch position on the screen is moved. */ type TouchMoveEvent = _TouchEvent; /** Triggered when a touch event starts. */ type TouchStartEvent = _TouchEvent; /** If a DeviceTracking component is present in the scene, this event is triggered when the tracking is restarted (typically when the Lens starts, or if the user taps the ground). */ interface SurfaceTrackingResetEvent extends SceneEvent<SurfaceTrackingResetEvent> {} /** Triggered when the lens turns off. */ interface TurnOffEvent extends SceneEvent<TurnOffEvent> {} /** Triggered when the lens turns on. */ interface TurnOnEvent extends SceneEvent<TurnOnEvent> {} /** Triggered every frame. */ interface UpdateEvent extends SceneEvent<UpdateEvent> { /** Returns the time elapsed ( seconds: in) between the current frame and previous frame. */ getDeltaTime(): number; } /** Triggered when new world tracking meshes are detected. Only available when a Device Tracking component is in the scene, and world mesh tracking is supported and enabled. */ interface WorldTrackingMeshesAddedEvent extends SceneEvent<WorldTrackingMeshesAddedEvent> { /** Returns an array of newly added Tracked Meshes. */ getMeshes(): TrackedMesh[]; } /** Represents a mesh generated by world tracking. Only available when world mesh tracking is supported and enabled. */ interface TrackedMesh extends ScriptObject { /** Returns whether the tracked mesh is valid. */ isValid: boolean; /** Returns the World Transformation matrix of the detected mesh. */ transform: mat4; } /** Triggered when some world tracking meshes are no longer detected. Only available when a Device Tracking component is in the scene, and world mesh tracking is supported and enabled. */ interface WorldTrackingMeshesRemovedEvent extends SceneEvent<WorldTrackingMeshesRemovedEvent> { /** Returns an array of TrackedMeshes that are no longer detected. */ getMeshes(): TrackedMesh[]; } /** Triggered when world tracking meshes are updated. Only available when a Device Tracking component is in the scene, and world mesh tracking is supported and enabled. */ interface WorldTrackingMeshesUpdatedEvent extends SceneEvent<WorldTrackingMeshesUpdatedEvent> { /** Returns an array of TrackedMeshes that were updated. */ getMeshes(): TrackedMesh[]; } /** The base class for scenewide events. SceneEvents can be created using ScriptComponent’s createEvent method. */ interface SceneEvent<T extends SceneEvent = any> extends IEventParameters { /** If true, the event is able to trigger. If false, the event will not trigger. */ enabled: boolean; /** Binds a callback function to this event. */ bind(evCallback: (eventData: Omit<T, 'enabled'>) => void): void; /** Returns the typename of the SceneEvent. */ getTypeName(): string; } /** The base class for parameter objects passed into event callbacks. */ type IEventParameters = ScriptObject; /** Base class for objects representing Script data. */ interface ScriptObject { /** Returns the name of this object’s type. */ getTypeName(): string; /** Returns true if the object matches or derives from the passed in type. */ isOfType(type: string): boolean; } /** * Controls how a mesh will get rendered. Each Pass acts as an interface for the shader * it’s associated with. Any properties on a Pass’s shader will automatically become * properties on that Pass. For example, if the shader defines a variable named baseColor, * a script would be able to access that property as Pass.baseColor. * * @see https://lensstudio.snapchat.com/api/classes/Pass/ * * If you need to rely on any of the Shader Properties documented below, then use a block like the following in your script to augment the Pass interface: * @see https://lensstudio.snapchat.com/api/ShaderProperties/ * ``` * declare global { * interface Pass { * // Specifies the base color (albedo) of the material if the ‘Base Texture’ is disabled. Multiplied with the ‘Base Texture’ otherwise. * baseColor: vec4 * // Most materials use a base texture (albedo), but disabling it means the base texture will be considered white, and ‘Base Color’ will solely control the color. * baseTex: Asset.Texture * // Normally, the Base Texture’s alpha is taken as opacity. Enabling this allows you to define a separate greyscale opacity texture. The ‘Opacity Texture’ value will be multiplied with the * // Base Texture’s alpha (which is 1 for textures without alpha) to get the final opacity. ‘Opacity Texture’ is only available if ‘Blend Mode’ is not ‘Disabled’. * opacityTex: Asset.Texture * } * } * ``` */ interface Pass extends ScriptObject { /** * The blend mode used for rendering. Possible values: * * BlendMode - Value - Expression * * Normal - 0 - SrcAlpha, OneMinusSrcAlpha * * MultiplyLegacy [DEPRECATED] - 1 - DstColor, OneMinusSrcAlpha * * AddLegacy [DEPRECATED] - 2 - One, One * * Screen - 3 - One, OneMinusSrcColor * * PremultipliedAlpha - 4 - One, OneMinusSrcAlpha * * AlphaToCoverage - 5 - Blend Disabled * * Disabled - 6 - Blend Disabled * * Add - 7 - SrcAlpha, One * * AlphaTest - 8 - Blend Disabled * * ColoredGlass - 9 - Blend Disabled * * Multiply - 10 - DstColor, Zero * * Min - 11 - One, One * * Max - 12 - One, One * * ``` * // Sets the blend mode of the main pass for a material to Screen * //@input Asset.Material material * script.material.mainPass.blendMode = 3; * ``` */ blendMode: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; /** Controls the masking of color channels with a vec4b representing each channel with a boolean. */ colorMask: vec4b; /** The cull mode used for rendering. */ cullMode: CullMode; /** Enables depth-sorting. */ depthTest: boolean; /** Enables writing pixels to the depth buffer. */ depthWrite: boolean; /** Number of times the pass will be rendered. Useful with the Instance ID node in Material Editor. */ instanceCount: number; /** Line width used for rendering. */ lineWidth: number; /** The name of the Pass. */ name: string; /** Changes the position that each polygon gets drawn. */ polygonOffset: vec2; /** Whether the material renders on both sides of a mesh face. */ twoSided: boolean; } /** Used with Pass’s cullMode property. Determines which faces of a surface are culled (not rendered). */ declare enum CullMode { /** Front facing surfaces are not rendered. */ Front, /** Back facing surfaces are not rendered. */ Back, /** Neither front facing nor back facing surfaces are rendered. */ FrontAndBack, } /** * Allows data to be stored and retrieved between Lens sessions. In other words, data can be saved on device and loaded back in the next time the Lens is opened. Can be accessed with global. * persistentStorageSystem. */ interface PersistentStorageSystem extends ScriptObject { /** The GeneralDataStore object used to store and retrieve data. */ store: GeneralDataStore; } /** Class for storing and retrieving data based on keys. Used by PersistentStorageSystem. For more information, see the Persistent Storage guide. */ interface GeneralDataStore extends ScriptObject { /** * Callback function that gets called when the allowed storage limit has been passed. The store won’t be saved if it is full, so if this is called make sure to remove data until back under the * limit. */ onStoreFull: () => void; /** Clears all data stored in the General Data Store. */ clear(): void; /** Returns a boolean value stored under the given key, or false if none exists. */ getBool(key: string): boolean; /** Returns a boolean array being stored under the given key, or an empty array if none exists. */ getBoolArray(key: string): boolean[]; /** Returns a double precision floating point number stored under the given key, or 0 if none exists. */ getDouble(key: string): number; /** Returns a floating point value stored under the given key, or 0 if none exists. */ getFloat(key: string): number; /** Returns a floating point array being stored under the given key, or an empty array if none exists. */ getFloatArray(key: string): number[]; /** Returns an integer number stored under the given key, or 0 if none exists. */ getInt(key: string): number; /** Returns an integer array being stored under the given key, or an empty array if none exists. */ getIntArray(key: string): number[]; /** Returns a mat2 value stored under the given key, or a default mat2 if none exists. */ getMat2(key: string): mat2; /** Returns a mat2 array being stored under the given key, or an empty array if none exists. */ getMat2Array(key: string): mat2[]; /** Stores a mat3 value under the given key. */ getMat3(key: string): mat3; /** Returns a mat3 array being stored under the given key, or an empty array if none exists. */ getMat3Array(key: string): mat3[]; /** Returns a mat4 value stored under the given key, or a default mat4 if none exists. */ getMat4(key: string): mat4; /** Returns a mat4 array being stored under the given key, or an empty array if none exists. */ getMat4Array(key: string): mat4[]; /** Returns the maximum total size in: allowed, bytes, of all data stored in this General Data Store. */ getMaxSizeInBytes(): number; /** Returns a quat value stored under the given key, or a default quat if none exists. */ getQuat(key: string): quat; /** Returns a quat array being stored under the given key, or an empty array if none exists. */ getQuatArray(key: string): quat[]; /** If onStoreFull has been set, this method returns the current total in: size, bytes, of all data stored in this General Data Store. Otherwise, 0 is returned. */ getSizeInBytes(): number; /** Returns a string value stored under the given key, or empty string if none exists. */ getString(key: string): string; /** Returns a string array being stored under the given key, or an empty array if none exists. */ getStringArray(key: string): string[]; /** Returns a vec2 value stored under the given key, or a default vec2 if none exists. */ getVec2(key: string): vec2; /** Returns a vec2 array being stored under the given key, or an empty array if none exists. */ getVec2Array(key: string): vec2[]; /** Returns a vec3 value stored under the given key, or a default vec3 if none exists. */ getVec3(key: string): vec3; /** Returns a vec3 array being stored under the given key, or an empty array if none exists. */ getVec3Array(key: string): vec3[]; /** Returns a vec4 value stored under the given key, or a default vec4 if none exists. */ getVec4(key: string): vec4; /** Returns a vec4 array being stored under the given key, or an empty array if none exists. */ getVec4Array(key: string): vec4[]; /** Returns true if a value is being stored under the given key. */ has(key: string): boolean; /** Stores a boolean value under the given key. */ putBool(key: string, value: boolean): void; /** Stores a boolean array under the given key. */ putBoolArray(key: string, value: boolean[]): void; /** Stores a double precision floating point number under the given key. */ putDouble(key: string, value: number): void; /** Stores a floating point value under the given key. */ putFloat(key: string, value: number): void; /** Stores a floating point array under the given key. */ putFloatArray(key: string, value: number[]): void; /** Stores an integer number value under the given key. */ putInt(key: string, value: number): void; /** Stores an integer array under the given key. */ putIntArray(key: string, value: number[]): void; /** Stores a mat2 value under the given key. */ putMat2(key: string, value: mat2): void; /** Stores a mat2 array under the given key. */ putMat2Array(key: string, value: mat2[]): void; /** Stores a mat3 value under the given key. */ putMat3(key: string, value: mat3): void; /** Stores a mat3 array under the given key. */ putMat3Array(key: string, value: mat3[]): void; /** Stores a mat4 value under the given key. */ putMat4(key: string, value: mat4): void; /** Stores a mat4 array under the given key. */ putMat4Array(key: string, value: mat4[]): void; /** Stores a quat value under the given key. */ putQuat(key: string, value: quat): void; /** Stores a quat array under the given key. */ putQuatArray(key: string, value: quat[]): void; /** Stores a string value under the given key. */ putString(key: string, value: string): void; /** Stores a string array under the given key. */ putStringArray(key: string, value: string[]): void; /** Stores a vec2 value under the given key. */ putVec2(key: string, value: vec2): void; /** Stores a vec2 array under the given key. */ putVec2Array(key: string, value: vec2[]): void; /** Stores a vec3 value under the given key. */ putVec3(key: string, value: vec3): void; /** Stores a vec3 array under the given key. */ putVec3Array(key: string, value: vec3[]): void; /** Stores a vec4 value under the given key. */ putVec4(key: string, value: vec4): void; /** Stores a vec4 array under the given key. */ putVec4Array(key: string, value: vec4[]): void; /** Removes the value being stored under the given key. If no value exists under the key, nothing will happen. */ remove(key: string): void; } /** * Provides information about the user such as display name, birthday, * and current weather. Accessible through global.userContextSystem. * * All callbacks will execute as soon as the requested information is available. * In some rare cases, the requested information may be completely unavailable, * and the callback will never occur. * * Note that formatted or localized strings may appear differently to users * depending on their region. */ interface UserContextSystem extends ScriptObject { /** Provides the user’s current altitude as a localized string. */ requestAltitudeFormatted(callback: (formattedData: string) => void): void; /** Provides the user’s current altitude in meters. */ requestAltitudeInMeters(callback: (data: number) => void): void; /** Provides the user’s birth date as a Date object. */ requestBirthdate(callback: (data: Date) => void): void; /** Provides the user’s birth date as localized string. */ requestBirthdateFormatted(callback: (formattedData: string) => void): void; /** Provides the name of the city the user is currently located in. */ requestCity(callback: (data: string) => void): void; /** Provides the user’s display name. */ requestDisplayName(callback: (data: string) => void): void; /** Provides the user’s current temperature in celsius. */ requestTemperatureCelsius(callback: (data: number) => void): void; /** Provides the user’s current temperature in fahrenheit. */ requestTemperatureFahrenheit(callback: (data: number) => void): void; /** Provides the user’s current temperature as a localized string. */ requestTemperatureFormatted(callback: (formattedData: string) => void): void; /** Provides the user’s current weather condition. */ requestWeatherCondition(callback: (data: WeatherCondition) => void): void; /** Provides the user’s current weather condition as a localized string. */ requestWeatherLocalized(callback: (formattedData: string) => void): void; } /** * Helps convert data types to localized string representations. Accessible through global.localizationSystem. Note that formatted or localized strings may appear differently to users depending on * their region. The example results given here are representative of a user in the United States, but may appear differently for users in other regions. */ interface LocalizationSystem extends ScriptObject { /** Returns a localized string for the date and time of the passed in Date object. Example: “Jan 1, 2019 at 12:34 AM” */ getDateAndTimeFormatted(date: Date): string; /** Returns a localized string for the date of the passed in Date object. Example: “Jan 1, 2019” */ getDateFormatted(date: Date): string; /** Returns a short, localized string for the date of the passed in Date object. Example: “1/1/19” */ getDateShortFormatted(date: Date): string; /** Returns a localized string for the day of the week of the passed in Date object. Example: “Tuesday” */ getDayOfWeek(date: Date): string; /** Returns a localized, formatted string representation of the distance in meters passed in. Example: “39.4 in” (from 1 passed in) */ getFormattedDistanceFromMeters(meters: number): string; /** Returns a localized, formatted string representation of the number passed in. Example: “1,234” (from 1234 passed in) */ getFormattedNumber(number: number): string; /** Returns a localized, formatted string representing the number of seconds passed in. Example: “2:06” (from 126 passed in) */ getFormattedSeconds(seconds: number): string; /** Returns a localized, formatted string representation of the celsius temperature passed in. Example: “32°F” (from 0 passed in) */ getFormattedTemperatureFromCelsius(temperature: number): string; /** Returns a localized, formatted string representation of the fahrenheit temperature passed in. Example: “32°F” (from 32 passed in) */ getFormattedTemperatureFromFahrenheit(temperature: number): string; /** Returns the language code of the language being used on the device. Example: “en” ( English: for) */ getLanguage(): string; /** Returns a localized string for the month of the passed in Date object. Example: “January” */ getMonth(date: Date): string; /** Returns a localized string for the time of the passed in Date object. Example: “12:34 AM” */ getTimeFormatted(date: Date): string; } /** * This provider is returned by global.touchSystem and allows your lens to handle any touches on the screen, and optionally let certain touch types to pass through (let Snapchat handle the * touch). */ interface TouchDataProvider extends ScriptObject { /** * Set your lens to handle touches on the screen, preventing default Snapchat touch behavior from occuring. Useful for enabling full screen touches without any touch components. It is similar to * creating a plane the size of the screen in front of the camera. */ touchBlocking: boolean; /** The current touch mask. */ touchBlockingExceptionMask: number; /** Returns a copy of currentMask with the newException flag set to true. */ composeTouchBlockingExceptionMask(currentMask: number, newException: TouchTypeException): number; /** Allow or stop allowing a certain TouchType to pass through your lens. Useful for allowing Snapchat to handle certain TouchType, e.g. allowing TouchTypeDoubleTap to flip the camera. */ enableTouchBlockingException(exception: TouchTypeException, enable: boolean): void; } /** Settings for rendering the background on a Text component. Accessible through the Text component’s backgroundSettings property. */ interface BackgroundSettings extends ScriptObject { /** If enabled, the background will be rendered. */ enabled: boolean; /** Settings for how the inside of the background is drawn. */ fill: TextFill; /** Controls how far in each direction the background should extend away from the text. */ margins: Rect; } /** Used in Text’s dropShadowSettings property. Configures how dropshadow will appear on a Text component. */ interface DropshadowSettings extends ScriptObject { /** Whether dropshadow is enabled on the Text. */ enabled: boolean; /** Settings for how the inside of the dropshadow is drawn. */ fill: TextFill; /** An (x, y) offset controlling where the dropshadow is drawn relative to the Text. */ offset: vec2; } /** Fill settings used by several text related classes. Used in Text’s textFill property, DropshadowSettings’ fill property, and OutlineSettings’ fill property. */ interface TextFill extends ScriptObject { /** If mode is set to TextFillMode.Solid, this will be used as the solid color used in drawing. */ color: vec4; /** Controls which drawing method is used. Can switch between Texture mode (for drawing using a tiled texture) or Solid mode (for drawing a solid color). */ mode: TextFillMode; /** If mode is set to TextFillMode.Texture, this will be used as the texture asset used in drawing. */ texture: Asset.Texture; /** If mode is set to TextFillMode.Texture, this defines what type of stretching is used when the Texture’s aspect ratio doesn’t match the drawing area’s aspect ratio. */ textureStretch: StretchMode; /** If mode is set to TextFillMode.Texture, this defines how many times the texture will tile across its drawing zone. */ tileCount: number; /** If mode is set to TextFillMode.Texture, this defines what area should be used for tiling the texture. */ tileZone: TileZone; } /** Used in TextFill’s mode property. Controls which drawing method is used for the TextFill. */ declare enum TextFillMode { /** Solid color will be used for drawing. */ Solid, /** Tiled texture will be used for drawing. */ Texture, } /** Defines the bounding area used for texture tiling with TextFill’s tileZone property. */ declare enum TileZone { /** The attached ScreenTransform’s bounding rectangle is used for texture tiling */ Rect, /** The Text component’s drawn area (extents) is used for texture tiling */ Extents, /** Each character uses its own drawn area for texture tiling */ Character, /** The position of each character in screen space is used for tiling */ Screen, } /** Options for wrapping text horizontally. Used by Text component’s horizontalOverflow property. */ declare enum HorizontalOverflow { /** Text will continue drawing past horizontal boundaries. */ Overflow, /** Text is clipped to the width of horizontal boundaries. */ Truncate, /** Text wraps when reaching horizontal boundaries and continues on the next line. */ Wrap, /** Text will shrink to fit within the horizontal boundaries. */ Shrink, } /** Options for handling vertical text overflow. Used by Text component’s verticalOverflow property. */ declare enum VerticalOverflow { /** Text will continue to draw past the end of the vertical boundaries. */ Overflow, /** Text will be clipped at the end of the vertical boundaries. */ Truncate, /** Text will shrink to fit within the vertical boundaries. */ Shrink, } /** Used in Text’s outlineSettings property. Configures how text outlining will appear on a Text component. */ interface OutlineSettings extends ScriptObject { /** Whether outline is enabled on the Text. */ enabled: boolean; /** Settings for how the outline is drawn. */ fill: TextFill; /** The strength of the outline effect, ranging from 0.0 ( outline: no) to 1.0 (very strong outline). */ size: number; } type TouchTypeException = `TouchType${'None' | 'Touch' | 'Tap' | 'DoubleTap' | 'Scale' | 'Pan' | 'Swipe'}`; declare namespace SnapchatLensStudio { interface Global { /** Returns the global GeneralDataStore for Launch Params, which provides any special data passed in when the Lens is launched. */ launchParams: GeneralDataStore; /** Returns the global LocalizationSystem, which helps convert times, dates, and other units to user friendly strings. */ localizationSystem: LocalizationSystem; /** Returns the global PersistentStorageSystem, which allows data to persist between Lens sessions. */ persistentStorageSystem: PersistentStorageSystem; /** Returns the global ScriptScene object, which offers information and controls for the current scene. */ scene: ScriptScene; /** Returns the global TouchDataProvider, which controls how the Lens handles touch events. */ touchSystem: TouchDataProvider; /** Returns the global UserContextSystem, which provides information about the user such as display name, birthday, and even current weather. */ userContextSystem: UserContextSystem; /** Returns the time difference in seconds between the current frame and previous frame. */ getDeltaTime(): number; /** Returns the time in seconds since the lens was started. */ getTime(): number; /** Returns true if the passed in object is null or destroyed. Useful as a safe way to check if a SceneObject or Component has been destroyed. */ isNull(reference: object): boolean; /** Prints out a message to the Logger window. */ print(message: object): void; } interface ComponentMapping { 'Component.ScriptComponent': Component.ScriptComponent; 'Component.Visual': Component.Visual; 'Component.Camera': Component.Camera; 'Component.ScreenTransform': Component.ScreenTransform; 'Component.MLComponent': Component.MLComponent; 'Component.ObjectTracking': Component.ObjectTracking; 'Component.PinToMeshComponent': Component.PinToMeshComponent; 'Component.RectangleSetter': Component.RectangleSetter; 'Component.ScreenRegionComponent': Component.ScreenRegionComponent; 'Component.Animation': Component.Animation; 'Component.AnimationMixer': Component.AnimationMixer; 'Component.AudioComponent': Component.AudioComponent; 'Component.SpriteAligner': Component.SpriteAligner; 'Component.TouchComponent': Component.TouchComponent; 'Component.VertexCache': Component.VertexCache; 'Component.BlendShapes': Component.BlendShapes; 'Component.DeviceLocationTrackingComponent': Component.DeviceLocationTrackingComponent; 'Component.DeviceTracking': Component.DeviceTracking; 'Component.Head': Component.Head; 'Component.HintsComponent': Component.HintsComponent; 'Component.LightSource': Component.LightSource; 'Component.LookAtComponent': Component.LookAtComponent; 'Component.ManipulateComponent': Component.ManipulateComponent; 'Component.MarkerTrackingComponent': Component.MarkerTrackingComponent; 'Component.BaseMeshVisual': Component.BaseMeshVisual; 'Component.FaceStretchVisual': Component.FaceStretchVisual; 'Component.LiquifyVisual': Component.LiquifyVisual; 'Component.MaterialMeshVisual': Component.MaterialMeshVisual; 'Component.Text': Component.Text; 'Component.EyeColorVisual': Component.EyeColorVisual; 'Component.FaceInsetVisual': Component.FaceInsetVisual; 'Component.FaceMaskVisual': Component.FaceMaskVisual; 'Component.Image': Component.Image; 'Component.RenderMeshVisual': Component.RenderMeshVisual; 'Component.RetouchVisual': Component.RetouchVisual; 'Component.SpriteVisual': Component.SpriteVisual; } interface ScriptInputs {} // tslint:disable-line no-empty-interface interface ScriptApi {} // tslint:disable-line no-empty-interface }
the_stack
import * as React from 'react'; import { renderWithProvider } from '@synerise/ds-utils/dist/testing'; import { DSProvider } from '@synerise/ds-core'; import { fireEvent, cleanup } from '@testing-library/react'; import ItemsRoll from '../ItemsRoll'; import { propsFactory, ACTIONS, ITEM_TEXT } from './utils'; const messages = { en: { DS: { 'ITEMS-ROLL': { 'CHANGE-SELECTION': 'Change selection', 'CLEAR-ALL': 'Clear all', 'CLEAR-TOOLTIP': 'Clear', ITEMS: 'Items', MORE: 'more', 'NO-RESULTS': 'No results', 'REMOVE-TOOLTIP': 'Remove', SHOW: 'Show', 'SHOW-LESS': 'Show less', }, }, }, }; const DEFAULT_ITEMS_LENGTH = 100; const DEFAULT_MAX_TO_SHOW_ITEMS = 10; afterEach(() => { cleanup(); }); describe('ItemsRoll', () => { it('renders with default', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const onItemClick = jest.fn(); const onItemRemove = jest.fn(); const props = propsFactory({ actions: ACTIONS, onSearch, onSearchClear, onClearAll, onChangeSelection, onItemClick, onItemRemove, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useFooter /> </DSProvider>, {} ); const searchInput = C.container.querySelector('.ant-input')!; // ASSERT expect(C.getByText(`${DEFAULT_ITEMS_LENGTH}`)).toBeInTheDocument(); expect(C.getByText('Change selection')).toBeInTheDocument(); expect(C.getByText(`${DEFAULT_MAX_TO_SHOW_ITEMS}`)).toBeInTheDocument(); expect(C.container.querySelectorAll(`.items-roll-list-item`).length).toBe(DEFAULT_MAX_TO_SHOW_ITEMS); expect(C.getByText(`Clear all`)).toBeInTheDocument(); expect(C.container.querySelectorAll('.ant-divider').length).toBe(2); expect(searchInput.getAttribute('placeholder')).toBe('Search...'); expect(searchInput).toHaveValue(''); // ACT const firstListItem = C.container.querySelectorAll('.items-roll-list-item')[0] as HTMLDivElement; fireEvent.mouseOver(firstListItem); const removeIcon = C.container.querySelector('.element-remove-icon') as HTMLDivElement; // ASSERT expect(removeIcon).toBeInTheDocument(); // ACT fireEvent.click(firstListItem); // ASSERT expect(onItemClick).toHaveBeenCalledTimes(1); // ACT fireEvent.click(removeIcon); // ASSERT expect(onItemRemove).toHaveBeenCalledTimes(1); // ACT const actionMenuTrigger = C.container.querySelector('.ant-dropdown-trigger') as HTMLElement; fireEvent.click(actionMenuTrigger); const actionMenu = C.getByTestId('items-roll-action-menu') as HTMLElement; // ASSERT expect(C.getByText('Import')).toBeInTheDocument(); expect(C.getByText('Export')).toBeInTheDocument(); expect(actionMenu.querySelectorAll('li').length).toBe(2); }); it('renders without change selection when onChangeSelection is NOT provided', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const props = propsFactory({ onSearch, onSearchClear, onClearAll, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useFooter /> </DSProvider>, {} ); // ASSERT expect(C.queryAllByText('Change selection').length).toBe(0); }); it('renders without actions menu', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const props = propsFactory({ onSearch, onSearchClear, onClearAll, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useFooter /> </DSProvider>, {} ); // ASSERT expect(C.container.querySelectorAll('.ant-dropdown-trigger').length).toBe(0); }); it('renders without footer', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const props = propsFactory({ onSearch, onSearchClear, onClearAll, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} /> </DSProvider>, {} ); // ASSERT expect(C.queryAllByTestId('items-roll-footer').length).toBe(0); }); it('renders with custom texts', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const props = propsFactory({ onSearch, onSearchClear, onClearAll, onChangeSelection, texts: { changeSelectionLabel: 'Custom Change Selection', } as any, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} /> </DSProvider>, {} ); // ASSERT expect(C.getByText('Custom Change Selection')).toBeInTheDocument(); }); it('renders with virtualized list', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const props = propsFactory({ onSearch, onSearchClear, onClearAll, onChangeSelection, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useVirtualizedList /> </DSProvider>, {} ); // ASSERT expect(C.getByTestId('items-roll-virtualized-list')).toBeInTheDocument(); }); it('renders with grouped list', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const groups = ['Params', 'Attributes']; const props = propsFactory( { onSearch, onSearchClear, onClearAll, onChangeSelection, }, { groups, } ); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} groups={groups} /> </DSProvider>, {} ); // ASSERT expect(C.getByText('Params')).toBeInTheDocument(); expect(C.getByText('Attributes')).toBeInTheDocument(); }); it('fire onSearch', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const props = propsFactory({ actions: ACTIONS, onSearch, onSearchClear, onClearAll, onChangeSelection, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useFooter /> </DSProvider>, {} ); const searchInput = C.container.querySelector('.ant-input') as HTMLElement; // ACT fireEvent.change(searchInput, { target: { value: '5' }, }); // ASSERT expect(onSearch).toHaveBeenCalledTimes(1); }); it('render Input with Value', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const props = propsFactory( { actions: ACTIONS, onSearch, onSearchClear, onClearAll, onChangeSelection, }, undefined, true ); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useFooter /> </DSProvider>, {} ); const searchInput = C.container.querySelector('.ant-input') as HTMLElement; // ASSERT expect(searchInput.getAttribute('value')).toBe('5'); }); it('fire onClearAll', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const props = propsFactory({ onSearch, onSearchClear, onClearAll, onChangeSelection, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useFooter /> </DSProvider>, {} ); const onClearAllButton = C.getByText('Clear all') as HTMLElement; // ACT fireEvent.click(onClearAllButton); const confirmBtn = document.querySelector('.ant-popover .ant-btn-primary') as HTMLButtonElement; fireEvent.click(confirmBtn); // ASSERT expect(onClearAll).toHaveBeenCalledTimes(1); }); it('fire onChangeSelection', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const props = propsFactory({ onSearch, onSearchClear, onClearAll, onChangeSelection, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} /> </DSProvider>, {} ); const onChangeSelectionButton = C.getByText('Change selection') as HTMLElement; // ACT fireEvent.click(onChangeSelectionButton); // ASSERT expect(onChangeSelection).toHaveBeenCalledTimes(1); }); it('renders with No results', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const props = propsFactory({ onSearch, onSearchClear, onClearAll, onChangeSelection, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} items={[]} useVirtualizedList /> </DSProvider>, {} ); // ASSERT expect(C.getByText('No results')).toBeInTheDocument(); }); it('renders with provided show more / less button', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const MAX_ITEMS_TO_SHOW = 22; const SHOW_MORE_STEP = 33; const props = propsFactory({ onSearch, onSearchClear, onClearAll, onChangeSelection, maxToShowItems: MAX_ITEMS_TO_SHOW, showMoreStep: SHOW_MORE_STEP, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useFooter /> </DSProvider>, {} ); // ASSERT expect(C.getByText(`${SHOW_MORE_STEP}`)).toBeInTheDocument(); expect(C.getByText(`${ITEM_TEXT}-${MAX_ITEMS_TO_SHOW - 1}`)).toBeInTheDocument(); }); it('renders with calculated show more button', () => { const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const SHOW_MORE_STEP = 200; const props = propsFactory({ onSearch, onSearchClear, onClearAll, onChangeSelection, showMoreStep: SHOW_MORE_STEP, }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} useFooter /> </DSProvider>, {} ); // ASSERT expect(C.getByText(`${SHOW_MORE_STEP - 100 - 10}`)).toBeInTheDocument(); }); it('renders withChangeSelectionDropdown', () => { const CHANGE_SELECTION_BTN = 'Change selection'; const onVisibleChange = jest.fn(); const onSearch = jest.fn(); const onSearchClear = jest.fn(); const onClearAll = jest.fn(); const onChangeSelection = jest.fn(); const changeSelectionDropdownProps = { overlay: <div>Overlay content</div>, trigger: ['click' as 'click'], onVisibleChange }; const props = propsFactory({ onSearch, onSearchClear, onClearAll, onChangeSelection, changeSelectionDropdownProps, // @ts-ignore texts: { changeSelectionLabel: CHANGE_SELECTION_BTN } }); // ARRANGE const C = renderWithProvider( <DSProvider locale="en" messages={messages}> <ItemsRoll {...props} /> </DSProvider>, {} ); // ACT fireEvent.click(C.getByText(CHANGE_SELECTION_BTN)); // ASSERT expect(onChangeSelection).toHaveBeenCalled(); expect(onVisibleChange).toHaveBeenCalled(); }); });
the_stack
import { version as v } from "../package.json"; const version: string = v; interface Opts { leftOutsideNot: string | string[]; leftOutside: string | string[]; leftMaybe: string | string[]; searchFor: string | string[]; rightMaybe: string | string[]; rightOutside: string | string[]; rightOutsideNot: string | string[]; i: { leftOutsideNot: boolean; leftOutside: boolean; leftMaybe: boolean; searchFor: boolean; rightMaybe: boolean; rightOutside: boolean; rightOutsideNot: boolean; }; } // astralAwareSearch() - searches for strings, returns the findings in an array function astralAwareSearch( whereToLook: string, whatToLookFor: string, opts?: { i?: boolean } ) { function existy(something: any): boolean { return something != null; } if ( typeof whereToLook !== "string" || whereToLook.length === 0 || typeof whatToLookFor !== "string" || whatToLookFor.length === 0 ) { return []; } const foundIndexArray = []; const arrWhereToLook = Array.from(whereToLook); const arrWhatToLookFor = Array.from(whatToLookFor); let found; for (let i = 0; i < arrWhereToLook.length; i++) { // check if current source character matches the first char of what we're looking for if (opts && opts.i) { if ( arrWhereToLook[i].toLowerCase() === arrWhatToLookFor[0].toLowerCase() ) { found = true; // this means first character matches // match the rest: for (let i2 = 0; i2 < arrWhatToLookFor.length; i2++) { if ( !existy(arrWhereToLook[i + i2]) || !existy(arrWhatToLookFor[i2]) || arrWhereToLook[i + i2].toLowerCase() !== arrWhatToLookFor[i2].toLowerCase() ) { found = false; break; } } if (found) { foundIndexArray.push(i); } } } else if (arrWhereToLook[i] === arrWhatToLookFor[0]) { found = true; // this means first character matches // match the rest: for (let i2 = 0; i2 < arrWhatToLookFor.length; i2++) { if (arrWhereToLook[i + i2] !== arrWhatToLookFor[i2]) { found = false; break; } } if (found) { foundIndexArray.push(i); } } } return foundIndexArray; } // =========================== /** * stringise/arrayiffy - Turns null/undefined into ''. If array, turns each elem into String. * all other cases, runs through String() * * @param {whatever} incoming can be anything * @return {String/Array} string or array of strings */ function stringise(incoming: any): string[] { function existy(something: any): boolean { return something != null; } if (!existy(incoming) || typeof incoming === "boolean") { return [""]; } if (Array.isArray(incoming)) { return incoming .filter((el) => existy(el) && typeof el !== "boolean") .map((el) => String(el)) .filter((el) => el.length > 0); } return [String(incoming)]; } // =========================== function iterateLeft( elem: string, arrSource: string[], foundBeginningIndex: number, i: boolean ): boolean { let matched = true; const charsArray = Array.from(elem); for (let i2 = 0, len = charsArray.length; i2 < len; i2++) { // iterate each character of particular Outside: if (i) { if ( charsArray[i2].toLowerCase() !== arrSource[ foundBeginningIndex - Array.from(elem).length + i2 ].toLowerCase() ) { matched = false; break; } } else if ( charsArray[i2] !== arrSource[foundBeginningIndex - Array.from(elem).length + i2] ) { matched = false; break; } } return matched; } function iterateRight( elem: string, arrSource: string[], foundEndingIndex: number, i: boolean ): boolean { let matched = true; const charsArray = Array.from(elem); for (let i2 = 0, len = charsArray.length; i2 < len; i2++) { // iterate each character of particular Outside: if (i) { if ( charsArray[i2].toLowerCase() !== arrSource[foundEndingIndex + i2].toLowerCase() ) { matched = false; break; } } else if (charsArray[i2] !== arrSource[foundEndingIndex + i2]) { matched = false; break; } } return matched; } // ____ // bug hammer | | // O=================| | // bugs into ham |____| // // .=O=. // ========================= // M A I N F U N C T I O N // ========================= function er( originalSource: string, options: Opts, originalReplacement: string ): string { const defaults = { i: { leftOutsideNot: false, leftOutside: false, leftMaybe: false, searchFor: false, rightMaybe: false, rightOutside: false, rightOutsideNot: false, }, }; const opts = { ...defaults, ...options }; // enforce the peace and order: const source = stringise(originalSource); opts.leftOutsideNot = stringise(opts.leftOutsideNot); opts.leftOutside = stringise(opts.leftOutside); opts.leftMaybe = stringise(opts.leftMaybe); opts.searchFor = String(opts.searchFor); opts.rightMaybe = stringise(opts.rightMaybe); opts.rightOutside = stringise(opts.rightOutside); opts.rightOutsideNot = stringise(opts.rightOutsideNot); const replacement = stringise(originalReplacement); const arrSource = Array.from(source[0]); let foundBeginningIndex; let foundEndingIndex; let matched; let found; const replacementRecipe: [number, number][] = []; let result = ""; // T H E L O O P const allResults = astralAwareSearch(source[0], opts.searchFor, { i: opts.i.searchFor, }); for ( let resIndex = 0, resLen = allResults.length; resIndex < resLen; resIndex++ ) { const oneOfFoundIndexes = allResults[resIndex]; // oneOfFoundIndexes is the index of starting index of found // the principle of replacement is after finding the searchFor string, // the boundaries optionally expand. That's left/right Maybe's from the // options object. When done, the outsides are checked, first positive // (leftOutside, rightOutside), then negative (leftOutsideNot, rightOutsideNot). // That's the plan. foundBeginningIndex = oneOfFoundIndexes; foundEndingIndex = oneOfFoundIndexes + Array.from(opts.searchFor).length; // // ===================== leftMaybe ===================== // commence with maybe's // they're not hungry, i.e. the whole Maybe must be of the left of searchFor exactly // /* istanbul ignore else */ if (opts.leftMaybe.length > 0) { for (let i = 0, len = opts.leftMaybe.length; i < len; i++) { // iterate each of the maybe's in the array: matched = true; const splitLeftMaybe = Array.from(opts.leftMaybe[i]); for (let i2 = 0, len2 = splitLeftMaybe.length; i2 < len2; i2++) { // iterate each character of particular Maybe: if (opts.i.leftMaybe) { if ( splitLeftMaybe[i2].toLowerCase() !== arrSource[ oneOfFoundIndexes - splitLeftMaybe.length + i2 ].toLowerCase() ) { matched = false; break; } } else if ( splitLeftMaybe[i2] !== arrSource[oneOfFoundIndexes - splitLeftMaybe.length + i2] ) { matched = false; break; } } if ( matched && oneOfFoundIndexes - splitLeftMaybe.length < foundBeginningIndex ) { foundBeginningIndex = oneOfFoundIndexes - splitLeftMaybe.length; } } } // ===================== rightMaybe ===================== /* istanbul ignore else */ if (opts.rightMaybe.length > 0) { for (let i = 0, len = opts.rightMaybe.length; i < len; i++) { // iterate each of the Maybe's in the array: matched = true; const splitRightMaybe = Array.from(opts.rightMaybe[i]); for (let i2 = 0, len2 = splitRightMaybe.length; i2 < len2; i2++) { // iterate each character of particular Maybe: if (opts.i.rightMaybe) { if ( splitRightMaybe[i2].toLowerCase() !== arrSource[ oneOfFoundIndexes + Array.from(opts.searchFor).length + i2 ].toLowerCase() ) { matched = false; break; } } else if ( splitRightMaybe[i2] !== arrSource[ oneOfFoundIndexes + Array.from(opts.searchFor).length + i2 ] ) { matched = false; break; } } if ( matched && foundEndingIndex < oneOfFoundIndexes + Array.from(opts.searchFor).length + splitRightMaybe.length ) { foundEndingIndex = oneOfFoundIndexes + Array.from(opts.searchFor).length + splitRightMaybe.length; } } } // ===================== leftOutside ===================== if (opts.leftOutside[0] !== "") { found = false; for (let i = 0, len = opts.leftOutside.length; i < len; i++) { // iterate each of the outsides in the array: matched = iterateLeft( opts.leftOutside[i], arrSource, foundBeginningIndex, opts.i.leftOutside ); if (matched) { found = true; } } if (!found) { continue; } } // ===================== rightOutside ===================== if (opts.rightOutside[0] !== "") { found = false; for (let i = 0, len = opts.rightOutside.length; i < len; i++) { // iterate each of the outsides in the array: matched = iterateRight( opts.rightOutside[i], arrSource, foundEndingIndex, opts.i.rightOutside ); if (matched) { found = true; } } if (!found) { continue; } } // ===================== leftOutsideNot ===================== if (opts.leftOutsideNot[0] !== "") { for (let i = 0, len = opts.leftOutsideNot.length; i < len; i++) { // iterate each of the outsides in the array: matched = iterateLeft( opts.leftOutsideNot[i], arrSource, foundBeginningIndex, opts.i.leftOutsideNot ); if (matched) { foundBeginningIndex = -1; foundEndingIndex = -1; break; } } if (foundBeginningIndex === -1) { continue; } } // ===================== rightOutsideNot ===================== if (opts.rightOutsideNot[0] !== "") { for (let i = 0, len = opts.rightOutsideNot.length; i < len; i++) { // iterate each of the outsides in the array: matched = iterateRight( opts.rightOutsideNot[i], arrSource, foundEndingIndex, opts.i.rightOutsideNot ); if (matched) { foundBeginningIndex = -1; foundEndingIndex = -1; break; } } if (foundBeginningIndex === -1) { continue; } } // ===================== the rest ===================== replacementRecipe.push([foundBeginningIndex, foundEndingIndex]); } // ===== // first we need to remove any overlaps in the recipe, cases like: // [ [0,10], [2,12] ] => [ [0,10], [10,12] ] if (replacementRecipe.length > 0) { replacementRecipe.forEach((_elem, i) => { // iterate through all replacement-recipe-array's elements: if ( replacementRecipe[i + 1] !== undefined && replacementRecipe[i][1] > replacementRecipe[i + 1][0] ) { replacementRecipe[i + 1][0] = replacementRecipe[i][1]; } }); // iterate the recipe array again, cleaning up elements like [12,12] replacementRecipe.forEach((elem, i) => { if (elem[0] === elem[1]) { replacementRecipe.splice(i, 1); } }); } else { // there were no findings, so return source return source.join(""); } // // iterate the recipe array and perform the replacement: // first, if replacements don't start with 0, attach this part onto result let: if (replacementRecipe.length > 0 && replacementRecipe[0][0] !== 0) { result += arrSource.slice(0, replacementRecipe[0][0]).join(""); } replacementRecipe.forEach((_elem, i) => { // first position is replacement string: result += replacement.join(""); if (replacementRecipe[i + 1] !== undefined) { // if next element exists, add content between current and next finding result += arrSource .slice(replacementRecipe[i][1], replacementRecipe[i + 1][0]) .join(""); } else { // if this is the last element in the replacement recipe array, add // remainder of the string after last replacement and the end: result += arrSource.slice(replacementRecipe[i][1]).join(""); } }); return result; } export { er, version };
the_stack
import { KubernetesObject } from "kpt-functions"; import * as apisMetaV1 from "./io.k8s.apimachinery.pkg.apis.meta.v1"; import * as pkgUtilIntstr from "./io.k8s.apimachinery.pkg.util.intstr"; // IPBlock describes a particular CIDR (Ex. "192.168.1.1/24") that is allowed to the pods matched by a NetworkPolicySpec's podSelector. The except entry describes CIDRs that should not be included within this rule. export class IPBlock { // CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24" public cidr: string; // Except is a slice of CIDRs that should not be included within an IP Block Valid examples are "192.168.1.1/24" Except values will be rejected if they are outside the CIDR range public except?: string[]; constructor(desc: IPBlock) { this.cidr = desc.cidr; this.except = desc.except; } } // NetworkPolicy describes what network traffic is allowed for a set of Pods export class NetworkPolicy implements KubernetesObject { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata public metadata: apisMetaV1.ObjectMeta; // Specification of the desired behavior for this NetworkPolicy. public spec?: NetworkPolicySpec; constructor(desc: NetworkPolicy.Interface) { this.apiVersion = NetworkPolicy.apiVersion; this.kind = NetworkPolicy.kind; this.metadata = desc.metadata; this.spec = desc.spec; } } export function isNetworkPolicy(o: any): o is NetworkPolicy { return ( o && o.apiVersion === NetworkPolicy.apiVersion && o.kind === NetworkPolicy.kind ); } export namespace NetworkPolicy { export const apiVersion = "networking.k8s.io/v1"; export const group = "networking.k8s.io"; export const version = "v1"; export const kind = "NetworkPolicy"; // named constructs a NetworkPolicy with metadata.name set to name. export function named(name: string): NetworkPolicy { return new NetworkPolicy({ metadata: { name } }); } // NetworkPolicy describes what network traffic is allowed for a set of Pods export interface Interface { // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata metadata: apisMetaV1.ObjectMeta; // Specification of the desired behavior for this NetworkPolicy. spec?: NetworkPolicySpec; } } // NetworkPolicyEgressRule describes a particular set of traffic that is allowed out of pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and to. This type is beta-level in 1.8 export class NetworkPolicyEgressRule { // List of destination ports for outgoing traffic. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. public ports?: NetworkPolicyPort[]; // List of destinations for outgoing traffic of pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all destinations (traffic not restricted by destination). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the to list. public to?: NetworkPolicyPeer[]; } // NetworkPolicyIngressRule describes a particular set of traffic that is allowed to the pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and from. export class NetworkPolicyIngressRule { // List of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least on item, this rule allows traffic only if the traffic matches at least one item in the from list. public from?: NetworkPolicyPeer[]; // List of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. public ports?: NetworkPolicyPort[]; } // NetworkPolicyList is a list of NetworkPolicy objects. export class NetworkPolicyList { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Items is a list of schema objects. public items: NetworkPolicy[]; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; // Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata public metadata?: apisMetaV1.ListMeta; constructor(desc: NetworkPolicyList) { this.apiVersion = NetworkPolicyList.apiVersion; this.items = desc.items.map(i => new NetworkPolicy(i)); this.kind = NetworkPolicyList.kind; this.metadata = desc.metadata; } } export function isNetworkPolicyList(o: any): o is NetworkPolicyList { return ( o && o.apiVersion === NetworkPolicyList.apiVersion && o.kind === NetworkPolicyList.kind ); } export namespace NetworkPolicyList { export const apiVersion = "networking.k8s.io/v1"; export const group = "networking.k8s.io"; export const version = "v1"; export const kind = "NetworkPolicyList"; // NetworkPolicyList is a list of NetworkPolicy objects. export interface Interface { // Items is a list of schema objects. items: NetworkPolicy[]; // Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata metadata?: apisMetaV1.ListMeta; } } // NetworkPolicyPeer describes a peer to allow traffic from. Only certain combinations of fields are allowed export class NetworkPolicyPeer { // IPBlock defines policy on a particular IPBlock. If this field is set then neither of the other fields can be. public ipBlock?: IPBlock; // Selects Namespaces using cluster-scoped labels. This field follows standard label selector semantics; if present but empty, it selects all namespaces. // // If PodSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector. public namespaceSelector?: apisMetaV1.LabelSelector; // This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods. // // If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects the Pods matching PodSelector in the policy's own Namespace. public podSelector?: apisMetaV1.LabelSelector; } // NetworkPolicyPort describes a port to allow traffic on export class NetworkPolicyPort { // The port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. public port?: pkgUtilIntstr.IntOrString; // The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this field defaults to TCP. public protocol?: string; } // NetworkPolicySpec provides the specification of a NetworkPolicy export class NetworkPolicySpec { // List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8 public egress?: NetworkPolicyEgressRule[]; // List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default) public ingress?: NetworkPolicyIngressRule[]; // Selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace. public podSelector: apisMetaV1.LabelSelector; // List of rule types that the NetworkPolicy relates to. Valid options are "Ingress", "Egress", or "Ingress,Egress". If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include "Egress" (since such a policy would not include an Egress section and would otherwise default to just [ "Ingress" ]). This field is beta-level in 1.8 public policyTypes?: string[]; constructor(desc: NetworkPolicySpec) { this.egress = desc.egress; this.ingress = desc.ingress; this.podSelector = desc.podSelector; this.policyTypes = desc.policyTypes; } }
the_stack
import './definition'; import PlSqlParser from './plsqlParser'; import * as iconv from 'iconv-lite'; import * as path from 'path'; import * as fs from 'fs'; export interface PLSQLCursorInfos { previousWord: string; currentWord: string; previousDot: boolean; } export class PlSqlNavigator { private static useEncoding = 'utf8'; public static setEncoding(encoding: string) { this.useEncoding = encoding; } public static goto(cursorInfos: PLSQLCursorInfos, lineOffset: number, parserRoot: PLSQLRoot, pkgGetName_cb, search_cb, findSpec?: boolean): Promise<PLSQLSymbol> { return new Promise<PLSQLSymbol>((resolve, reject) => { let cursorSymbol: PLSQLSymbol, rootSymbol: PLSQLSymbol, rootSymbol2: PLSQLSymbol, navigateSymbol: PLSQLSymbol, navigateSymbol2: PLSQLSymbol, isDeclaration: boolean, packageName: string; // Declaration if (/*!cursorInfos.previousDot &&*/ this.isPackageDeclaration(cursorInfos.previousWord)) { isDeclaration = true; cursorSymbol = PlSqlParser.findSymbolByNameOffset( parserRoot.symbols, cursorInfos.currentWord, lineOffset); if (cursorSymbol && cursorSymbol.parent) { if (findSpec && ((cursorSymbol.parent.kind === PLSQLSymbolKind.packageSpec) || [PLSQLSymbolKind.procedureSpec, PLSQLSymbolKind.functionSpec].includes(cursorSymbol.kind))) return resolve(); // switch in body (spec and body are in body) if (cursorSymbol.parent.kind !== PLSQLSymbolKind.packageSpec) { navigateSymbol = PlSqlParser.findSymbolByNameKind(cursorSymbol.parent.symbols, cursorSymbol.name, PlSqlParser.switchSymbolKind(cursorSymbol.kind), false); if (navigateSymbol) return resolve(navigateSymbol); } // switch body <-> spec rootSymbol = PlSqlParser.switchSymbol(cursorSymbol.parent); if (rootSymbol && rootSymbol !== cursorSymbol.parent) { navigateSymbol = PlSqlParser.findSymbolByNameKind(rootSymbol.symbols, cursorSymbol.name, PlSqlParser.switchSymbolKind(cursorSymbol.kind), false); return resolve(navigateSymbol); } else if (rootSymbol === cursorSymbol.parent) return resolve(); // No navigation here we are not in a package else // search in another file (spec && body are in separate files) packageName = cursorSymbol.parent.name; } else // No parent => a function or a procedure not in a package return resolve(); // Call } else { // Body => Body or Spec rootSymbol = PlSqlParser.findSymbolNearOffset(parserRoot.symbols, lineOffset, false); if (rootSymbol && rootSymbol.kind === PLSQLSymbolKind.packageSpec) return resolve(); // No navigation here we are in a spec packageName = cursorInfos.previousDot ? cursorInfos.previousWord : ''; // Use synonyme for package if (pkgGetName_cb) packageName = pkgGetName_cb.call(this, packageName); // Search in current file if (rootSymbol && (!packageName || (packageName.toLowerCase() === rootSymbol.name.toLowerCase()))) { // Search in current body of file (recursive for subFunctions or subProcedure) navigateSymbol = PlSqlParser.findSymbolByNameOffset(rootSymbol.symbols, cursorInfos.currentWord, 0, true); if (navigateSymbol) { if ((!findSpec && PlSqlParser.isSymbolSpec(navigateSymbol)) || (findSpec && !PlSqlParser.isSymbolSpec(navigateSymbol))) navigateSymbol2 = PlSqlParser.findSymbolByNameKind(rootSymbol.symbols, navigateSymbol.name, PlSqlParser.switchSymbolKind(navigateSymbol.kind), false); if (!findSpec) return resolve(navigateSymbol2 || navigateSymbol); else navigateSymbol = navigateSymbol2 || navigateSymbol; } // Search in current spec (maybe a constant or type definition) rootSymbol2 = PlSqlParser.switchSymbol(rootSymbol); if (rootSymbol2 && rootSymbol2 !== rootSymbol) { navigateSymbol = PlSqlParser.findSymbolByNameOffset(rootSymbol2.symbols, cursorInfos.currentWord, 0, false) || navigateSymbol; if (navigateSymbol) return resolve(navigateSymbol); } else if (!packageName && !rootSymbol2 && rootSymbol.kind === PLSQLSymbolKind.packageBody) { // spec is in separate file packageName = rootSymbol.name; } } } // Search in external files const search = { package: packageName, cursorWord: cursorInfos.currentWord, isDeclaration: isDeclaration, priority: isDeclaration ? null : (findSpec ? PLSQLSymbolKind.packageSpec : PLSQLSymbolKind.packageBody) }; this.searchExternal(search, search_cb, this.gotoFile) .then(symbol => resolve(symbol)) .catch(err => reject(err)); }); } public static getCursorInfos(currentWord: string, endOffset: number, line: string): PLSQLCursorInfos { let previousWord = null, previousDot = false; if (this.isPackageDeclaration(currentWord)) { const regexp = new RegExp(/(?:^\s+)?([\w\$#]+)/i); const found = regexp.exec(line.substr(endOffset)); if (found) { previousWord = currentWord; currentWord = found[1]; } else currentWord = null; } else { const regexp = new RegExp(`([\\w\\$#]+)(\\s+|.)(\")?${currentWord.replace(/[\$#]/g, '\\$&')}(\")?$`); const found = regexp.exec(line.substr(0, endOffset)); if (found) { previousWord = found[1]; previousDot = found[2] === '.'; if (found[3] || found[4]) currentWord = `"${currentWord}"`; } } return { previousWord, currentWord, previousDot }; } public static complete(cursorInfos: PLSQLCursorInfos, pkgGetName_cb, search_cb): Promise<PLSQLSymbol[]> { return new Promise<PLSQLSymbol[]>((resolve, reject) => { const search = { package: cursorInfos.previousWord, cursorWord: cursorInfos.currentWord, mode: 'complete' }; this.searchExternal(search, search_cb, this.completeItem) .then(symbols => resolve(symbols)) .catch(err => reject(err)); }); } private static isPackageDeclaration(text) { return text && ['function', 'procedure'].includes(text.toLowerCase()); } private static async searchExternal(search, search_cb, parseFn): Promise<any> { const globCmd = this.getGlobCmd(search, search_cb); for (let searchFld of globCmd.searchFld) { globCmd.params.cwd = searchFld; const resultSearch = await this.searchExternalGlob(globCmd, {...search}, parseFn); if (resultSearch) return resultSearch; // else continue with next globSearch } } private static searchExternalGlob(globCmd, search, parseFn): Promise<any> { return new Promise<any>((resolve, reject) => { let files; this.getGlobFiles(globCmd) .then(globFiles => { files = globFiles; return this.parseFiles(files, search, parseFn); }) .then(symbol => { // search without packageName (because it's perhaps only the name of the schema) if (!symbol && search.package && search.mode !== 'complete') { search.package = null; return this.parseFiles(files, search, parseFn); } return symbol; }) .then(symbol => { resolve(symbol); }) .catch(err => { reject(err); }); }); } private static getGlobFiles(globCmd): Promise<string[]> { const glob = require('glob'); return new Promise((resolve, reject) => { if (!globCmd.params.cwd) return reject('No current directory for glob search !'); glob(globCmd.glob, globCmd.params, (err, files) => { if (err) return reject(err); return resolve(files .map(file => path.join(globCmd.params.cwd, file)) .filter(file => file !== globCmd.current && globCmd.ext.includes(path.extname(file).toLowerCase().substr(1)) ) ); }); }); } private static getGlobCmd(searchTexts, cb): any { let files: string[] = []; if (searchTexts.package) files.push(searchTexts.package); if (searchTexts.cursorWord) files.push(searchTexts.cursorWord); let search = { files: files, glob: undefined, ext: ['sql','ddl','dml','pkh','pks','pkb','pck','pls','plb'], params: { nocase: true } }; search = cb.call(this, search); let searchTxt; if (search.files.length > 1) searchTxt = `{${search.files.join(',')}}`; else searchTxt = search.files[0]; // search.glob = `**/*${searchTxt}*.{${search.ext.join(',')}}`; search.glob = `**/*${searchTxt}*.*`; // filter on extension is made after => faster return search; } private static parseFiles(files: string[], searchInfos, func): Promise<any> { return new Promise((resolve, reject) => { const me = this; let latestSymbol; (function process(index) { if (index >= files.length) { return resolve(); } me.readFile(files[index]) .then(rootSymbol => { const navigateSymbol = func.call(this, searchInfos, rootSymbol); if (navigateSymbol.continue) { latestSymbol = navigateSymbol.symbol; process(index + 1); } else resolve(navigateSymbol.symbol || latestSymbol); }) .catch(errParse => { // an error with this file reject(errParse); }); })(0); }); } private static completeItem(searchInfos, rootSymbol: PLSQLRoot): any { // TODO: return current package body private func/proc/spec const parentSymbol = PlSqlParser.findSymbolByNameKind(rootSymbol.symbols, searchInfos.package, [PLSQLSymbolKind.packageSpec], false); if (parentSymbol) return {symbol: parentSymbol.symbols}; else return {continue: true}; // return null for continue search with next file } private static gotoFile(searchInfos, rootSymbol: PLSQLRoot): any { let parentSymbol, navigateSymbol, symbols: PLSQLSymbol[]; if (searchInfos.package) { parentSymbol = PlSqlParser.findSymbolByNameKind(rootSymbol.symbols, searchInfos.package, [PLSQLSymbolKind.packageSpec, PLSQLSymbolKind.packageBody], false); if (parentSymbol) symbols = parentSymbol.symbols; // else continue search, package is not in this file } else symbols = rootSymbol.symbols; if (symbols) { navigateSymbol = PlSqlParser.findSymbolByNameOffset(symbols, searchInfos.cursorWord, 0, false); if (navigateSymbol) { if (navigateSymbol.parent && ((searchInfos.priority === PLSQLSymbolKind.packageSpec && navigateSymbol.parent.kind === PLSQLSymbolKind.packageBody && [PLSQLSymbolKind.function, PLSQLSymbolKind.procedure].includes(navigateSymbol.kind)) || (searchInfos.priority === PLSQLSymbolKind.packageBody && navigateSymbol.parent.kind === PLSQLSymbolKind.packageSpec && [PLSQLSymbolKind.functionSpec, PLSQLSymbolKind.procedureSpec].includes(navigateSymbol.kind)))) { parentSymbol = PlSqlParser.switchSymbol(navigateSymbol.parent); if (parentSymbol && parentSymbol !== navigateSymbol.parent) return {symbol: PlSqlParser.findSymbolByNameOffset(parentSymbol.symbols, searchInfos.cursorWord, 0, false) || navigateSymbol}; else return {symbol: navigateSymbol, continue: true}; // continue search, body and spec are in a different file } else return {symbol: navigateSymbol}; } } return {continue: true}; } private static readFile(file: string): Promise<PLSQLRoot> { return new Promise((resolve, reject) => { fs.readFile(file, (err, data) => { if (err) return reject(err); let dataS = ''; if (this.useEncoding === 'utf8') dataS = data.toString(); else dataS = iconv.decode(data, this.useEncoding); return resolve(PlSqlParser.parseFile(file, dataS)); }); }); } }
the_stack
import React, { Component } from 'react'; import { StyleSheet, Text, View, NativeEventEmitter, ScrollView, TouchableOpacity, Alert, } from 'react-native'; import type { EmitterSubscription, ColorValue } from 'react-native'; import Kontakt, { KontaktModule } from 'react-native-kontaktio'; import type { RegionType, IBeaconIos, IBeaconIosDiscoveryWithMajorMinor, } from 'react-native-kontaktio'; const { init, configure, // authorization getAuthorizationStatus, requestWhenInUseAuthorization, requestAlwaysAuthorization, // discovery startDiscovery, stopDiscovery, restartDiscovery, // ranging startRangingBeaconsInRegion, stopRangingBeaconsInRegion, stopRangingBeaconsInAllRegions, getRangedRegions, // monitoring startMonitoringForRegion, stopMonitoringForRegion, stopMonitoringForAllRegions, getMonitoredRegions, } = Kontakt; const kontaktEmitter = new NativeEventEmitter(KontaktModule); const region1: RegionType = { identifier: 'Test beacons 1', uuid: 'B0702880-A295-A8AB-F734-031A98A512DE', major: 1, // no minor provided: will detect all minors }; const region2: RegionType = { identifier: 'Test beacons 2', uuid: 'B0702880-A295-A8AB-F734-031A98A512DE', major: 2, // no minor provided: will detect all minors }; type State = { scanning: boolean; ranging: boolean; monitoring: boolean; discoveredBeacons: Array<IBeaconIosDiscoveryWithMajorMinor>; rangedBeacons: Array<IBeaconIos>; rangedRegions: Array<RegionType>; monitoredRegions: Array<RegionType>; monitoredRegionsCloseBy: Array<RegionType>; authorizationStatus: string; }; export default class IBeaconExample extends Component<{}, State> { state: State = { scanning: false, ranging: false, monitoring: false, discoveredBeacons: [], rangedBeacons: [], rangedRegions: [], monitoredRegions: [], monitoredRegionsCloseBy: [], authorizationStatus: '', }; startMonitoringSubscription: EmitterSubscription | null = null; monitoringFailSubscription: EmitterSubscription | null = null; regionEnterSubscription: EmitterSubscription | null = null; regionExitSubscription: EmitterSubscription | null = null; regionRangeSubscription: EmitterSubscription | null = null; regionRangeFailSubscription: EmitterSubscription | null = null; authorizationSubscription: EmitterSubscription | null = null; discoverSubscription: EmitterSubscription | null = null; discoverFailSubscription: EmitterSubscription | null = null; componentDidMount() { // Initialization, configuration and adding of beacon regions init('MY_KONTAKTIO_API_KEY') .then(() => configure({ dropEmptyRanges: true, // don't trigger beacon events in case beacon array is empty invalidationAge: 5000, // time to forget lost beacon // connectNearbyBeacons: false, // true not working yet }) ) .then(() => this._requestAlwaysAuthorization()) // .then(() => requestWhenInUseAuthorization()) .then(() => console.log( 'Successfully initialized beacon ranging, monitoring and scanning' ) ) .catch((error) => console.log('error', error)); // Monitoring events this.startMonitoringSubscription = kontaktEmitter.addListener( 'didStartMonitoringForRegion', ({ region }) => { console.log('didStartMonitoringForRegion', region); } ); this.monitoringFailSubscription = kontaktEmitter.addListener( 'monitoringDidFailForRegion', ({ region, error }) => console.log('monitoringDidFailForRegion', region, error) ); this.regionEnterSubscription = kontaktEmitter.addListener( 'didEnterRegion', ({ region }) => { console.log('didEnterRegion', region); this.setState({ monitoredRegionsCloseBy: this.state.monitoredRegionsCloseBy.concat(region), }); } ); this.regionExitSubscription = kontaktEmitter.addListener( 'didExitRegion', ({ region: exitRegion }) => { console.log('didExitRegion', exitRegion); const { monitoredRegionsCloseBy } = this.state; const index = monitoredRegionsCloseBy.findIndex((region) => this._isIdenticalRegion(exitRegion, region) ); this.setState({ monitoredRegionsCloseBy: monitoredRegionsCloseBy.reduce< Array<RegionType> >((result, val, ind) => { // don't add disappeared region to array if (ind === index) return result; // add all other regions to array else { result.push(val); return result; } }, []), }); } ); // Ranging event this.regionRangeSubscription = kontaktEmitter.addListener( 'didRangeBeacons', ({ beacons: rangedBeacons, region }) => { console.log('didRangeBeacons', rangedBeacons, region); this.setState({ rangedBeacons }); } ); this.regionRangeFailSubscription = kontaktEmitter.addListener( 'rangingDidFailForRegion', ({ region, error }) => console.log('rangingDidFailForRegion', region, error) ); // Authorization event this.authorizationSubscription = kontaktEmitter.addListener( 'authorizationStatusDidChange', ({ status }) => { console.log('authorizationStatusDidChange', status); this.setState({ authorizationStatus: status }); } ); // Discovery event this.discoverSubscription = kontaktEmitter.addListener( 'didDiscoverDevices', ({ beacons: discoveredBeacons }) => { console.log('didDiscoverDevices', discoveredBeacons); this.setState({ discoveredBeacons }); } ); this.discoverFailSubscription = kontaktEmitter.addListener( 'discoveryDidFail', ({ error }) => console.log('discoveryDidFail', error) ); } componentWillUnmount() { this.startMonitoringSubscription?.remove(); this.monitoringFailSubscription?.remove(); this.regionEnterSubscription?.remove(); this.regionExitSubscription?.remove(); this.regionRangeSubscription?.remove(); this.regionRangeFailSubscription?.remove(); this.authorizationSubscription?.remove(); this.discoverSubscription?.remove(); this.discoverFailSubscription?.remove(); } /* --- Discovering beacons --- */ _startDiscovery = () => { startDiscovery({ interval: 1000 }) .then(() => this.setState({ scanning: true, discoveredBeacons: [] })) .then(() => console.log('started discovery')) .catch((error) => console.log('[startDiscovery]', error)); }; _stopDiscovery = () => { stopDiscovery() .then(() => this.setState({ scanning: false, discoveredBeacons: [] })) .then(() => console.log('stopped discovery')) .catch((error) => console.log('[stopDiscovery]', error)); }; _restartDiscovery = () => { restartDiscovery() .then(() => this.setState({ scanning: true, discoveredBeacons: [] })) .then(() => console.log('restarted discovery')) .catch((error) => console.log('[restartDiscovery]', error)); }; /* --- Ranging beacons --- */ _startRanging = () => { startRangingBeaconsInRegion(region1) .then(() => this.setState({ ranging: true, rangedBeacons: [] })) .then(() => console.log('started ranging')) .catch((error) => console.log('[startRanging]', error)); }; _stopRanging = () => { stopRangingBeaconsInRegion(region1) .then(() => this.setState({ ranging: false, rangedBeacons: [] })) .then(() => console.log('stopped ranging')) .catch((error) => console.log('[stopRanging]', error)); }; _stopAllRanging = () => { stopRangingBeaconsInAllRegions() .then(() => this.setState({ ranging: false, rangedBeacons: [] })) .then(() => console.log('stopped ranging in all regions')) .catch((error) => console.log('[stopAllRanging]', error)); }; /* --- Monitoring beacons --- */ _startMonitoring = () => { startMonitoringForRegion(region1) .then(() => this.setState({ monitoring: true })) .then(() => console.log('started monitoring')) .catch((error) => console.log('[startMonitoring]', error)); }; _stopMonitoring = () => { stopMonitoringForRegion(region1) .then(() => this.setState({ monitoring: false })) .then(() => console.log('stopped monitoring')) .catch((error) => console.log('[stopRanging]', error)); }; _stopAllMonitoring = () => { stopMonitoringForAllRegions() .then(() => this.setState({ monitoring: false })) .then(() => console.log('stopped monitoring in all regions')) .catch((error) => console.log('[stopAllMonitoring]', error)); }; /* --- Authorization --- */ _getAuthorizationStatus = () => { getAuthorizationStatus() .then((authorizationStatus) => { Alert.alert(`Authorization status: ${authorizationStatus}`); console.log(`Authorization status: ${authorizationStatus}`); }) .catch((error) => console.log('[getAuthorizationStatus]', error)); }; _requestAlwaysAuthorization = () => { requestAlwaysAuthorization() .then(() => console.log('requested always authorization')) .catch((error) => console.log('[requestAlwaysAuthorization]', error)); }; _requestWhenInUseAuthorization = () => { requestWhenInUseAuthorization() .then(() => console.log('requested when in use authorization')) .catch((error) => console.log('[requestWhenInUseAuthorization]', error)); }; /* --- Regions --- */ _getRangedRegions = () => { getRangedRegions() .then((regions) => this.setState({ rangedRegions: regions })) .then(() => console.log('got ranged regions')) .catch((error) => console.log('[getRangedRegions]', error)); }; _getMonitoredRegions = () => { getMonitoredRegions() .then((regions) => this.setState({ monitoredRegions: regions })) .then(() => console.log('got monitored regions')) .catch((error) => console.log('[getMonitoredRegions]', error)); }; /** * Helper function used to identify equal regions */ _isIdenticalRegion = (r1: RegionType, r2: RegionType) => r1.identifier === r2.identifier; /* --- Render methods --- */ _renderDiscoveredBeacons = () => { const colors = ['#F7C376', '#EFF7B7', '#F4CDED', '#A2C8F9', '#AAF7AF']; return this.state.discoveredBeacons .sort( ( a: IBeaconIosDiscoveryWithMajorMinor, b: IBeaconIosDiscoveryWithMajorMinor ) => a.rssi - b.rssi ) .map( (beacon: IBeaconIosDiscoveryWithMajorMinor, index: number) => ( <View key={index} style={[ styles.beacon, { backgroundColor: colors[beacon.minor ? beacon.minor - 1 : 0] }, ]} > <Text style={{ fontWeight: 'bold' }}>{beacon.uniqueId}</Text> <Text> Battery Power: {beacon.batteryLevel}, TxPower:{' '} {beacon.transmissionPower} </Text> <Text> Model: {beacon.model}, RSSI: {beacon.rssi} </Text> <Text> FirmwareVersion: {beacon.firmwareVersion}, Name: {beacon.name} </Text> <Text> Locked: {beacon.locked ? 'Yes' : 'No'}, Shuffled:{' '} {beacon.shuffled ? 'Yes' : 'No'} </Text> <Text>updatedAt: {beacon.updatedAt}</Text> </View> ), this ); }; _renderRangedBeacons = () => { const colors = ['#F7C376', '#EFF7B7', '#F4CDED', '#A2C8F9', '#AAF7AF']; return this.state.rangedBeacons .sort( (a: IBeaconIos, b: IBeaconIos) => parseInt(a.accuracy) - parseInt(b.accuracy) ) .map( (beacon: IBeaconIos, index: number) => ( <View key={index} style={[ styles.beacon, { backgroundColor: colors[beacon.minor - 1] }, ]} > <Text style={{ fontWeight: 'bold' }}>{beacon.uuid}</Text> <Text> Major: {beacon.major}, Minor: {beacon.minor} </Text> <Text> RSSI: {beacon.rssi}, Proximity: {beacon.proximity} </Text> <Text>Distance: {beacon.accuracy}</Text> </View> ), this ); }; _renderMonitoredRegions = () => { const colors = ['#F7C376', '#EFF7B7', '#F4CDED', '#A2C8F9', '#AAF7AF']; return this.state.monitoredRegionsCloseBy.map( (region: RegionType, index: number) => ( <View key={index} style={[ styles.beacon, { backgroundColor: colors[region.major ? region.major - 1 : 0] }, ]} > <Text style={{ fontWeight: 'bold' }}>{region.identifier}</Text> <Text>UUID: {region.uuid}</Text> <Text> Major: {region.major}, Minor: {region.minor} </Text> </View> ), this ); }; _renderRegions = () => { const { rangedRegions, monitoredRegions } = this.state; return ( <View> <Text style={{ color: '#ABE88D' }}> {rangedRegions !== [] ? rangedRegions.reduce( (result, region: RegionType) => result + region.identifier + ', ', '' ) : 'No ranged regions'} </Text> <Text style={{ color: '#F48661' }}> {monitoredRegions !== [] ? monitoredRegions.reduce( (result, region: RegionType) => result + region.identifier + ', ', '' ) : 'No monitored regions'} </Text> </View> ); }; _renderEmpty = () => { const { scanning, ranging, monitoring, discoveredBeacons, rangedBeacons, monitoredRegionsCloseBy, } = this.state; let text = ''; if (!scanning && !ranging && !monitoring) text = 'Start scanning to listen for beacon signals!'; if (scanning && !discoveredBeacons.length) text = 'No beacons discovered yet...'; if (ranging && !rangedBeacons.length) text = 'No beacons ranged yet...'; if (monitoring && !monitoredRegionsCloseBy.length) text = 'No monitored regions in your proximity...'; return text ? ( <View style={styles.textContainer}> <Text style={styles.text}>{text}</Text> </View> ) : null; }; _renderAuthorizationStatusText = () => { const { authorizationStatus } = this.state; return authorizationStatus ? ( <View style={styles.textContainer}> <Text style={[styles.text, { color: 'red' }]}> {authorizationStatus} </Text> </View> ) : null; }; _renderButton = ( text: string, onPress: () => void, backgroundColor: ColorValue ) => ( <TouchableOpacity style={[styles.button, { backgroundColor }]} onPress={onPress} > <Text>{text}</Text> </TouchableOpacity> ); render() { const { scanning, ranging, monitoring, discoveredBeacons, rangedBeacons, monitoredRegionsCloseBy, } = this.state; return ( <View style={styles.container}> <View style={styles.buttonContainer}> {this._renderButton( 'Start discovery', this._startDiscovery, '#84e2f9' )} {this._renderButton('Stop', this._stopDiscovery, '#84e2f9')} {this._renderButton('Restart', this._restartDiscovery, '#84e2f9')} </View> <View style={styles.buttonContainer}> {this._renderButton('Start ranging', this._startRanging, '#ABE88D')} {this._renderButton('Stop', this._stopRanging, '#ABE88D')} {this._renderButton('Stop all', this._stopAllRanging, '#ABE88D')} </View> <View style={styles.buttonContainer}> {this._renderButton( 'Start monitoring', this._startMonitoring, '#F48661' )} {this._renderButton('Stop', this._stopMonitoring, '#F48661')} {this._renderButton('Stop all', this._stopAllMonitoring, '#F48661')} </View> <View style={styles.buttonContainer}> {this._renderButton( 'Get Status', this._getAuthorizationStatus, '#F4ED5A' )} {this._renderAuthorizationStatusText()} </View> <View style={styles.buttonContainer}> {this._renderButton( 'Ranged regions', this._getRangedRegions, '#ABE88D' )} {this._renderButton( 'Monitored regions', this._getMonitoredRegions, '#F48661' )} </View> {this._renderRegions()} <ScrollView> {this._renderEmpty()} {scanning && !!discoveredBeacons.length && this._renderDiscoveredBeacons()} {ranging && !!rangedBeacons.length && this._renderRangedBeacons()} {monitoring && !!monitoredRegionsCloseBy.length && this._renderMonitoredRegions()} </ScrollView> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, marginTop: 20, // statusbarHeight }, beacon: { justifyContent: 'space-around', alignItems: 'center', padding: 10, }, textContainer: { alignItems: 'center', }, text: { fontSize: 18, fontWeight: 'bold', }, buttonContainer: { marginVertical: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', }, button: { padding: 10, borderRadius: 10, }, });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/registeredServersMappers"; import * as Parameters from "../models/parameters"; import { StorageSyncManagementClientContext } from "../storageSyncManagementClientContext"; /** Class representing a RegisteredServers. */ export class RegisteredServers { private readonly client: StorageSyncManagementClientContext; /** * Create a RegisteredServers. * @param {StorageSyncManagementClientContext} client Reference to the service client. */ constructor(client: StorageSyncManagementClientContext) { this.client = client; } /** * Get a given registered server list. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param [options] The optional parameters * @returns Promise<Models.RegisteredServersListByStorageSyncServiceResponse> */ listByStorageSyncService(resourceGroupName: string, storageSyncServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.RegisteredServersListByStorageSyncServiceResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param callback The callback */ listByStorageSyncService(resourceGroupName: string, storageSyncServiceName: string, callback: msRest.ServiceCallback<Models.RegisteredServerArray>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param options The optional parameters * @param callback The callback */ listByStorageSyncService(resourceGroupName: string, storageSyncServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RegisteredServerArray>): void; listByStorageSyncService(resourceGroupName: string, storageSyncServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RegisteredServerArray>, callback?: msRest.ServiceCallback<Models.RegisteredServerArray>): Promise<Models.RegisteredServersListByStorageSyncServiceResponse> { return this.client.sendOperationRequest( { resourceGroupName, storageSyncServiceName, options }, listByStorageSyncServiceOperationSpec, callback) as Promise<Models.RegisteredServersListByStorageSyncServiceResponse>; } /** * Get a given registered server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId GUID identifying the on-premises server. * @param [options] The optional parameters * @returns Promise<Models.RegisteredServersGetResponse> */ get(resourceGroupName: string, storageSyncServiceName: string, serverId: string, options?: msRest.RequestOptionsBase): Promise<Models.RegisteredServersGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId GUID identifying the on-premises server. * @param callback The callback */ get(resourceGroupName: string, storageSyncServiceName: string, serverId: string, callback: msRest.ServiceCallback<Models.RegisteredServer>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId GUID identifying the on-premises server. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, storageSyncServiceName: string, serverId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RegisteredServer>): void; get(resourceGroupName: string, storageSyncServiceName: string, serverId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RegisteredServer>, callback?: msRest.ServiceCallback<Models.RegisteredServer>): Promise<Models.RegisteredServersGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, storageSyncServiceName, serverId, options }, getOperationSpec, callback) as Promise<Models.RegisteredServersGetResponse>; } /** * Add a new registered server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId GUID identifying the on-premises server. * @param parameters Body of Registered Server object. * @param [options] The optional parameters * @returns Promise<Models.RegisteredServersCreateResponse> */ create(resourceGroupName: string, storageSyncServiceName: string, serverId: string, parameters: Models.RegisteredServerCreateParameters, options?: msRest.RequestOptionsBase): Promise<Models.RegisteredServersCreateResponse> { return this.beginCreate(resourceGroupName,storageSyncServiceName,serverId,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.RegisteredServersCreateResponse>; } /** * Delete the given registered server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId GUID identifying the on-premises server. * @param [options] The optional parameters * @returns Promise<Models.RegisteredServersDeleteResponse> */ deleteMethod(resourceGroupName: string, storageSyncServiceName: string, serverId: string, options?: msRest.RequestOptionsBase): Promise<Models.RegisteredServersDeleteResponse> { return this.beginDeleteMethod(resourceGroupName,storageSyncServiceName,serverId,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.RegisteredServersDeleteResponse>; } /** * Triggers Server certificate rollover. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId Server Id * @param parameters Body of Trigger Rollover request. * @param [options] The optional parameters * @returns Promise<Models.RegisteredServersTriggerRolloverResponse> */ triggerRollover(resourceGroupName: string, storageSyncServiceName: string, serverId: string, parameters: Models.TriggerRolloverRequest, options?: msRest.RequestOptionsBase): Promise<Models.RegisteredServersTriggerRolloverResponse> { return this.beginTriggerRollover(resourceGroupName,storageSyncServiceName,serverId,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.RegisteredServersTriggerRolloverResponse>; } /** * Add a new registered server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId GUID identifying the on-premises server. * @param parameters Body of Registered Server object. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreate(resourceGroupName: string, storageSyncServiceName: string, serverId: string, parameters: Models.RegisteredServerCreateParameters, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, storageSyncServiceName, serverId, parameters, options }, beginCreateOperationSpec, options); } /** * Delete the given registered server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId GUID identifying the on-premises server. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, storageSyncServiceName: string, serverId: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, storageSyncServiceName, serverId, options }, beginDeleteMethodOperationSpec, options); } /** * Triggers Server certificate rollover. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param serverId Server Id * @param parameters Body of Trigger Rollover request. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginTriggerRollover(resourceGroupName: string, storageSyncServiceName: string, serverId: string, parameters: Models.TriggerRolloverRequest, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, storageSyncServiceName, serverId, parameters, options }, beginTriggerRolloverOperationSpec, options); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByStorageSyncServiceOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/registeredServers", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.RegisteredServerArray, headersMapper: Mappers.RegisteredServersListByStorageSyncServiceHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/registeredServers/{serverId}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName, Parameters.serverId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.RegisteredServer, headersMapper: Mappers.RegisteredServersGetHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer }; const beginCreateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/registeredServers/{serverId}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName, Parameters.serverId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.RegisteredServerCreateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.RegisteredServer, headersMapper: Mappers.RegisteredServersCreateHeaders }, 202: { headersMapper: Mappers.RegisteredServersCreateHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/registeredServers/{serverId}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName, Parameters.serverId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { headersMapper: Mappers.RegisteredServersDeleteHeaders }, 202: { headersMapper: Mappers.RegisteredServersDeleteHeaders }, 204: { headersMapper: Mappers.RegisteredServersDeleteHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer }; const beginTriggerRolloverOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/registeredServers/{serverId}/triggerRollover", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName, Parameters.serverId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.TriggerRolloverRequest, required: true } }, responses: { 200: { headersMapper: Mappers.RegisteredServersTriggerRolloverHeaders }, 202: { headersMapper: Mappers.RegisteredServersTriggerRolloverHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer };
the_stack
import chalk from 'chalk'; import fs from 'fs'; import glob from 'glob'; import path from 'path'; import rlSync from 'readline-sync'; import urljoin from 'url-join'; import { ScJssConfig, JssConfiguration } from '../resolve-scjssconfig'; import { findAppNameInConfig } from './find-app-name'; import { createSecretPatchContents, writeSecretPatchFile } from './secret-patch'; const userConfigFileName = 'scjssconfig.json'; export const userConfigPath = path.resolve(process.cwd(), userConfigFileName); /** * @param {string | undefined} initialData * @param {boolean} allowInteraction * @param {string} paramName * @param {string} prompt * @param {string} examplePrompt * @param {RegExp} [validation] * @param {string} [validationMessage] * @param {boolean} skipValidationIfNonInteractive */ function getInteractiveData( initialData: string | undefined, allowInteraction: boolean, paramName: string, prompt: string, examplePrompt: string, validation?: RegExp, validationMessage?: string, skipValidationIfNonInteractive = false ): string { if (!allowInteraction && !initialData && !skipValidationIfNonInteractive) { throw new Error(`Non interactive mode specified and ${paramName} not provided.`); } if (allowInteraction) { const finalPrompt = initialData ? `${prompt} [${initialData}]: ` : `${prompt} ${examplePrompt}: `; return rlSync.question(finalPrompt, { defaultInput: initialData, limit: validation, limitMessage: validationMessage, }); } const result = initialData as string; if (validation && validationMessage && !validation.test(result)) { if (skipValidationIfNonInteractive) { console.error(chalk.yellow(validationMessage)); } else { throw new Error(validationMessage); } } return result; } /** * @param {boolean} interactive * @param {string} outputFile * @param {JssConfiguration} [initialData] * @param {string} [configName] */ export function setup( interactive: boolean, outputFile?: string, initialData?: JssConfiguration, configName = 'sitecore' ) { const getValidation = (regexp: RegExp) => (initialData?.skipValidation ? undefined : regexp); let config: ScJssConfig = { sitecore: { instancePath: '', }, }; if (!outputFile) { outputFile = userConfigPath; } // read in any existing config file so that we can keep its values if (outputFile && fs.existsSync(outputFile)) { try { const existingFile = fs.readFileSync(outputFile, 'utf8'); const existingJson = JSON.parse(existingFile) as ScJssConfig; console.log( chalk.green( `Found existing ${outputFile}. The existing config will become defaults in this setup session.` ) ); config = existingJson; } catch (e) { console.warn( chalk.yellow( `Found existing ${outputFile} but error reading it. Existing values will be ignored.` ), e ); } } const existingConfigObject = config[configName] || ({} as JssConfiguration); // merge existing values with any CLI arguments (which should override any preexisting values) if (initialData) { config[configName] = { ...config[configName], instancePath: initialData.instancePath || existingConfigObject.instancePath, apiKey: initialData.apiKey || existingConfigObject.apiKey, deploySecret: initialData.deploySecret || existingConfigObject.deploySecret, deployUrl: initialData.deployUrl || existingConfigObject.deployUrl, layoutServiceHost: initialData.layoutServiceHost || existingConfigObject.layoutServiceHost, }; } const configObject = config[configName]; // INSTANCE PATH const getInstancePath = (initialPath?: string) => { configObject.instancePath = getInteractiveData( initialPath, interactive, 'instancePath', 'Path to the Sitecore folder', '(e.g. c:\\inetpub\\wwwroot\\my.siteco.re)', getValidation(/[A-z]/), 'Invalid input.', true ); if (configObject.instancePath) { if (!fs.existsSync(configObject.instancePath)) { console.log(chalk.red(`${configObject.instancePath} did not exist!`)); if (interactive) { getInstancePath(); } else { process.exit(1); } } } else { console.warn( chalk.yellow( 'Non-interactive mode specified and no instancePath given. File/config deployment will not be available.' ) ); } }; // if you are setting up for the first time, we don't need an instance path for a remote Sitecore instance if (interactive) { if ( !configObject.instancePath && rlSync.keyInYN('Is your Sitecore instance on this machine or accessible via network share?') ) { getInstancePath(configObject.instancePath); } else if (configObject.instancePath) { getInstancePath(configObject.instancePath); } } // DEPLOY URL/LS HOST const defaultDeployUrl = '/sitecore/api/jss/import'; if (!interactive && !configObject.layoutServiceHost) { throw 'Non interactive mode specified and layoutServiceHost not provided.'; } if (interactive) { configObject.layoutServiceHost = getInteractiveData( configObject.layoutServiceHost, interactive, 'host', 'Sitecore hostname', '(e.g. http://myapp.local.siteco.re; see /sitecore/config; ensure added to hosts)', getValidation(/^https?:\/\/(.*)/), 'Invalid input. Must start with http(s)' ); } if (interactive) { configObject.deployUrl = getInteractiveData( configObject.deployUrl || urljoin(configObject.layoutServiceHost as string, defaultDeployUrl), interactive, 'host', 'Sitecore import service URL', '(usually same as hostname)', getValidation(/^https?:\/\/(.*)/), 'Invalid input. Must start with http(s)' ); } // API KEY configObject.apiKey = getInteractiveData( configObject.apiKey, interactive, 'apiKey', 'Sitecore API Key', '(ID of API key item)', getValidation(/^{?[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}}?$/i), 'Invalid API Key. Should be a GUID / Sitecore Item ID.' ); // DEPLOY SECRET configObject.deploySecret = getInteractiveData( configObject.deploySecret, interactive, 'deploySecret', 'Please enter your deployment secret', '(32+ random chars; or press enter to generate one)', getValidation(/^(.{32,}|)$/), 'Invalid secret. Should be blank or at least 32 random characters.', true ); if (!configObject.deploySecret && interactive) { configObject.deploySecret = Math.random() .toString(36) .substring(2, 15) + Math.random() .toString(36) .substring(2, 15) + Math.random() .toString(36) .substring(2, 15) + Math.random() .toString(36) .substring(2, 15); console.log( 'Deployment secret has been generated. Ensure the JSS app config on the Sitecore end has the same secret set.' ); } if (configObject.deploySecret) { const appConfig = glob .sync('./sitecore/config/*.config') .find((file) => !file.match(/deploysecret/)); if (appConfig) { const appName = findAppNameInConfig(appConfig); if (appName) { const patchFile = path.resolve(`./sitecore/config/${appName}.deploysecret.config`); writeSecretPatchFile(patchFile, appName, configObject.deploySecret); console.log(`Deploy secret Sitecore config written to ${chalk.green(patchFile)}`); console.log('Ensure this configuration is deployed to Sitecore.'); } else { console.log(chalk.yellow(`Unable to resolve JSS app name in ${appConfig}`)); console.log( chalk.yellow( // eslint-disable-next-line prettier/prettier 'For deployment to succeed the app\'s \'deploySecret\' must be set in a Sitecore config patch similar to:' ) ); console.log(createSecretPatchContents('YOUR-JSS-APP-NAME-HERE', configObject.deploySecret)); console.log(''); } } else { console.log( chalk.yellow( 'No JSS config patches were in ./sitecore/config to get the JSS app name from.' ) ); console.log( chalk.yellow( // eslint-disable-next-line prettier/prettier 'For deployment to succeed the app\'s \'deploySecret\' must be set in a Sitecore config patch similar to:' ) ); console.log(createSecretPatchContents('YOUR-JSS-APP-NAME-HERE', configObject.deploySecret)); console.log(''); } } fs.writeFileSync(outputFile, JSON.stringify(config, null, 2)); let hostName = 'undefined'; if (configObject.layoutServiceHost) { hostName = configObject.layoutServiceHost.replace(/https?:\/\//, ''); } console.log(`JSS connection settings saved to ${chalk.green(outputFile)}`); console.log(); console.log(chalk.green('NEXT STEPS')); console.log( `* Ensure the ${chalk.green( 'hostName' )} in /sitecore/config/*.config is configured as ${chalk.green( hostName )}, and in hosts file if needed.` ); if (configObject.instancePath) { console.log(`* Deploy your configuration (i.e. '${chalk.green('jss deploy config')}')`); console.log(`* Deploy your app (i.e. '${chalk.green('jss deploy app -c -d')}')`); } else { console.log(`* Deploy the app's items (i.e. ${chalk.green('jss deploy items -c -d')})`); console.log(`* Create a production build (i.e. ${chalk.green('jss build')})`); console.log( `* Copy the build artifacts to the Sitecore instance in the ${chalk.green( 'sitecoreDistPath' )} set in package.json.` ); console.warn( `${chalk.yellow(' > Note:')} ${chalk.red('jss deploy config')}, ${chalk.red( 'jss deploy files' )}, and ${chalk.red('jss deploy app')} cannot be used with remote Sitecore.` ); } console.log( `* Test your app in integrated mode by visiting ${chalk.green( configObject.layoutServiceHost as string )}` ); }
the_stack
import ShaderChunk, {IShaderChunkCode, IMaterialUniform, IMaterialAttribute} from '../Material/ShaderChunk'; import {IShaderChunk} from './ShaderChunk'; import {IMaterial} from '../Material/Material'; import Hilo3d from '../Core/Hilo3d'; import Debug from '../Debug'; import Material from '../Material/Material'; import Constants from '../Core/Constants'; import {isTexture} from '../Texture/Texture'; import SName from '../Core/SName'; import {SMaterial} from '../Core/Decorator'; /** * `RawShaderMaterial`的初始化参数类型。 */ export interface IShaderMaterialOptions< TExtraUniformSemantic extends string = '', TExtraAttributeSemantic extends string = '' > extends IMaterial { /** * 需要添加的`chucks`,可利用其进行材质复用,详见[ShaderChuck](../shaderchuck)。 */ chunks?: ShaderChunk[]; /** * 材质的attributes属性。 */ attributes?: IShaderChunk<TExtraUniformSemantic, TExtraAttributeSemantic>['attributes']; /** * 材质的uniform属性。 */ uniforms?: IShaderChunk<TExtraUniformSemantic, TExtraAttributeSemantic>['uniforms']; /** * 材质两个着色器共有的宏,将会添加到两个着色器的开头。 */ defines?: IShaderChunk['defines']; /** * 材质的顶点着色器。 */ vs?: string | IShaderChunkCode; /** * 材质的片段着色器。 */ fs?: string | IShaderChunkCode; /** * 材质的混合模式。 * * @default 'OPAQUE' */ alphaMode?: 'BLEND' | 'MASK' | 'OPAQUE'; /** * 材质是否属双向可见的,若是,则会关闭背面剔除。 * * @default false */ doubleSided?: boolean; /** * 材质是否无光照,一般无需关心。 * * @todo: 配合KHR_materials_unlit使用。 * * @default false */ unlit?: boolean; /** * 材质ID,用于材质复用。一般而言若使用了`SMaterial`装饰器标注材质,不用特别指定此,引擎会自动处理。 */ id?: string; } /** * @hidden */ function isIMaterialUniform(value: any): value is IMaterialUniform { return value && !(value as string).substr && 'value' in (value as IMaterialUniform); } /** * @hidden */ function isIMaterialAttribute(value: any): value is IMaterialAttribute { return (value as IMaterialAttribute).name !== undefined; } /** * @hidden */ function isNumber(value: any): value is number { return !!(value as number).toPrecision; } /** * @hidden */ function isNumberArray(value: any): value is number[] { return !!(value as number[]).push; } /** * @hidden */ function isString(value: any): value is string { return !!(value as string).toLowerCase; } /** * 判断一个实例是否为`RawShaderMaterial`。 */ export function isRawShaderMaterial(value: Material): value is RawShaderMaterial { return (value as RawShaderMaterial).isRawShaderMaterial; } /** * 纯净的自定义材质类,允许你创建属于自己的Shader材质。 * * @noInheritDoc */ @SMaterial({className: 'RawShaderMaterial'}) export default class RawShaderMaterial< TExtraUniformSemantic extends string = '', TExtraAttributeSemantic extends string = '' > extends Hilo3d.ShaderMaterial { /** * 类名。 */ public static CLASS_NAME: SName = new SName('RawShaderMaterial'); public isRawShaderMaterial = true; /** * 类名。 */ public className = 'RawShaderMaterial'; /** * 当材质作为模型中的自定义材质时,每次创建一个新模型实例时是否要对材质进行`clone`。 * 这通常用于可能有多个实例的、具有材质动画的模型。 */ public cloneForInst: boolean = false; /** * @hidden */ public vs: string; /** * @hidden */ public fs: string; protected _initOptions: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>; protected _mainVsChunkName: string; protected _mainFsChunkName: string; protected _chuckDefines: string[] = []; protected _chuckVs: IShaderChunkCode[] = []; protected _chuckFs: IShaderChunkCode[] = []; protected _uniforms: {[name: string]: IMaterialUniform} = {}; /** * **高级材质属性,一般而言不要直接修改或者读取它。** * 通过getUniforms方法或者getUniform方法获取或修改! * 或通过setUniform方法修改! */ public uniforms: any; constructor(options?: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>) { super({useHeaderCache: true}); this._initOptions = options; if (!options) { return; } this.className = (this.constructor as typeof RawShaderMaterial).CLASS_NAME.value; options.shaderCacheId = options.id; if (!options.id && this.className !== 'RawShaderMaterial' && this.className !== 'ShaderMaterial') { options.shaderCacheId = this.className; } delete options.id; this.init(options); } /** * 获取特定的Uniform实例引用,可以获取后直接用`value`来设置它。 */ public getUniform<TValue extends IMaterialUniform['value'] = any>(key: string): {value: TValue} { return this._uniforms[key] as {value: TValue}; } /** * 直接设置某个特定uniform的`value`。 */ public setUniform<TValue extends IMaterialUniform['value'] = any>(key: string, value: TValue) { const uniform = this._uniforms[key]; if (!uniform || uniform.value === null || uniform.value === undefined) { this.initUniform(key, {value}); return this; } uniform.value = value; return this; } /** * 通过一个回调函数以及其传入的uniform当前值,设置某个特定uniform的`value`。 */ public changeUniform<TValue extends IMaterialUniform['value'] = any>(key: string, handler: (value: TValue) => TValue) { const value = handler(this._uniforms[key].value as TValue); return this.setUniform(key, value); } protected init(options: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>) { if (!options.id) { delete options.id; } // default blend mode this.blendSrc = Constants.SRC_ALPHA; this.blendDst = Constants.ONE_MINUS_SRC_ALPHA; this.blendEquationAlpha = Constants.FUNC_ADD; Object.assign(this, options); this.uniforms = {}; this.attributes = {}; this.vs = ''; this.fs = ''; this.initChunks(options); this.initAttributes(options); this.initUniforms(options); this.initShaders(options); } protected initChunks(options: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>) { options.attributes = options.attributes || {}; options.uniforms = options.uniforms || {}; if (options.chunks) { const length = options.chunks.length; for (let index = 0; index < length; index += 1) { const chuck = options.chunks[index]; if (Debug.devMode) { this.checkChuck(chuck, options); } Object.assign(options.attributes, chuck.attributes); Object.assign(options.uniforms, chuck.uniforms); if (chuck.vs) { this._chuckVs.push(chuck.vs); if (chuck.isMain && chuck.hasVsOut) { this._mainVsChunkName = chuck.vsEntryName; } } if (chuck.fs) { this._chuckFs.push(chuck.fs); if (chuck.isMain && chuck.hasFsOut) { this._mainFsChunkName = chuck.fsEntryName; } } if (chuck.defines) { this._chuckDefines.push(chuck.defines); } } } if (options.vs) { if (isString(options.vs)) { this._chuckVs.push({main: options.vs, header: ''}); } else { this._chuckVs.push(options.vs); } this._mainVsChunkName = ''; } if (options.fs) { if (isString(options.fs)) { this._chuckFs.push({main: options.fs, header: ''}); } else if (options.fs) { this._chuckFs.push(options.fs); } this._mainFsChunkName = ''; } if (options.defines) { this._chuckDefines.push(options.defines); } } protected checkChuck(chuck: ShaderChunk, options: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>) { const { requiredUniforms, requiredAttributes, uniforms, attributes } = chuck; // check requiredAttributes for (const key of requiredAttributes) { if (!options.attributes[key]) { throw new Error(`Shader chuck "${chuck.name}" requires attribute "${key}" !`); } } // check requiredUniforms for (const key of requiredUniforms) { if (!options.uniforms[key]) { throw new Error(`Shader chuck "${chuck.name}" requires uniform "${key}" !`); } } // check conflict for (const key in attributes) { if (options.attributes[key]) { throw new Error(`Attribute "${key}" is already existed, re-defined in shader chuck "${chuck.name}" !`); } } for (const key in uniforms) { if (options.uniforms[key]) { throw new Error(`Uniform "${key}" is already existed, re-defined in shader chuck "${chuck.name}" !`); } } } protected initAttributes(options: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>) { const {attributes} = options; this.attributes = {}; for (const key in attributes) { const attribute = attributes[key]; if (!isIMaterialAttribute(attribute)) { this.attributes[key] = attribute; } else { this.attributes[key] = { get: mesh => mesh.geometry[attribute.name] }; } } } protected initUniforms(options: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>) { const {uniforms} = options; if (!uniforms['u_gammaFactor']) { uniforms['u_gammaFactor'] = 'GAMMAFACTOR'; } if (!uniforms['u_exposure']) { uniforms['u_exposure'] = 'EXPOSURE'; } for (const key in uniforms) { const uniform = uniforms[key]; if (!isIMaterialUniform(uniform)) { this.uniforms[key] = uniform; continue; } this.initUniform(key, uniform); } } protected initUniform(key: string, uniform: IMaterialUniform) { const {_uniforms} = this; if (uniform.isGlobal) { _uniforms[key] = uniform; } else { _uniforms[key] = {value: uniform.value}; } const {value} = _uniforms[key]; this.isDirty = true; if (value === null || value === undefined) { this.uniforms[key] = { get() { return null; } }; return; } if (isTexture(value)) { this.uniforms[key] = { get(_, __, programInfo) { return (Hilo3d.semantic as any).handlerTexture(_uniforms[key].value, programInfo.textureIndex); } }; return; } if (isNumber(value) || isNumberArray(value)) { this.uniforms[key] = { get() { return _uniforms[key].value; } }; return; } this.uniforms[key] = { get() { return (_uniforms[key].value as any).elements; } }; } protected initShaders(options: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>) { const definesChuck = this._chuckDefines.join('\n') + '\n'; this.vs += definesChuck; this.fs += definesChuck; this.vs += this.generateShader(this._chuckVs); this.fs += this.generateShader(this._chuckFs); if (this._mainVsChunkName) { this.vs += ` void main() { gl_Position = ${this._mainVsChunkName}(); } `; } if (this._mainFsChunkName) { this.fs += ` void main() { gl_FragColor = ${this._mainFsChunkName}(); } `; } this.initCommonOptions(options); } /** * 不需要自己使用! * * @hidden */ public initCommonOptions(options: IShaderMaterialOptions<TExtraUniformSemantic, TExtraAttributeSemantic>, fromLoader: boolean = false) { if (options.alphaMode && (!fromLoader || !this._initOptions.alphaMode)) { switch (options.alphaMode) { case 'BLEND': this.transparent = true; this.blend = true; if (!fromLoader) { this.blendSrc = options.blendSrc || Constants.SRC_ALPHA; this.blendDst = options.blendDst || Constants.ONE_MINUS_SRC_ALPHA; this.blendEquationAlpha = options.blendEquationAlpha || Constants.FUNC_ADD; } break; case 'MASK': if ('alphaCutoff' in options) { this.alphaCutoff = options.alphaCutoff; } else { this.alphaCutoff = 0.5; } break; case 'OPAQUE': default: this.ignoreTranparent = true; break; } this._initOptions.alphaMode = options.alphaMode; } if ((options.doubleSided && !fromLoader) || (options.doubleSided && !this._initOptions.doubleSided)) { this.side = Constants.FRONT_AND_BACK; this._initOptions.doubleSided = true; } (this as any).lightType = options.unlit ? 'NONE' : 'ENABLE'; } private generateShader(chucks: IShaderChunkCode[]) { let headerCode = ''; let mainCode = ''; const length = chucks.length; for (let index = 0; index < length; index += 1) { const {header, main} = chucks[index]; headerCode += header + '\n'; mainCode += main + '\n'; } return headerCode + '\n' + mainCode + '\n'; } /** * 获取定制的渲染参数,一般用于宏开关。 */ public getCustomRenderOption = (options: any) => { } /** * clone一个材质,一般不会重新编译program,但会生成一份新的`uniforms`。 */ public clone(): RawShaderMaterial { const material = new (this.constructor as any)(this._initOptions); material.initCommonOptions(this._initOptions); return material; } public destroyTextures() { super.destroyTextures(); for (const propName in this._uniforms) { const texture = this._uniforms[propName].value; if (texture && isTexture(texture)) { texture.destroy(); } } return this; } }
the_stack
import { Buffer } from '@stacks/common'; import { MAX_STRING_LENGTH_BYTES, MEMO_MAX_LENGTH_BYTES, AddressHashMode, AddressVersion, TransactionVersion, StacksMessageType, PostConditionPrincipalID, } from './constants'; import { StacksPublicKey, serializePublicKey, deserializePublicKey, isCompressed } from './keys'; import { BufferArray, intToHexString, hexStringToInt, exceedsMaxLengthBytes, hashP2PKH, rightPadHexToLength, hashP2SH, hashP2WSH, hashP2WPKH, } from './utils'; import { c32addressDecode, c32address } from 'c32check'; import { BufferReader } from './bufferReader'; import { PostCondition, serializePostCondition, deserializePostCondition } from './postcondition'; import { Payload, deserializePayload, serializePayload } from './payload'; import { DeserializationError } from './errors'; import { deserializeTransactionAuthField, deserializeMessageSignature, MessageSignature, serializeMessageSignature, serializeTransactionAuthField, TransactionAuthField, } from './authorization'; export type StacksMessage = | Address | PostConditionPrincipal | LengthPrefixedString | LengthPrefixedList | Payload | MemoString | AssetInfo | PostCondition | StacksPublicKey | TransactionAuthField | MessageSignature; export function serializeStacksMessage(message: StacksMessage): Buffer { switch (message.type) { case StacksMessageType.Address: return serializeAddress(message); case StacksMessageType.Principal: return serializePrincipal(message); case StacksMessageType.LengthPrefixedString: return serializeLPString(message); case StacksMessageType.MemoString: return serializeMemoString(message); case StacksMessageType.AssetInfo: return serializeAssetInfo(message); case StacksMessageType.PostCondition: return serializePostCondition(message); case StacksMessageType.PublicKey: return serializePublicKey(message); case StacksMessageType.LengthPrefixedList: return serializeLPList(message); case StacksMessageType.Payload: return serializePayload(message); case StacksMessageType.TransactionAuthField: return serializeTransactionAuthField(message); case StacksMessageType.MessageSignature: return serializeMessageSignature(message); } } export function deserializeStacksMessage( bufferReader: BufferReader, type: StacksMessageType, listType?: StacksMessageType ): StacksMessage { switch (type) { case StacksMessageType.Address: return deserializeAddress(bufferReader); case StacksMessageType.Principal: return deserializePrincipal(bufferReader); case StacksMessageType.LengthPrefixedString: return deserializeLPString(bufferReader); case StacksMessageType.MemoString: return deserializeMemoString(bufferReader); case StacksMessageType.AssetInfo: return deserializeAssetInfo(bufferReader); case StacksMessageType.PostCondition: return deserializePostCondition(bufferReader); case StacksMessageType.PublicKey: return deserializePublicKey(bufferReader); case StacksMessageType.Payload: return deserializePayload(bufferReader); case StacksMessageType.LengthPrefixedList: if (!listType) { throw new DeserializationError('No List Type specified'); } return deserializeLPList(bufferReader, listType); case StacksMessageType.MessageSignature: return deserializeMessageSignature(bufferReader); default: throw new Error('Could not recognize StacksMessageType'); } } export interface Address { readonly type: StacksMessageType.Address; readonly version: AddressVersion; readonly hash160: string; } export function createAddress(c32AddressString: string): Address { const addressData = c32addressDecode(c32AddressString); return { type: StacksMessageType.Address, version: addressData[0], hash160: addressData[1], }; } export function createEmptyAddress(): Address { return { type: StacksMessageType.Address, version: AddressVersion.MainnetSingleSig, hash160: '0'.repeat(40), }; } export function addressFromVersionHash(version: AddressVersion, hash: string): Address { return { type: StacksMessageType.Address, version, hash160: hash }; } /** * Translates the tx auth hash mode to the corresponding address version. * @see https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#transaction-authorization */ export function addressHashModeToVersion( hashMode: AddressHashMode, txVersion: TransactionVersion ): AddressVersion { switch (hashMode) { case AddressHashMode.SerializeP2PKH: switch (txVersion) { case TransactionVersion.Mainnet: return AddressVersion.MainnetSingleSig; case TransactionVersion.Testnet: return AddressVersion.TestnetSingleSig; default: throw new Error( `Unexpected txVersion ${JSON.stringify(txVersion)} for hashMode ${hashMode}` ); } case AddressHashMode.SerializeP2SH: case AddressHashMode.SerializeP2WPKH: case AddressHashMode.SerializeP2WSH: switch (txVersion) { case TransactionVersion.Mainnet: return AddressVersion.MainnetMultiSig; case TransactionVersion.Testnet: return AddressVersion.TestnetMultiSig; default: throw new Error( `Unexpected txVersion ${JSON.stringify(txVersion)} for hashMode ${hashMode}` ); } default: throw new Error(`Unexpected hashMode ${JSON.stringify(hashMode)}`); } } export function addressFromHashMode( hashMode: AddressHashMode, txVersion: TransactionVersion, data: string ): Address { const version = addressHashModeToVersion(hashMode, txVersion); return addressFromVersionHash(version, data); } export function addressFromPublicKeys( version: AddressVersion, hashMode: AddressHashMode, numSigs: number, publicKeys: StacksPublicKey[] ): Address { if (publicKeys.length === 0) { throw Error('Invalid number of public keys'); } if (hashMode === AddressHashMode.SerializeP2PKH || hashMode === AddressHashMode.SerializeP2WPKH) { if (publicKeys.length !== 1 || numSigs !== 1) { throw Error('Invalid number of public keys or signatures'); } } if (hashMode === AddressHashMode.SerializeP2WPKH || hashMode === AddressHashMode.SerializeP2WSH) { for (let i = 0; i < publicKeys.length; i++) { if (!isCompressed(publicKeys[i])) { throw Error('Public keys must be compressed for segwit'); } } } switch (hashMode) { case AddressHashMode.SerializeP2PKH: return addressFromVersionHash(version, hashP2PKH(publicKeys[0].data)); case AddressHashMode.SerializeP2WPKH: return addressFromVersionHash(version, hashP2WPKH(publicKeys[0].data)); case AddressHashMode.SerializeP2SH: return addressFromVersionHash(version, hashP2SH(numSigs, publicKeys.map(serializePublicKey))); case AddressHashMode.SerializeP2WSH: return addressFromVersionHash( version, hashP2WSH(numSigs, publicKeys.map(serializePublicKey)) ); } } export function addressToString(address: Address): string { return c32address(address.version, address.hash160).toString(); } export function serializeAddress(address: Address): Buffer { const bufferArray: BufferArray = new BufferArray(); bufferArray.appendHexString(intToHexString(address.version, 1)); bufferArray.appendHexString(address.hash160); return bufferArray.concatBuffer(); } export function deserializeAddress(bufferReader: BufferReader): Address { const version = hexStringToInt(bufferReader.readBuffer(1).toString('hex')); const data = bufferReader.readBuffer(20).toString('hex'); return { type: StacksMessageType.Address, version, hash160: data }; } export type PostConditionPrincipal = StandardPrincipal | ContractPrincipal; export interface StandardPrincipal { readonly type: StacksMessageType.Principal; readonly prefix: PostConditionPrincipalID.Standard; readonly address: Address; } export interface ContractPrincipal { readonly type: StacksMessageType.Principal; readonly prefix: PostConditionPrincipalID.Contract; readonly address: Address; readonly contractName: LengthPrefixedString; } /** * Parses a principal string for either a standard principal or contract principal. * @param principalString - String in the format `{address}.{contractName}` * @example "SP13N5TE1FBBGRZD1FCM49QDGN32WAXM2E5F8WT2G.example-contract" * @example "SP13N5TE1FBBGRZD1FCM49QDGN32WAXM2E5F8WT2G" */ export function parsePrincipalString( principalString: string ): StandardPrincipal | ContractPrincipal { if (principalString.includes('.')) { const [address, contractName] = principalString.split('.'); return createContractPrincipal(address, contractName); } else { return createStandardPrincipal(principalString); } } export function createStandardPrincipal(addressString: string): StandardPrincipal { const addr = createAddress(addressString); return { type: StacksMessageType.Principal, prefix: PostConditionPrincipalID.Standard, address: addr, }; } export function createContractPrincipal( addressString: string, contractName: string ): ContractPrincipal { const addr = createAddress(addressString); const name = createLPString(contractName); return { type: StacksMessageType.Principal, prefix: PostConditionPrincipalID.Contract, address: addr, contractName: name, }; } export function serializePrincipal(principal: PostConditionPrincipal): Buffer { const bufferArray: BufferArray = new BufferArray(); bufferArray.push(Buffer.from([principal.prefix])); bufferArray.push(serializeAddress(principal.address)); if (principal.prefix === PostConditionPrincipalID.Contract) { bufferArray.push(serializeLPString(principal.contractName)); } return bufferArray.concatBuffer(); } export function deserializePrincipal(bufferReader: BufferReader): PostConditionPrincipal { const prefix = bufferReader.readUInt8Enum(PostConditionPrincipalID, _ => { throw new DeserializationError('Unexpected Principal payload type: ${n}'); }); const address = deserializeAddress(bufferReader); if (prefix === PostConditionPrincipalID.Standard) { return { type: StacksMessageType.Principal, prefix, address } as StandardPrincipal; } const contractName = deserializeLPString(bufferReader); return { type: StacksMessageType.Principal, prefix, address, contractName, } as ContractPrincipal; } export interface LengthPrefixedString { readonly type: StacksMessageType.LengthPrefixedString; readonly content: string; readonly lengthPrefixBytes: number; readonly maxLengthBytes: number; } export function createLPString(content: string): LengthPrefixedString; export function createLPString(content: string, lengthPrefixBytes: number): LengthPrefixedString; export function createLPString( content: string, lengthPrefixBytes: number, maxLengthBytes: number ): LengthPrefixedString; export function createLPString( content: string, lengthPrefixBytes?: number, maxLengthBytes?: number ): LengthPrefixedString { const prefixLength = lengthPrefixBytes || 1; const maxLength = maxLengthBytes || MAX_STRING_LENGTH_BYTES; if (exceedsMaxLengthBytes(content, maxLength)) { throw new Error(`String length exceeds maximum bytes ${maxLength.toString()}`); } return { type: StacksMessageType.LengthPrefixedString, content, lengthPrefixBytes: prefixLength, maxLengthBytes: maxLength, }; } export function serializeLPString(lps: LengthPrefixedString) { const bufferArray: BufferArray = new BufferArray(); const contentBuffer = Buffer.from(lps.content); const length = contentBuffer.byteLength; bufferArray.appendHexString(intToHexString(length, lps.lengthPrefixBytes)); bufferArray.push(contentBuffer); return bufferArray.concatBuffer(); } export function deserializeLPString( bufferReader: BufferReader, prefixBytes?: number, maxLength?: number ): LengthPrefixedString { prefixBytes = prefixBytes ? prefixBytes : 1; const length = hexStringToInt(bufferReader.readBuffer(prefixBytes).toString('hex')); const content = bufferReader.readBuffer(length).toString(); return createLPString(content, prefixBytes, maxLength ?? 128); } export function codeBodyString(content: string): LengthPrefixedString { return createLPString(content, 4, 100000); } export interface MemoString { readonly type: StacksMessageType.MemoString; readonly content: string; } export function createMemoString(content: string): MemoString { if (content && exceedsMaxLengthBytes(content, MEMO_MAX_LENGTH_BYTES)) { throw new Error(`Memo exceeds maximum length of ${MEMO_MAX_LENGTH_BYTES.toString()} bytes`); } return { type: StacksMessageType.MemoString, content }; } export function serializeMemoString(memoString: MemoString): Buffer { const bufferArray: BufferArray = new BufferArray(); const contentBuffer = Buffer.from(memoString.content); const paddedContent = rightPadHexToLength( contentBuffer.toString('hex'), MEMO_MAX_LENGTH_BYTES * 2 ); bufferArray.push(Buffer.from(paddedContent, 'hex')); return bufferArray.concatBuffer(); } export function deserializeMemoString(bufferReader: BufferReader): MemoString { const content = bufferReader.readBuffer(MEMO_MAX_LENGTH_BYTES).toString(); return { type: StacksMessageType.MemoString, content }; } export interface AssetInfo { readonly type: StacksMessageType.AssetInfo; readonly address: Address; readonly contractName: LengthPrefixedString; readonly assetName: LengthPrefixedString; } /** * Parse a fully qualified string that identifies the token type. * @param id - String in the format `{address}.{contractName}::{assetName}` * @example "SP13N5TE1FBBGRZD1FCM49QDGN32WAXM2E5F8WT2G.example-contract::example-token" */ export function parseAssetInfoString(id: string): AssetInfo { const [assetAddress, assetContractName, assetTokenName] = id.split(/\.|::/); const assetInfo = createAssetInfo(assetAddress, assetContractName, assetTokenName); return assetInfo; } export function createAssetInfo( addressString: string, contractName: string, assetName: string ): AssetInfo { return { type: StacksMessageType.AssetInfo, address: createAddress(addressString), contractName: createLPString(contractName), assetName: createLPString(assetName), }; } export function serializeAssetInfo(info: AssetInfo): Buffer { const bufferArray: BufferArray = new BufferArray(); bufferArray.push(serializeAddress(info.address)); bufferArray.push(serializeLPString(info.contractName)); bufferArray.push(serializeLPString(info.assetName)); return bufferArray.concatBuffer(); } export function deserializeAssetInfo(bufferReader: BufferReader): AssetInfo { return { type: StacksMessageType.AssetInfo, address: deserializeAddress(bufferReader), contractName: deserializeLPString(bufferReader), assetName: deserializeLPString(bufferReader), }; } export interface LengthPrefixedList { readonly type: StacksMessageType.LengthPrefixedList; readonly lengthPrefixBytes: number; readonly values: StacksMessage[]; } export function createLPList<T extends StacksMessage>( values: T[], lengthPrefixBytes?: number ): LengthPrefixedList { return { type: StacksMessageType.LengthPrefixedList, lengthPrefixBytes: lengthPrefixBytes || 4, values, }; } export function serializeLPList(lpList: LengthPrefixedList): Buffer { const list = lpList.values; const bufferArray: BufferArray = new BufferArray(); bufferArray.appendHexString(intToHexString(list.length, lpList.lengthPrefixBytes)); for (let index = 0; index < list.length; index++) { bufferArray.push(serializeStacksMessage(list[index])); } return bufferArray.concatBuffer(); } export function deserializeLPList( bufferReader: BufferReader, type: StacksMessageType, lengthPrefixBytes?: number ): LengthPrefixedList { const length = hexStringToInt(bufferReader.readBuffer(lengthPrefixBytes || 4).toString('hex')); const l: StacksMessage[] = []; for (let index = 0; index < length; index++) { switch (type) { case StacksMessageType.Address: l.push(deserializeAddress(bufferReader)); break; case StacksMessageType.LengthPrefixedString: l.push(deserializeLPString(bufferReader)); break; case StacksMessageType.MemoString: l.push(deserializeMemoString(bufferReader)); break; case StacksMessageType.AssetInfo: l.push(deserializeAssetInfo(bufferReader)); break; case StacksMessageType.PostCondition: l.push(deserializePostCondition(bufferReader)); break; case StacksMessageType.PublicKey: l.push(deserializePublicKey(bufferReader)); break; case StacksMessageType.TransactionAuthField: l.push(deserializeTransactionAuthField(bufferReader)); break; } } return createLPList(l, lengthPrefixBytes); }
the_stack
import { ConcreteRouteDef, isConcreteRouteDef, isStaticRedirectionRouteDef, ProgrammticRedirectionRouteDef, RedirectionRouteDef, RouteDef, } from './route_config_types'; import {Route, RouteKind, RouteParams, SerializableQueryParams} from './types'; interface NegativeMatch { result: false; } interface PositiveMatch { result: true; params: RouteParams; pathParts: string[]; isRedirection: boolean; redirectionQueryParams?: SerializableQueryParams; } type Match = NegativeMatch | PositiveMatch; type PathPartMatch = | { isParamPathPart: false; partMatched: boolean; } | { partMatched: boolean; isParamPathPart: true; paramName: string; paramValue: string; }; type PathMatcher = (pathPartQuery: string) => PathPartMatch; interface NonParamPathFragment { pathPart: string; isParam: false; } interface ParamPathFragment { pathPart: string; isParam: true; paramName: string; } type PathFragment = ParamPathFragment | NonParamPathFragment; function getPathFragments(path: string): PathFragment[] { const parts = getPathParts(path); return parts.map((part) => { const isParam = part.startsWith(':'); if (!isParam) { return {pathPart: part, isParam}; } return { pathPart: part, isParam: true, paramName: part.slice(1), }; }); } abstract class RouteConfigMatcher { protected readonly pathFragments: PathFragment[]; protected readonly pathMatchers: PathMatcher[]; abstract readonly definition: RouteDef; static getMatcher(routeDef: RouteDef): RouteConfigMatcher { if (isConcreteRouteDef(routeDef)) { return new ConcreteRouteConfigMatcher(routeDef); } if (isStaticRedirectionRouteDef(routeDef)) { return new StaticRedirectionRouteConfigMatcher(routeDef); } return new ProgrammaticalRedirectionRouteConfigMatcher(routeDef); } protected constructor(routeDef: RouteDef) { this.validateConfig(routeDef); this.pathFragments = getPathFragments(routeDef.path); this.pathMatchers = this.getPathMatchers(this.pathFragments); } private validateConfig({path}: RouteDef) { if (!path.startsWith('/')) { throw new RangeError(`config.path should start with '/'. ${path}`); } let colonIndex = 0; while ((colonIndex = path.indexOf(':', colonIndex + 1)) >= 0) { if (path[colonIndex - 1] !== '/') { throw new RangeError( `config.path parameter should come after '/'. ${path}` ); } if (path[colonIndex + 1] === undefined || path[colonIndex + 1] === '/') { throw new RangeError( `config.path parameter should have non-empty name. ${path}` ); } } } private getPathMatchers(pathFragments: PathFragment[]): PathMatcher[] { return pathFragments.map((fragment) => { const {pathPart} = fragment; if (fragment.isParam) { return (pathPartQuery: string) => { return { isParamPathPart: true, partMatched: true, paramName: fragment.paramName, paramValue: pathPartQuery, }; }; } return (pathPartQuery: string) => { return { isParamPathPart: false, partMatched: pathPartQuery === pathPart, }; }; }); } /** * In case of parameter reprojection failure (cannot create redirection * pathname from parameter present in current pathname), it throws a * RangeError. */ match(pathParts: string[]): Match { let combinedParams: Record<string, string> = {}; if (this.pathMatchers.length !== pathParts.length) { return {result: false}; } let pathIndex = 0; for (const matcher of this.pathMatchers) { const pathToMatch = pathParts[pathIndex++]; const match = matcher(pathToMatch); if (!match.partMatched) { return {result: false}; } if (match.isParamPathPart) { combinedParams = { ...combinedParams, [match.paramName]: match.paramValue, }; } } return { result: true, params: combinedParams, pathParts, isRedirection: false, }; } /** * In case of parameter projection failure (cannot create pathname), it throws * a RangeError. */ matchByParams(params: RouteParams): PositiveMatch { const pathParts = this.reprojectPathByParams(this.pathFragments, params); return { result: true, params, pathParts, isRedirection: false, }; } /** * Reprojects route parameter values to path fragments for path parts. */ protected reprojectPathByParams( pathFragments: PathFragment[], params: RouteParams ): string[] { const pathParts: string[] = []; for (const fragment of pathFragments) { if (fragment.isParam) { const {paramName} = fragment; if (!params.hasOwnProperty(paramName)) { throw new RangeError( `Failed to reproject parameter. "${paramName}" parameter ` + 'should be present.' ); } pathParts.push(params[paramName]); } else { pathParts.push(fragment.pathPart); } } return pathParts; } } class ConcreteRouteConfigMatcher extends RouteConfigMatcher { constructor(readonly definition: ConcreteRouteDef) { super(definition); } } class StaticRedirectionRouteConfigMatcher extends RouteConfigMatcher { private readonly redirectionFragments: PathFragment[]; constructor(readonly definition: RedirectionRouteDef) { super(definition); this.redirectionFragments = getPathFragments(definition.redirectionPath); } override match(pathParts: string[]): Match { const match = super.match(pathParts); if (!match.result) return match; const newPathParts = this.reprojectPathByParams( this.redirectionFragments, match.params ); return { result: true, params: match.params, pathParts: newPathParts, isRedirection: true, }; } } class ProgrammaticalRedirectionRouteConfigMatcher extends RouteConfigMatcher { constructor(readonly definition: ProgrammticRedirectionRouteDef) { super(definition); } override match(pathParts: string[]): Match { const match = super.match(pathParts); if (!match.result) return match; const {pathParts: newPathParts, queryParams} = this.definition.redirector(pathParts); return { result: true, params: match.params, pathParts: newPathParts, isRedirection: true, redirectionQueryParams: queryParams, }; } } interface BaseRedirectionRouteMatch { routeKind: Route['routeKind']; pathname: Route['pathname']; // Route parameters. An object. Its keys are defined to be parameter defined // in the path spec while their respective values are string. params: Route['params']; deepLinkProvider: ConcreteRouteDef['deepLinkProvider'] | null; originateFromRedirection: boolean; } export interface NonRedirectionRouteMatch extends BaseRedirectionRouteMatch { originateFromRedirection: false; } export interface RedirectionRouteMatch extends BaseRedirectionRouteMatch { originateFromRedirection: true; redirectionOnlyQueryParams?: Route['queryParams']; } export type RouteMatch = NonRedirectionRouteMatch | RedirectionRouteMatch; export class RouteConfigs { private readonly routeKindToConcreteConfigMatchers: Map< RouteKind, ConcreteRouteConfigMatcher >; private readonly configMatchers: RouteConfigMatcher[]; private readonly defaultRouteConfig: ConcreteRouteConfigMatcher | null; constructor( configs: RouteDef[], private readonly maxRedirection: number = 3 ) { if (maxRedirection < 0) { throw new RangeError('maxRedirection has to be non-negative number'); } this.validateRouteConfigs(configs); this.defaultRouteConfig = null; this.routeKindToConcreteConfigMatchers = new Map(); this.configMatchers = []; for (const config of configs) { const matcher = RouteConfigMatcher.getMatcher(config); this.configMatchers.push(matcher); if (matcher instanceof ConcreteRouteConfigMatcher) { this.routeKindToConcreteConfigMatchers.set( matcher.definition.routeKind, matcher ); if (matcher.definition.defaultRoute) { this.defaultRouteConfig = matcher; } } } } private validateRouteConfigs(configs: RouteDef[]) { const concreteDefinitions = configs.filter( isConcreteRouteDef ) as ConcreteRouteDef[]; const defaultRoutes = concreteDefinitions.filter((def) => def.defaultRoute); if (defaultRoutes.length > 1) { const paths = defaultRoutes.map(({path}) => path).join(', '); throw new RangeError(`There are more than one defaultRoutes. ${paths}`); } else if (defaultRoutes.length === 1) { const {path} = defaultRoutes[0]; const hasParam = Boolean( getPathFragments(path).find(({isParam}) => isParam) ); if (hasParam) { throw new RangeError(`A defaultRoute cannot have any params. ${path}`); } } const routeKindConfig = new Set<RouteKind>(); for (const {routeKind} of concreteDefinitions) { if (routeKindConfig.has(routeKind)) { throw new RangeError( `Multiple route configuration for kind: ${routeKind}. ` + 'Configurations should have unique routeKinds' ); } routeKindConfig.add(routeKind); } } match(navigation: {pathname: string}): RouteMatch | null { if (!navigation.pathname.startsWith('/')) { throw new RangeError( 'Navigation has to made with pathname that starts with "/"' ); } let pathParts = getPathParts(navigation.pathname); let redirectionCount = 0; let wasRedirected = false; let redirectionOnlyQueryParams: undefined | SerializableQueryParams = undefined; while (true) { let hasMatch = false; for (const matcher of this.configMatchers) { const match = matcher.match(pathParts); if (match.result) { hasMatch = true; const {params, pathParts: newPathParts, isRedirection} = match; if (isRedirection) { pathParts = newPathParts; wasRedirected = true; redirectionOnlyQueryParams = match.redirectionQueryParams; break; } if (!(matcher instanceof ConcreteRouteConfigMatcher)) { throw new RangeError( 'No concrete route definition `match` return redirection' ); } const {definition} = matcher; const base = { routeKind: definition.routeKind, params, pathname: getPathFromParts(newPathParts), deepLinkProvider: definition.deepLinkProvider || null, }; if (!wasRedirected) { return { ...base, originateFromRedirection: false, }; } return { ...base, originateFromRedirection: true, redirectionOnlyQueryParams, }; } } if (wasRedirected) { redirectionCount++; } if (!hasMatch || redirectionCount > this.maxRedirection) { // If not redirected, no need to rematch the routes. Abort. break; } } if (redirectionCount > this.maxRedirection) { throw new Error( `Potential redirection loop (redirecting more than ` + `${this.maxRedirection} times. Please do not have cycles in the ` + `routes.` ); } if (this.defaultRouteConfig) { const {definition} = this.defaultRouteConfig; return { routeKind: definition.routeKind, deepLinkProvider: definition.deepLinkProvider ?? null, pathname: definition.path, params: {}, originateFromRedirection: wasRedirected, }; } return null; } matchByRouteKind( routeKind: RouteKind, params: RouteParams ): RouteMatch | null { const matcher = this.routeKindToConcreteConfigMatchers.get(routeKind); if (!matcher) { throw new RangeError( `Requires configuration for routeKind: ${routeKind}` ); } const match = matcher.matchByParams(params); return { routeKind, params, pathname: getPathFromParts(match.pathParts), deepLinkProvider: matcher.definition.deepLinkProvider || null, originateFromRedirection: false, }; } } function getPathParts(path: string): string[] { return path.split('/').slice(1); } function getPathFromParts(pathParts: string[]): string { return '/' + pathParts.join('/'); }
the_stack
import { Secp256k1, Sha256 } from '../../../crypto/crypto'; import { flattenBinArray } from '../../../format/hex'; import { AuthenticationProgramStateCommon, AuthenticationProgramStateError, AuthenticationProgramStateSignatureAnalysis, AuthenticationProgramStateStack, } from '../../vm-types'; import { combineOperations, pushToStack, useOneScriptNumber, useOneStackItem, useThreeStackItems, useTwoScriptNumbers, useTwoStackItems, } from '../common/combinators'; import { ConsensusCommon } from '../common/common'; import { isValidPublicKeyEncoding, isValidSignatureEncodingDER, } from '../common/encoding'; import { applyError, AuthenticationErrorCommon } from '../common/errors'; import { opVerify } from '../common/flow-control'; import { bigIntToScriptNumber, booleanToScriptNumber } from '../common/types'; import { AuthenticationErrorBCH } from './bch-errors'; import { OpcodesBCH } from './bch-opcodes'; import { ConsensusBCH } from './bch-types'; export const opCat = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> >() => (state: State) => useTwoStackItems(state, (nextState, [a, b]) => a.length + b.length > ConsensusCommon.maximumStackItemLength ? applyError<State, AuthenticationErrorBCH>( AuthenticationErrorBCH.exceededMaximumStackItemLength, nextState ) : pushToStack(nextState, flattenBinArray([a, b])) ); export const opSplit = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> >({ requireMinimalEncoding, }: { requireMinimalEncoding: boolean; }) => (state: State) => useOneScriptNumber( state, (nextState, value) => { const index = Number(value); return useOneStackItem(nextState, (finalState, [item]) => index < 0 || index > item.length ? applyError<State, AuthenticationErrorBCH>( AuthenticationErrorBCH.invalidSplitIndex, finalState ) : pushToStack(finalState, item.slice(0, index), item.slice(index)) ); }, { requireMinimalEncoding } ); enum Constants { positiveSign = 0x00, negativeSign = 0x80, } export const padMinimallyEncodedScriptNumber = ( scriptNumber: Uint8Array, length: number ) => { // eslint-disable-next-line functional/no-let let signBit = Constants.positiveSign; // eslint-disable-next-line functional/no-conditional-statement if (scriptNumber.length > 0) { // eslint-disable-next-line functional/no-expression-statement, no-bitwise signBit = scriptNumber[scriptNumber.length - 1] & Constants.negativeSign; // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data scriptNumber[scriptNumber.length - 1] &= Constants.negativeSign - 1; } const result = Array.from(scriptNumber); // eslint-disable-next-line functional/no-loop-statement while (result.length < length - 1) { // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data result.push(0); } // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data result.push(signBit); return Uint8Array.from(result); }; export const opNum2Bin = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> >() => (state: State) => useOneScriptNumber( state, (nextState, value) => { const targetLength = Number(value); return targetLength > ConsensusCommon.maximumStackItemLength ? applyError<State, AuthenticationErrorBCH>( AuthenticationErrorBCH.exceededMaximumStackItemLength, nextState ) : useOneScriptNumber( nextState, (finalState, [target]) => { const minimallyEncoded = bigIntToScriptNumber(target); return minimallyEncoded.length > targetLength ? applyError<State, AuthenticationErrorBCH>( AuthenticationErrorBCH.insufficientLength, finalState ) : minimallyEncoded.length === targetLength ? pushToStack(finalState, minimallyEncoded) : pushToStack( finalState, padMinimallyEncodedScriptNumber( minimallyEncoded, targetLength ) ); }, { maximumScriptNumberByteLength: // TODO: is this right? ConsensusCommon.maximumStackItemLength, requireMinimalEncoding: false, } ); }, { requireMinimalEncoding: true } ); export const opBin2Num = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> >() => (state: State) => useOneScriptNumber( state, (nextState, [target]) => { const minimallyEncoded = bigIntToScriptNumber(target); return minimallyEncoded.length > ConsensusCommon.maximumScriptNumberLength ? applyError<State, AuthenticationErrorBCH>( AuthenticationErrorBCH.exceededMaximumScriptNumberLength, nextState ) : pushToStack(nextState, minimallyEncoded); }, { // TODO: is this right? maximumScriptNumberByteLength: ConsensusCommon.maximumStackItemLength, requireMinimalEncoding: false, } ); export const bitwiseOperation = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> >( combine: (a: Uint8Array, b: Uint8Array) => Uint8Array ) => (state: State) => useTwoStackItems(state, (nextState, [a, b]) => a.length === b.length ? pushToStack(nextState, combine(a, b)) : applyError<State, AuthenticationErrorBCH>( AuthenticationErrorBCH.mismatchedBitwiseOperandLength, nextState ) ); export const opAnd = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> // eslint-disable-next-line no-bitwise >() => bitwiseOperation<State>((a, b) => a.map((v, i) => v & b[i])); export const opOr = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> // eslint-disable-next-line no-bitwise >() => bitwiseOperation<State>((a, b) => a.map((v, i) => v | b[i])); export const opXor = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> // eslint-disable-next-line no-bitwise >() => bitwiseOperation<State>((a, b) => a.map((v, i) => v ^ b[i])); export const opDiv = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> >({ requireMinimalEncoding, }: { requireMinimalEncoding: boolean; }) => (state: State) => useTwoScriptNumbers( state, (nextState, [a, b]) => b === BigInt(0) ? applyError<State, AuthenticationErrorBCH>( AuthenticationErrorBCH.divisionByZero, nextState ) : pushToStack(nextState, bigIntToScriptNumber(a / b)), { requireMinimalEncoding } ); export const opMod = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<AuthenticationErrorBCH> >({ requireMinimalEncoding, }: { requireMinimalEncoding: boolean; }) => (state: State) => useTwoScriptNumbers( state, (nextState, [a, b]) => b === BigInt(0) ? applyError<State, AuthenticationErrorBCH>( AuthenticationErrorBCH.divisionByZero, nextState ) : pushToStack(nextState, bigIntToScriptNumber(a % b)), { requireMinimalEncoding } ); /** * Validate the encoding of a raw signature – a signature without a signing * serialization type byte (A.K.A. "sighash" byte). * * @param signature - the raw signature */ export const isValidSignatureEncodingBCHRaw = (signature: Uint8Array) => signature.length === 0 || signature.length === ConsensusBCH.schnorrSignatureLength || isValidSignatureEncodingDER(signature); export const opCheckDataSig = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<Errors> & AuthenticationProgramStateSignatureAnalysis, Errors >({ secp256k1, sha256, }: { sha256: { hash: Sha256['hash'] }; secp256k1: { verifySignatureSchnorr: Secp256k1['verifySignatureSchnorr']; verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS']; }; }) => (state: State) => // eslint-disable-next-line complexity useThreeStackItems(state, (nextState, [signature, message, publicKey]) => { if (!isValidSignatureEncodingBCHRaw(signature)) { return applyError<State, Errors>( AuthenticationErrorCommon.invalidSignatureEncoding, nextState ); } if (!isValidPublicKeyEncoding(publicKey)) { return applyError<State, Errors>( AuthenticationErrorCommon.invalidPublicKeyEncoding, nextState ); } const digest = sha256.hash(message); // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data nextState.signedMessages.push(message); const useSchnorr = signature.length === ConsensusBCH.schnorrSignatureLength; const success = useSchnorr ? secp256k1.verifySignatureSchnorr(signature, publicKey, digest) : secp256k1.verifySignatureDERLowS(signature, publicKey, digest); return !success && signature.length !== 0 ? applyError<State, Errors>( AuthenticationErrorCommon.nonNullSignatureFailure, nextState ) : pushToStack(nextState, booleanToScriptNumber(success)); }); export const opCheckDataSigVerify = < State extends AuthenticationProgramStateStack & AuthenticationProgramStateError<Errors> & AuthenticationProgramStateSignatureAnalysis, Errors >({ secp256k1, sha256, }: { sha256: { hash: Sha256['hash'] }; secp256k1: { verifySignatureSchnorr: Secp256k1['verifySignatureSchnorr']; verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS']; }; }) => combineOperations( opCheckDataSig<State, Errors>({ secp256k1, sha256 }), opVerify<State, Errors>() ); export const bitcoinCashOperations = < Opcodes, State extends AuthenticationProgramStateCommon< Opcodes, AuthenticationErrorBCH > >({ flags, secp256k1, sha256, }: { sha256: { hash: Sha256['hash'] }; secp256k1: { verifySignatureSchnorr: Secp256k1['verifySignatureSchnorr']; verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS']; }; flags: { requireBugValueZero: boolean; requireMinimalEncoding: boolean; requireNullSignatureFailures: boolean; }; }) => ({ [OpcodesBCH.OP_CAT]: opCat<State>(), [OpcodesBCH.OP_SPLIT]: opSplit<State>(flags), [OpcodesBCH.OP_NUM2BIN]: opNum2Bin<State>(), [OpcodesBCH.OP_BIN2NUM]: opBin2Num<State>(), [OpcodesBCH.OP_AND]: opAnd<State>(), [OpcodesBCH.OP_OR]: opOr<State>(), [OpcodesBCH.OP_XOR]: opXor<State>(), [OpcodesBCH.OP_DIV]: opDiv<State>(flags), [OpcodesBCH.OP_MOD]: opMod<State>(flags), [OpcodesBCH.OP_CHECKDATASIG]: opCheckDataSig<State, AuthenticationErrorBCH>({ secp256k1, sha256, }), [OpcodesBCH.OP_CHECKDATASIGVERIFY]: opCheckDataSigVerify< State, AuthenticationErrorBCH >({ secp256k1, sha256 }), });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { MongoDBDatabaseGetResults, MongoDBResourcesListMongoDBDatabasesOptionalParams, MongoDBCollectionGetResults, MongoDBResourcesListMongoDBCollectionsOptionalParams, MongoDBResourcesGetMongoDBDatabaseOptionalParams, MongoDBResourcesGetMongoDBDatabaseResponse, MongoDBDatabaseCreateUpdateParameters, MongoDBResourcesCreateUpdateMongoDBDatabaseOptionalParams, MongoDBResourcesCreateUpdateMongoDBDatabaseResponse, MongoDBResourcesDeleteMongoDBDatabaseOptionalParams, MongoDBResourcesGetMongoDBDatabaseThroughputOptionalParams, MongoDBResourcesGetMongoDBDatabaseThroughputResponse, ThroughputSettingsUpdateParameters, MongoDBResourcesUpdateMongoDBDatabaseThroughputOptionalParams, MongoDBResourcesUpdateMongoDBDatabaseThroughputResponse, MongoDBResourcesMigrateMongoDBDatabaseToAutoscaleOptionalParams, MongoDBResourcesMigrateMongoDBDatabaseToAutoscaleResponse, MongoDBResourcesMigrateMongoDBDatabaseToManualThroughputOptionalParams, MongoDBResourcesMigrateMongoDBDatabaseToManualThroughputResponse, MongoDBResourcesGetMongoDBCollectionOptionalParams, MongoDBResourcesGetMongoDBCollectionResponse, MongoDBCollectionCreateUpdateParameters, MongoDBResourcesCreateUpdateMongoDBCollectionOptionalParams, MongoDBResourcesCreateUpdateMongoDBCollectionResponse, MongoDBResourcesDeleteMongoDBCollectionOptionalParams, MongoDBResourcesGetMongoDBCollectionThroughputOptionalParams, MongoDBResourcesGetMongoDBCollectionThroughputResponse, MongoDBResourcesUpdateMongoDBCollectionThroughputOptionalParams, MongoDBResourcesUpdateMongoDBCollectionThroughputResponse, MongoDBResourcesMigrateMongoDBCollectionToAutoscaleOptionalParams, MongoDBResourcesMigrateMongoDBCollectionToAutoscaleResponse, MongoDBResourcesMigrateMongoDBCollectionToManualThroughputOptionalParams, MongoDBResourcesMigrateMongoDBCollectionToManualThroughputResponse, ContinuousBackupRestoreLocation, MongoDBResourcesRetrieveContinuousBackupInformationOptionalParams, MongoDBResourcesRetrieveContinuousBackupInformationResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a MongoDBResources. */ export interface MongoDBResources { /** * Lists the MongoDB databases under an existing Azure Cosmos DB database account. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param options The options parameters. */ listMongoDBDatabases( resourceGroupName: string, accountName: string, options?: MongoDBResourcesListMongoDBDatabasesOptionalParams ): PagedAsyncIterableIterator<MongoDBDatabaseGetResults>; /** * Lists the MongoDB collection under an existing Azure Cosmos DB database account. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ listMongoDBCollections( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesListMongoDBCollectionsOptionalParams ): PagedAsyncIterableIterator<MongoDBCollectionGetResults>; /** * Gets the MongoDB databases under an existing Azure Cosmos DB database account with the provided * name. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ getMongoDBDatabase( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesGetMongoDBDatabaseOptionalParams ): Promise<MongoDBResourcesGetMongoDBDatabaseResponse>; /** * Create or updates Azure Cosmos DB MongoDB database * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param createUpdateMongoDBDatabaseParameters The parameters to provide for the current MongoDB * database. * @param options The options parameters. */ beginCreateUpdateMongoDBDatabase( resourceGroupName: string, accountName: string, databaseName: string, createUpdateMongoDBDatabaseParameters: MongoDBDatabaseCreateUpdateParameters, options?: MongoDBResourcesCreateUpdateMongoDBDatabaseOptionalParams ): Promise< PollerLike< PollOperationState<MongoDBResourcesCreateUpdateMongoDBDatabaseResponse>, MongoDBResourcesCreateUpdateMongoDBDatabaseResponse > >; /** * Create or updates Azure Cosmos DB MongoDB database * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param createUpdateMongoDBDatabaseParameters The parameters to provide for the current MongoDB * database. * @param options The options parameters. */ beginCreateUpdateMongoDBDatabaseAndWait( resourceGroupName: string, accountName: string, databaseName: string, createUpdateMongoDBDatabaseParameters: MongoDBDatabaseCreateUpdateParameters, options?: MongoDBResourcesCreateUpdateMongoDBDatabaseOptionalParams ): Promise<MongoDBResourcesCreateUpdateMongoDBDatabaseResponse>; /** * Deletes an existing Azure Cosmos DB MongoDB database. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ beginDeleteMongoDBDatabase( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesDeleteMongoDBDatabaseOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes an existing Azure Cosmos DB MongoDB database. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ beginDeleteMongoDBDatabaseAndWait( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesDeleteMongoDBDatabaseOptionalParams ): Promise<void>; /** * Gets the RUs per second of the MongoDB database under an existing Azure Cosmos DB database account * with the provided name. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ getMongoDBDatabaseThroughput( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesGetMongoDBDatabaseThroughputOptionalParams ): Promise<MongoDBResourcesGetMongoDBDatabaseThroughputResponse>; /** * Update RUs per second of the an Azure Cosmos DB MongoDB database * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param updateThroughputParameters The RUs per second of the parameters to provide for the current * MongoDB database. * @param options The options parameters. */ beginUpdateMongoDBDatabaseThroughput( resourceGroupName: string, accountName: string, databaseName: string, updateThroughputParameters: ThroughputSettingsUpdateParameters, options?: MongoDBResourcesUpdateMongoDBDatabaseThroughputOptionalParams ): Promise< PollerLike< PollOperationState< MongoDBResourcesUpdateMongoDBDatabaseThroughputResponse >, MongoDBResourcesUpdateMongoDBDatabaseThroughputResponse > >; /** * Update RUs per second of the an Azure Cosmos DB MongoDB database * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param updateThroughputParameters The RUs per second of the parameters to provide for the current * MongoDB database. * @param options The options parameters. */ beginUpdateMongoDBDatabaseThroughputAndWait( resourceGroupName: string, accountName: string, databaseName: string, updateThroughputParameters: ThroughputSettingsUpdateParameters, options?: MongoDBResourcesUpdateMongoDBDatabaseThroughputOptionalParams ): Promise<MongoDBResourcesUpdateMongoDBDatabaseThroughputResponse>; /** * Migrate an Azure Cosmos DB MongoDB database from manual throughput to autoscale * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ beginMigrateMongoDBDatabaseToAutoscale( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesMigrateMongoDBDatabaseToAutoscaleOptionalParams ): Promise< PollerLike< PollOperationState< MongoDBResourcesMigrateMongoDBDatabaseToAutoscaleResponse >, MongoDBResourcesMigrateMongoDBDatabaseToAutoscaleResponse > >; /** * Migrate an Azure Cosmos DB MongoDB database from manual throughput to autoscale * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ beginMigrateMongoDBDatabaseToAutoscaleAndWait( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesMigrateMongoDBDatabaseToAutoscaleOptionalParams ): Promise<MongoDBResourcesMigrateMongoDBDatabaseToAutoscaleResponse>; /** * Migrate an Azure Cosmos DB MongoDB database from autoscale to manual throughput * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ beginMigrateMongoDBDatabaseToManualThroughput( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesMigrateMongoDBDatabaseToManualThroughputOptionalParams ): Promise< PollerLike< PollOperationState< MongoDBResourcesMigrateMongoDBDatabaseToManualThroughputResponse >, MongoDBResourcesMigrateMongoDBDatabaseToManualThroughputResponse > >; /** * Migrate an Azure Cosmos DB MongoDB database from autoscale to manual throughput * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param options The options parameters. */ beginMigrateMongoDBDatabaseToManualThroughputAndWait( resourceGroupName: string, accountName: string, databaseName: string, options?: MongoDBResourcesMigrateMongoDBDatabaseToManualThroughputOptionalParams ): Promise<MongoDBResourcesMigrateMongoDBDatabaseToManualThroughputResponse>; /** * Gets the MongoDB collection under an existing Azure Cosmos DB database account. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param options The options parameters. */ getMongoDBCollection( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, options?: MongoDBResourcesGetMongoDBCollectionOptionalParams ): Promise<MongoDBResourcesGetMongoDBCollectionResponse>; /** * Create or update an Azure Cosmos DB MongoDB Collection * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param createUpdateMongoDBCollectionParameters The parameters to provide for the current MongoDB * Collection. * @param options The options parameters. */ beginCreateUpdateMongoDBCollection( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, createUpdateMongoDBCollectionParameters: MongoDBCollectionCreateUpdateParameters, options?: MongoDBResourcesCreateUpdateMongoDBCollectionOptionalParams ): Promise< PollerLike< PollOperationState<MongoDBResourcesCreateUpdateMongoDBCollectionResponse>, MongoDBResourcesCreateUpdateMongoDBCollectionResponse > >; /** * Create or update an Azure Cosmos DB MongoDB Collection * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param createUpdateMongoDBCollectionParameters The parameters to provide for the current MongoDB * Collection. * @param options The options parameters. */ beginCreateUpdateMongoDBCollectionAndWait( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, createUpdateMongoDBCollectionParameters: MongoDBCollectionCreateUpdateParameters, options?: MongoDBResourcesCreateUpdateMongoDBCollectionOptionalParams ): Promise<MongoDBResourcesCreateUpdateMongoDBCollectionResponse>; /** * Deletes an existing Azure Cosmos DB MongoDB Collection. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param options The options parameters. */ beginDeleteMongoDBCollection( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, options?: MongoDBResourcesDeleteMongoDBCollectionOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes an existing Azure Cosmos DB MongoDB Collection. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param options The options parameters. */ beginDeleteMongoDBCollectionAndWait( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, options?: MongoDBResourcesDeleteMongoDBCollectionOptionalParams ): Promise<void>; /** * Gets the RUs per second of the MongoDB collection under an existing Azure Cosmos DB database account * with the provided name. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param options The options parameters. */ getMongoDBCollectionThroughput( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, options?: MongoDBResourcesGetMongoDBCollectionThroughputOptionalParams ): Promise<MongoDBResourcesGetMongoDBCollectionThroughputResponse>; /** * Update the RUs per second of an Azure Cosmos DB MongoDB collection * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param updateThroughputParameters The RUs per second of the parameters to provide for the current * MongoDB collection. * @param options The options parameters. */ beginUpdateMongoDBCollectionThroughput( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, updateThroughputParameters: ThroughputSettingsUpdateParameters, options?: MongoDBResourcesUpdateMongoDBCollectionThroughputOptionalParams ): Promise< PollerLike< PollOperationState< MongoDBResourcesUpdateMongoDBCollectionThroughputResponse >, MongoDBResourcesUpdateMongoDBCollectionThroughputResponse > >; /** * Update the RUs per second of an Azure Cosmos DB MongoDB collection * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param updateThroughputParameters The RUs per second of the parameters to provide for the current * MongoDB collection. * @param options The options parameters. */ beginUpdateMongoDBCollectionThroughputAndWait( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, updateThroughputParameters: ThroughputSettingsUpdateParameters, options?: MongoDBResourcesUpdateMongoDBCollectionThroughputOptionalParams ): Promise<MongoDBResourcesUpdateMongoDBCollectionThroughputResponse>; /** * Migrate an Azure Cosmos DB MongoDB collection from manual throughput to autoscale * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param options The options parameters. */ beginMigrateMongoDBCollectionToAutoscale( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, options?: MongoDBResourcesMigrateMongoDBCollectionToAutoscaleOptionalParams ): Promise< PollerLike< PollOperationState< MongoDBResourcesMigrateMongoDBCollectionToAutoscaleResponse >, MongoDBResourcesMigrateMongoDBCollectionToAutoscaleResponse > >; /** * Migrate an Azure Cosmos DB MongoDB collection from manual throughput to autoscale * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param options The options parameters. */ beginMigrateMongoDBCollectionToAutoscaleAndWait( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, options?: MongoDBResourcesMigrateMongoDBCollectionToAutoscaleOptionalParams ): Promise<MongoDBResourcesMigrateMongoDBCollectionToAutoscaleResponse>; /** * Migrate an Azure Cosmos DB MongoDB collection from autoscale to manual throughput * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param options The options parameters. */ beginMigrateMongoDBCollectionToManualThroughput( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, options?: MongoDBResourcesMigrateMongoDBCollectionToManualThroughputOptionalParams ): Promise< PollerLike< PollOperationState< MongoDBResourcesMigrateMongoDBCollectionToManualThroughputResponse >, MongoDBResourcesMigrateMongoDBCollectionToManualThroughputResponse > >; /** * Migrate an Azure Cosmos DB MongoDB collection from autoscale to manual throughput * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param options The options parameters. */ beginMigrateMongoDBCollectionToManualThroughputAndWait( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, options?: MongoDBResourcesMigrateMongoDBCollectionToManualThroughputOptionalParams ): Promise< MongoDBResourcesMigrateMongoDBCollectionToManualThroughputResponse >; /** * Retrieves continuous backup information for a Mongodb collection. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param location The name of the continuous backup restore location. * @param options The options parameters. */ beginRetrieveContinuousBackupInformation( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, location: ContinuousBackupRestoreLocation, options?: MongoDBResourcesRetrieveContinuousBackupInformationOptionalParams ): Promise< PollerLike< PollOperationState< MongoDBResourcesRetrieveContinuousBackupInformationResponse >, MongoDBResourcesRetrieveContinuousBackupInformationResponse > >; /** * Retrieves continuous backup information for a Mongodb collection. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName Cosmos DB database account name. * @param databaseName Cosmos DB database name. * @param collectionName Cosmos DB collection name. * @param location The name of the continuous backup restore location. * @param options The options parameters. */ beginRetrieveContinuousBackupInformationAndWait( resourceGroupName: string, accountName: string, databaseName: string, collectionName: string, location: ContinuousBackupRestoreLocation, options?: MongoDBResourcesRetrieveContinuousBackupInformationOptionalParams ): Promise<MongoDBResourcesRetrieveContinuousBackupInformationResponse>; }
the_stack
import { Dispatchable } from '../helpers/dispatchable'; import { Dic, Utils } from '../helpers/utils'; import { auth, debug, logger } from '../main'; import { DocType } from '../model/doc'; import { AppError, AppErrorType, AppProblem } from '../model/exceptions'; import { /*TokenUpdateWebMessage,*/ WebMessage, WebMessageType } from '../model/message'; import { PBICloudDataset, PBICloudDatasetConnectionMode } from '../model/pbi-dataset'; import { FormattedMeasure, TabularDatabase, TabularDatabaseServer, TabularMeasure } from '../model/tabular'; import { Account, SignInRequest } from './auth'; import { DiagnosticLevelType, FormatDaxOptions, Options, UpdateChannelType } from './options'; import { PBIDesktopReport, PBIDesktopReportConnectionMode } from '../model/pbi-report'; import { ThemeType } from './theme'; import { i18n } from '../model/i18n'; import { strings } from '../model/strings'; import { LogMessageObj } from './logger'; import { DateConfiguration, TableValidation } from '../model/dates'; import { ModelChanges } from '../model/model-changes'; import { PBICloudEnvironment } from '../model/pbi-cloud'; import { PowerBISignin } from '../view/powerbi-signin'; import { DialogResponse } from '../view/dialog'; declare global { interface External { receiveMessage(callback: { (message: any): void }): void sendMessage(message: any): void } } interface ApiRequest { action: string controller: AbortController timeout?: number aborted?: Utils.RequestAbortReason } export interface ProblemDetails { type?: string title?: string status?: number detail?: string instance?: string traceId?: string } export interface PBICloudAutenthicationRequest { userPrincipalName: string environment: PBICloudEnvironment } export interface FormatDaxRequest { options: FormatDaxRequestOptions measures: TabularMeasure[] } export interface FormatDaxRequestOptions extends TabularDatabaseServer, FormatDaxOptions { databaseName?: string } export interface UpdatePBIDesktopReportRequest{ report: PBIDesktopReport measures: FormattedMeasure[] } export interface UpdatePBICloudDatasetRequest{ dataset: PBICloudDataset measures: FormattedMeasure[] } export interface DatabaseUpdateResult { etag?: string } export enum DiagnosticMessageSeverity { None = 0, Warning = 1, Error = 2, } export enum DiagnosticMessageType { Text = 0, Json = 1, } export interface DiagnosticMessage { type: DiagnosticMessageType severity: DiagnosticMessageSeverity name?: string content?: string timestamp?: string } export enum ExportDataFormat { Csv = "Csv", Xlsx = "Xlsx" } export enum ExportDataStatus { Unknown = 0, Running = 1, Completed = 2, Canceled = 3, Failed = 4, Truncated = 5 } export interface ExportDataTable { status: ExportDataStatus name?: string rows: number } export interface ExportDataJob { status: ExportDataStatus tables?: ExportDataTable[] path?: string } export interface ExportDelimitedTextSettings { tables: string[] unicodeEncoding: boolean delimiter?: string quoteStringFields: boolean createSubfolder: boolean } export interface ExportExcelSettings { tables: string[] createExportSummary: boolean } export interface ExportDelimitedTextFromPBIReportRequest{ settings: ExportDelimitedTextSettings report: PBIDesktopReport } export interface ExportDelimitedTextFromPBICloudDatasetRequest{ settings: ExportDelimitedTextSettings dataset: PBICloudDataset } export interface ExportExcelFromPBIReportRequest{ settings: ExportExcelSettings report: PBIDesktopReport } export interface ExportExcelFromPBICloudDatasetRequest{ settings: ExportExcelSettings dataset: PBICloudDataset } export interface ManageDatesPBIDesktopReportConfigurationRequest { configuration: DateConfiguration report: PBIDesktopReport } export interface ManageDatesPreviewChangesFromPBIDesktopReportRequest { settings: { configuration: DateConfiguration previewRows: number } report: PBIDesktopReport } export interface BravoUpdate { updateChannel: UpdateChannelType currentVersion?: string installedVersion?: string downloadUrl?: string changelogUrl?: string isNewerVersion: boolean } export interface ApiLogSettings { messageLevel?: DiagnosticLevelType // Minimum diagnostic level required to log the message dataLevel?: DiagnosticLevelType // Minimum diagnostic level required to log the obj data } export class Host extends Dispatchable { static DEFAULT_TIMEOUT = 5 * 60 * 1000; address: string; token: string; requests: Dic<ApiRequest>; constructor(address: string, token: string) { super(); this.listen(); this.requests = {}; this.address = address; this.token = token; } // Listen for events listen() { try { window.external.receiveMessage(message => { const webMessage = <WebMessage>JSON.parse(message); if (!webMessage || !("type" in webMessage)) return; try { logger.log("Message", { content: webMessage }); } catch (ignore) {} this.trigger(WebMessageType[webMessage.type], webMessage); }); } catch (ignore) { // Ignore error } } // Send message to host send(message: any) { try { window.external.sendMessage(message); } catch (e) { // Ignore error } } // Functions apiCall(action: string, data = {}, options: RequestInit = {}, signinIfRequired = true, logSettings: ApiLogSettings = null, timeout = Host.DEFAULT_TIMEOUT): Promise<any> { let debugResponse = debug.catchApiCall(action, data); if (debugResponse !== null) return debugResponse; let requestId = Utils.Text.uuid(); let abortController = new AbortController(); this.requests[requestId] = { action: action, controller: abortController }; if (!("method" in options)) options["method"] = "GET"; options["signal"] = abortController.signal; if (timeout) { this.requests[requestId].timeout = window.setTimeout(()=> { this.apiAbortById(requestId, "timeout"); }, timeout); } let logMessageId = (logSettings ? this.apiLog(action, data, logSettings) : null); return Utils.Request.ajax(`${this.address}${action}`, data, options, this.token) .then(response => { if (logSettings) { logSettings.dataLevel = DiagnosticLevelType.Verbose; //Response data is visible only if Verbose this.apiLog(action, response, logSettings, logMessageId); } return response; }) .catch(async (response: Response | Error) => { let problem; //Catch unhandled errors, like an aborted request if (response instanceof Error) { let status = Utils.ResponseStatusCode.InternalError; if (Utils.Request.isAbort(response)) { if (requestId in this.requests && this.requests[requestId].aborted == "timeout") status = Utils.ResponseStatusCode.Timeout; else status = Utils.ResponseStatusCode.Aborted; } problem = { status: status, title: response.message } } else { problem = await response.json(); } let error = AppError.InitFromProblem(problem); if (error.type == AppErrorType.Auth && signinIfRequired) { //Remove the timeout because the call will be re-executed this.apiCallCompleted(requestId); if (auth.account) { // Try automatic sign-in with saved account (if any) const signinRequest: SignInRequest = { userPrincipalName: auth.account.userPrincipalName, environmentName: auth.account.environmentName, environments: auth.account.environments }; return auth.signIn(signinRequest) .then(()=>{ return this.apiCall(action, data, options, false, null, timeout); }) .catch(error => { throw error; }); } else { // Show the sign-in dialog let signinDialog = new PowerBISignin(); return signinDialog.show() .then((response: DialogResponse) => { if (response.action == "signin") return this.apiCall(action, data, options, false, null, timeout); throw error; }) .catch(error => { throw error; }); } } else { throw error; } }) .finally(()=>{ this.apiCallCompleted(requestId); }); } apiCallCompleted(requestId: string) { if (requestId in this.requests) { if ("timeout" in this.requests[requestId]) window.clearTimeout(this.requests[requestId].timeout); delete this.requests[requestId]; } } apiAbortById(requestId: string, reason: Utils.RequestAbortReason = "user") { if (requestId in this.requests) { try { this.requests[requestId].aborted = reason; this.requests[requestId].controller.abort(); } catch (ignore) {} try { logger.log(`${this.requests[requestId].action} ${reason == "user" ? "aborted" : "timeout"}`); } catch (ignore) {} } } apiAbortByAction(actions: string | string[], reason: Utils.RequestAbortReason = "user") { for (let requestId in this.requests) { if (Utils.Obj.isArray(actions) ? actions.indexOf(this.requests[requestId].action) >= 0 : actions == this.requests[requestId].action) { this.apiAbortById(requestId, reason); } } } apiLog(action: string, data: any, settings?: ApiLogSettings, messageId?: string): string { let obj: LogMessageObj; if (Utils.Obj.isSet(data) && !Utils.Obj.isEmpty(data)) { obj = { content: data, } if (settings && settings.dataLevel) obj.level = settings.dataLevel; } let id; try { if (messageId) { logger.updateLog(messageId, obj); } else { let messageLevel = (settings && settings.messageLevel ? settings.messageLevel : DiagnosticLevelType.Basic); id = logger.log(action, obj, messageLevel); } } catch (ignore) {} return id; } /**** APIs ****/ /* Authentication */ getEnvironments(userPrincipalName: string) { return <Promise<PBICloudEnvironment[]>>this.apiCall("auth/powerbi/GetEnvironments", { userPrincipalName: userPrincipalName }, {}, false); } signIn(request?: PBICloudAutenthicationRequest) { const logSettings: ApiLogSettings = {}; return <Promise<Account>>this.apiCall("auth/powerbi/SignIn", request || {}, { method: "POST" }, false, logSettings); } /*signIn(userPrincipalName?: string) { const logSettings: ApiLogSettings = {}; return <Promise<Account>>this.apiCall("auth/powerbi/SignIn", userPrincipalName ? { userPrincipalName: userPrincipalName } : {}, {}, false, logSettings); }*/ signOut() { const logSettings: ApiLogSettings = {}; return this.apiCall("auth/powerbi/SignOut", {}, {}, false, logSettings); } getUserAvatar() { return <Promise<string>>this.apiCall("auth/GetUserAvatar", {}, {}, false); } /* Analyze Model */ getModelFromVpax(file: File) { const logSettings: ApiLogSettings = {}; return <Promise<TabularDatabase>>this.apiCall("api/GetModelFromVpax", file, { method: "POST", headers: { /* IMPORTANT */ } }, true, logSettings); } getModelFromReport(report: PBIDesktopReport) { const logSettings: ApiLogSettings = {}; return this.validateReportConnection(report) .then(report => { return this.apiCall("api/GetModelFromReport", report, { method: "POST" }, true, logSettings) .then(database => <[TabularDatabase, PBIDesktopReport]>[database, report]); }); } validateReportConnection(report: PBIDesktopReport): Promise<PBIDesktopReport> { const logSettings: ApiLogSettings = {}; const connectionError = (connectionMode: PBIDesktopReportConnectionMode) => { let errorKey = `errorReportConnection${PBIDesktopReportConnectionMode[connectionMode]}`; let message = i18n(errorKey in strings ? (<any>strings)[errorKey] : strings.errorConnectionUnsupported); return AppError.InitFromProblemCode(AppProblem.ConnectionUnsupported, message); }; return new Promise((resolve, reject) => { if (report.connectionMode == PBIDesktopReportConnectionMode.Supported) { resolve(report); } else { this.apiLog("api/GetModelFromReport", report, logSettings); reject(connectionError(report.connectionMode)); } }); } getModelFromDataset(dataset: PBICloudDataset) { const logSettings: ApiLogSettings = {}; return this.validateDatasetConnection(dataset) .then(dataset => { return this.apiCall("api/GetModelFromDataset", dataset, { method: "POST" }, true, logSettings) .then(database => <[TabularDatabase, PBICloudDataset]>[database, dataset]); }); } validateDatasetConnection(dataset: PBICloudDataset): Promise<PBICloudDataset> { const logSettings: ApiLogSettings = {}; const connectionError = (connectionMode: PBICloudDatasetConnectionMode, diagnostic?: any) => { let errorKey = `errorDatasetConnection${PBICloudDatasetConnectionMode[connectionMode]}`; let message = i18n(errorKey in strings ? (<any>strings)[errorKey] : strings.errorConnectionUnsupported); let details = (diagnostic ? JSON.stringify(diagnostic) : null); return AppError.InitFromProblemCode(AppProblem.ConnectionUnsupported, message, details); }; return new Promise((resolve, reject) => { this.listDatasets() .then((datasets: PBICloudDataset[]) => { let foundDataset = dataset; for (let i = 0; i < datasets.length; i++) { if (datasets[i].serverName == dataset.serverName && datasets[i].databaseName == dataset.databaseName) { foundDataset = datasets[i]; if (foundDataset.connectionMode == PBICloudDatasetConnectionMode.Supported) { resolve(foundDataset); return; } break; } } this.apiLog("api/GetModelFromDataset", foundDataset, logSettings); reject(connectionError(foundDataset.connectionMode, foundDataset.diagnostic)); }) .catch(error => { reject(error); }); }); } listReports() { return <Promise<PBIDesktopReport[]>>this.apiCall("api/ListReports"); } listDatasets() { const logSettings: ApiLogSettings = {}; return <Promise<PBICloudDataset[]>>this.apiCall("api/ListDatasets", {}, {}, true, logSettings); } exportVpax(datasource: PBIDesktopReport | PBICloudDataset, type: DocType) { return <Promise<boolean>>this.apiCall(`api/ExportVpaxFrom${type == DocType.dataset ? "Dataset" : "Report"}`, datasource, { method: "POST" }) .then(response => (response !== null)); } abortExportVpax(type: DocType) { this.apiAbortByAction(`api/ExportVpaxFrom${type == DocType.dataset ? "Dataset" : "Report"}`); } /* Format DAX */ formatDax(request: FormatDaxRequest) { const logSettings: ApiLogSettings = {}; return <Promise<FormattedMeasure[]>>this.apiCall("api/FormatDax", request, { method: "POST" }, true, logSettings); } abortFormatDax(type: DocType) { this.apiAbortByAction(["api/FormatDax", `api/Update${type == DocType.dataset ? "Dataset" : "Report"}`]); } updateModel(request: UpdatePBIDesktopReportRequest | UpdatePBICloudDatasetRequest, type: DocType) { const logSettings: ApiLogSettings = {}; return <Promise<DatabaseUpdateResult>>this.apiCall(`api/Update${type == DocType.dataset ? "Dataset" : "Report"}`, request, { method: "POST" }, true, logSettings); } /* Export Data */ exportData(request: ExportDelimitedTextFromPBIReportRequest | ExportDelimitedTextFromPBICloudDatasetRequest | ExportExcelFromPBIReportRequest | ExportExcelFromPBICloudDatasetRequest, format: ExportDataFormat, type: DocType) { return <Promise<ExportDataJob>>this.apiCall(`api/Export${format}From${type == DocType.dataset ? "Dataset" : "Report"}`, request, { method: "POST" }, true, null, 0); } queryExportData(datasource: PBIDesktopReport | PBICloudDataset, type: DocType) { return <Promise<ExportDataJob>>this.apiCall(`api/QueryExportFrom${type == DocType.dataset ? "Dataset" : "Report"}`, datasource, { method: "POST" }); } abortExportData(type: DocType) { let actions: string[] = []; Object.values(ExportDataFormat).forEach(format => { actions.push(`api/Export${format}From${type == DocType.dataset ? "Dataset" : "Report"}`); }); this.apiAbortByAction(actions); } /* Manage Dates */ manageDatesGetConfigurations(datasource: PBIDesktopReport) { return <Promise<DateConfiguration[]>>this.apiCall("ManageDates/GetConfigurationsForReport", datasource, { method: "POST" }); } manageDatesValidateTableNames(request: ManageDatesPBIDesktopReportConfigurationRequest) { return <Promise<DateConfiguration>>this.apiCall("ManageDates/ValidateConfigurationForReport", request, { method: "POST" }); } manageDatesPreviewChanges(request: ManageDatesPreviewChangesFromPBIDesktopReportRequest) { return <Promise<ModelChanges>>this.apiCall("ManageDates/GetPreviewChangesFromReport", request, { method: "POST" }); } abortManageDatesPreviewChanges() { this.apiAbortByAction("ManageDates/GetPreviewChangesFromReport"); } manageDatesUpdate(request: ManageDatesPBIDesktopReportConfigurationRequest) { return this.apiCall("ManageDates/UpdateReport", request, { method: "POST" }); } abortManageDatesUpdate() { this.apiAbortByAction("ManageDates/UpdateReport"); } /* Application */ changeTheme(theme: ThemeType) { return this.apiCall("api/ChangeTheme", { theme: theme }); } getOptions() { return <Promise<Options>>this.apiCall("api/GetOptions"); } updateOptions(options: Options) { return this.apiCall("api/UpdateOptions", options, { method: "POST" }) .then(() => true) .catch(ignore => false); } navigateTo(url: string) { return this.apiCall("api/NavigateTo", { address: url }); } getDiagnostics(all = false) { return <Promise<DiagnosticMessage[]>>this.apiCall("api/GetDiagnostics", { all: all }); } getCurrentVersion(updateChannel: UpdateChannelType) { return <Promise<BravoUpdate>>this.apiCall("api/GetCurrentVersion", { updateChannel: updateChannel }); } fileSystemOpen(path: string) { return this.apiCall("api/FileSystemOpen", { path: path }); } openPBIX() { return <Promise<PBIDesktopReport>>this.apiCall("api/PBIDesktopOpenPBIX", { waitForStarted: true }); } abortOpenPBIX() { this.apiAbortByAction("api/PBIDesktopOpenPBIX"); } updateProxyCredentials() { return <Promise<boolean>>this.apiCall("api/UpdateProxyCredentials") .then(response => (response !== null)); } deleteProxyCredentials() { this.apiCall("api/DeleteProxyCredentials"); } openCredentialsManager() { this.apiCall("api/OpenControlPanelItem", { canonicalName: "/name Microsoft.CredentialManager /page ?SelectedVault=CredmanVault" }); } }
the_stack
import { mocked } from "ts-jest/utils"; import { User } from "../../models/user"; import { Dashboard, DashboardState, DashboardItem, } from "../../models/dashboard"; import DynamoDBService from "../../services/dynamodb"; import DashboardRepository from "../dashboard-repo"; import WidgetFactory from "../../factories/widget-factory"; import DashboardFactory from "../../factories/dashboard-factory"; import TopicAreaFactory from "../../factories/topicarea-factory"; import { WidgetType } from "../../models/widget"; jest.mock("../../services/dynamodb"); let user: User; let tableName: string; let repo: DashboardRepository; let dynamodb = mocked(DynamoDBService.prototype); beforeEach(() => { user = { userId: "test" }; tableName = "MainTable"; process.env.MAIN_TABLE = tableName; DynamoDBService.getInstance = jest.fn().mockReturnValue(dynamodb); repo = DashboardRepository.getInstance(); }); describe("DashboardRepository", () => { it("should be a singleton", () => { const repo2 = DashboardRepository.getInstance(); expect(repo).toBe(repo2); }); }); describe("create", () => { it("should call putItem on dynamodb", async () => { const now = new Date(); const dashboard: Dashboard = { id: "123", version: 1, name: "Dashboard1", topicAreaId: "456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Draft, parentDashboardId: "123", createdBy: user.userId, updatedAt: now, releaseNotes: "", }; const item = DashboardFactory.toItem(dashboard); await repo.putDashboard(dashboard); expect(dynamodb.put).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, Item: item, }) ); }); }); describe("createNew", () => { it("should call putItem on dynamodb", async () => { const dashboard = DashboardFactory.createNew( "Dashboard1", "456", "Topic1", "Description Test", user ); const item = DashboardFactory.toItem(dashboard); await repo.putDashboard(dashboard); expect(dynamodb.put).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, Item: item, }) ); }); }); describe("updateDashboard", () => { it("should call updateItem with the correct keys", async () => { const now = new Date(); await repo.updateDashboard( "123", "Dashboard1", "456", "Topic1", false, {}, "Description Test", now.toISOString(), user ); expect(dynamodb.update).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, Key: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), }, }) ); }); it("should call update with all the fields", async () => { const now = new Date(); jest.useFakeTimers("modern"); jest.setSystemTime(now); await repo.updateDashboard( "123", "Dashboard1", "456", "Topic1", false, {}, "Description Test", now.toISOString(), user ); expect(dynamodb.update).toHaveBeenCalledWith( expect.objectContaining({ UpdateExpression: "set #dashboardName = :dashboardName, #topicAreaId = :topicAreaId, #topicAreaName = :topicAreaName, #displayTableOfContents = :displayTableOfContents, #description = :description, #updatedAt = :updatedAt, #updatedBy = :userId, #tableOfContents = :tableOfContents", ExpressionAttributeValues: { ":dashboardName": "Dashboard1", ":topicAreaId": TopicAreaFactory.itemId("456"), ":topicAreaName": "Topic1", ":displayTableOfContents": false, ":tableOfContents": {}, ":description": "Description Test", ":lastUpdatedAt": now.toISOString(), ":updatedAt": now.toISOString(), ":userId": user.userId, }, }) ); }); }); describe("getDashboardVersions", () => { it("returns empty array when there is no dashboard", async () => { dynamodb.query = jest.fn().mockReturnValue({ Items: [] }); const dashboard = await repo.getDashboardVersions("123"); expect(dashboard).toEqual([]); }); it("performs a query using GSI and a filter by state", async () => { await repo.getDashboardVersions("123"); expect(dynamodb.query).toBeCalledWith({ TableName: tableName, IndexName: "byParentDashboard", KeyConditionExpression: "parentDashboardId = :parentDashboardId", ExpressionAttributeValues: { ":parentDashboardId": "123", }, }); }); it("returns a dashboard when is found", async () => { const existingDraft: DashboardItem = { pk: "Dashboard#xyz", sk: "Dashboard#xyz", type: "Dashboard", version: 2, parentDashboardId: "123", topicAreaId: "TopicArea#abc", topicAreaName: "Health", displayTableOfContents: false, dashboardName: "My Health Dashboard", description: "A relevant description", createdBy: "johndoe", updatedBy: "johndoe", updatedAt: new Date().toISOString(), state: "Draft", releaseNotes: "", }; dynamodb.query = jest.fn().mockReturnValue({ Items: [existingDraft] }); const dashboard = DashboardFactory.fromItem(existingDraft); const dashboardVersions = await repo.getDashboardVersions("123"); expect(dashboardVersions).toEqual([dashboard]); }); }); describe("DashboardRepository.publishDashboard", () => { let now: Date; beforeEach(() => { now = new Date(); jest.useFakeTimers("modern"); jest.setSystemTime(now); dynamodb.transactWrite = jest.fn(); }); it("should call update with the correct keys and all the fields", async () => { repo.getDashboardVersions = jest.fn().mockReturnValue([]); await repo.publishDashboard( "123", "456", now.toISOString(), "release note test", user, "my-friendly-url" ); expect(dynamodb.transactWrite).toHaveBeenCalledWith({ TransactItems: [ { Update: { TableName: tableName, Key: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), }, UpdateExpression: "set #state = :state, #updatedAt = :updatedAt, " + "#releaseNotes = :releaseNotes, #updatedBy = :userId, " + "#publishedBy = :userId, #friendlyURL = :friendlyURL", ExpressionAttributeValues: { ":state": "Published", ":lastUpdatedAt": now.toISOString(), ":updatedAt": now.toISOString(), ":releaseNotes": "release note test", ":userId": user.userId, ":friendlyURL": "my-friendly-url", }, ConditionExpression: "#updatedAt <= :lastUpdatedAt", ExpressionAttributeNames: { "#releaseNotes": "releaseNotes", "#state": "state", "#updatedAt": "updatedAt", "#updatedBy": "updatedBy", "#publishedBy": "publishedBy", "#friendlyURL": "friendlyURL", }, }, }, ], }); }); it("should move an Archived version to inactive", async () => { const parentDashboardId = "abc"; // Simulate there is an archived version already const getDashboardVersions = jest.spyOn(repo, "getDashboardVersions"); getDashboardVersions.mockReturnValue( Promise.resolve([ { id: "001", version: 1, name: "Archived Dashboard", topicAreaId: "456", topicAreaName: "Bananas", displayTableOfContents: false, description: "Description Test", state: DashboardState.Archived, parentDashboardId: parentDashboardId, createdBy: user.userId, updatedAt: new Date(), releaseNotes: "", }, ]) ); await repo.publishDashboard( "002", parentDashboardId, new Date().toISOString(), "release note test", user, "my-friendly-url" ); const transaction = dynamodb.transactWrite.mock.calls[0][0]; expect(transaction.TransactItems).toHaveLength(2); expect(transaction.TransactItems).toEqual( expect.arrayContaining([ expect.objectContaining({ Update: { TableName: tableName, Key: { pk: DashboardFactory.itemId("001"), sk: DashboardFactory.itemId("001"), }, UpdateExpression: "set #state = :state, #updatedAt = :updatedAt, #updatedBy = :userId " + "REMOVE #friendlyURL", // Make sure friendlyURL is removed ExpressionAttributeValues: { ":state": "Inactive", // Verify Archived version moves to Inactive ":updatedAt": now.toISOString(), ":userId": user.userId, }, ExpressionAttributeNames: { "#state": "state", "#updatedAt": "updatedAt", "#updatedBy": "updatedBy", "#friendlyURL": "friendlyURL", }, }, }), ]) ); getDashboardVersions.mockRestore(); }); it("should move a Published version to inactive", async () => { const parentDashboardId = "abc"; // Simulate there is a Published version already const getDashboardVersions = jest.spyOn(repo, "getDashboardVersions"); getDashboardVersions.mockReturnValue( Promise.resolve([ { id: "001", version: 1, name: "Archived Dashboard", topicAreaId: "456", topicAreaName: "Bananas", displayTableOfContents: false, description: "Description Test", state: DashboardState.Published, // PUBLISHED parentDashboardId: parentDashboardId, createdBy: user.userId, updatedAt: new Date(), releaseNotes: "", }, ]) ); await repo.publishDashboard( "002", parentDashboardId, new Date().toISOString(), "release note test", user, "my-friendly-url" ); const transaction = dynamodb.transactWrite.mock.calls[0][0]; expect(transaction.TransactItems).toHaveLength(2); expect(transaction.TransactItems).toEqual( expect.arrayContaining([ expect.objectContaining({ Update: { TableName: tableName, Key: { pk: DashboardFactory.itemId("001"), sk: DashboardFactory.itemId("001"), }, UpdateExpression: "set #state = :state, #updatedAt = :updatedAt, #updatedBy = :userId " + "REMOVE #friendlyURL", // Make sure friendlyURL is removed ExpressionAttributeValues: { ":state": "Inactive", // Verify Published version moves to Inactive ":updatedAt": now.toISOString(), ":userId": user.userId, }, ExpressionAttributeNames: { "#state": "state", "#updatedAt": "updatedAt", "#updatedBy": "updatedBy", "#friendlyURL": "friendlyURL", }, }, }), ]) ); getDashboardVersions.mockRestore(); }); }); describe("publishPendingDashboard", () => { let updatedDashboard: Dashboard; const now = new Date(); beforeEach(() => { const updateResult = { Attributes: {} }; dynamodb.update = jest.fn().mockReturnValue(updateResult); jest .spyOn(DashboardFactory, "fromItem") .mockReturnValueOnce(updatedDashboard); jest.useFakeTimers("modern"); jest.setSystemTime(now); }); it("should call update with the correct keys", async () => { await repo.publishPendingDashboard("123", now.toISOString(), user); expect(dynamodb.update).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, Key: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), }, }) ); }); it("should call update with all the fields", async () => { await repo.publishPendingDashboard( "123", now.toISOString(), user, "Lorem ipsum" ); expect(dynamodb.update).toHaveBeenCalledWith( expect.objectContaining({ UpdateExpression: "set #state = :state, #updatedAt = :updatedAt, #updatedBy = :userId, " + "#submittedBy = :userId, #releaseNotes = :releaseNotes", ExpressionAttributeValues: { ":state": "PublishPending", ":lastUpdatedAt": now.toISOString(), ":updatedAt": now.toISOString(), ":userId": user.userId, ":releaseNotes": "Lorem ipsum", }, }) ); }); it("returns the updated dashboard", async () => { const dashboard = await repo.publishPendingDashboard( "123", now.toISOString(), user ); expect(dashboard).toBe(updatedDashboard); expect(dynamodb.update).toBeCalledWith( expect.objectContaining({ ReturnValues: "ALL_NEW", }) ); }); }); describe("DashboardRepository.archiveDashboard", () => { let now: Date; beforeEach(() => { now = new Date(); jest.useFakeTimers("modern"); jest.setSystemTime(now); }); it("should call update with the correct keys", async () => { await repo.archiveDashboard("123", now.toISOString(), user); expect(dynamodb.update).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, Key: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), }, }) ); }); it("should call update with all the fields", async () => { await repo.archiveDashboard("123", now.toISOString(), user); expect(dynamodb.update).toHaveBeenCalledWith( expect.objectContaining({ UpdateExpression: "set #state = :state, #updatedAt = :updatedAt, #updatedBy = :userId, " + "#archivedBy = :userId REMOVE #friendlyURL", ExpressionAttributeValues: { ":state": "Archived", ":lastUpdatedAt": now.toISOString(), ":updatedAt": now.toISOString(), ":userId": user.userId, }, }) ); }); }); describe("DashboardRepository.moveToDraft", () => { let now: Date; beforeEach(() => { now = new Date(); jest.useFakeTimers("modern"); jest.setSystemTime(now); }); it("should call update with the correct keys", async () => { await repo.moveToDraft("123", now.toISOString(), user); expect(dynamodb.update).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, Key: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), }, }) ); }); it("should call update with all the fields", async () => { await repo.moveToDraft("123", now.toISOString(), user); expect(dynamodb.update).toHaveBeenCalledWith( expect.objectContaining({ UpdateExpression: "set #state = :state, #updatedAt = :updatedAt, #updatedBy = :userId, #submittedBy = :noUserId", ExpressionAttributeValues: { ":state": "Draft", ":lastUpdatedAt": now.toISOString(), ":updatedAt": now.toISOString(), ":userId": user.userId, ":noUserId": "", }, }) ); }); }); describe("DashboardRepository.delete", () => { it("should call delete with the correct key", async () => { await repo.delete("123"); expect(dynamodb.delete).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, Key: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), }, }) ); }); }); describe("listDashboards", () => { it("should query using the correct GSI", async () => { // Mock query response dynamodb.query = jest.fn().mockReturnValue({}); await repo.listDashboards(); expect(dynamodb.query).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, IndexName: "byType", }) ); }); it("returns a list of dashboards", async () => { // Mock query response const now = new Date(); dynamodb.query = jest.fn().mockReturnValue({ Items: [ { pk: "Dashboard#123", sk: "Dashboard#123", topicAreaId: "TopicArea#456", topicAreaName: "Topic 1", dashboardName: "Test name", description: "description test", createdBy: "test", updatedBy: "test", submittedBy: "test", publishedBy: "test", archivedBy: "test", deletedBy: "test", updatedAt: now.toISOString(), state: "Draft", }, ], }); const list = await repo.listDashboards(); expect(list.length).toEqual(1); expect(list[0]).toEqual({ id: "123", name: "Test name", topicAreaId: "456", topicAreaName: "Topic 1", description: "description test", createdBy: "test", updatedBy: "test", submittedBy: "test", publishedBy: "test", archivedBy: "test", deletedBy: "test", updatedAt: now, state: "Draft", }); }); it("returns a dashboard by id", async () => { // Mock query response const now = new Date(); dynamodb.get = jest.fn().mockReturnValue({ Item: { pk: "Dashboard#123", sk: "Dashboard#123", topicAreaId: "TopicArea#456", topicAreaName: "Topic 1", dashboardName: "Test name", description: "description test", createdBy: "test", updatedBy: "test", submittedBy: "test", publishedBy: "test", archivedBy: "test", deletedBy: "test", updatedAt: now.toISOString(), state: "Draft", }, }); const item = await repo.getDashboardById("123"); expect(item).toEqual({ id: "123", name: "Test name", topicAreaId: "456", topicAreaName: "Topic 1", description: "description test", createdBy: "test", updatedBy: "test", submittedBy: "test", publishedBy: "test", archivedBy: "test", deletedBy: "test", updatedAt: now, state: "Draft", }); }); it("returns a list of dashboards within a topic area", async () => { // Mock query response dynamodb.query = jest.fn().mockReturnValue({}); const topicAreaId = "456"; await repo.listDashboardsInTopicArea(topicAreaId); expect(dynamodb.query).toHaveBeenCalledWith( expect.objectContaining({ TableName: tableName, KeyConditionExpression: "#topicAreaId = :topicAreaId", ExpressionAttributeValues: { ":topicAreaId": TopicAreaFactory.itemId(topicAreaId), }, }) ); const now = new Date(); // Mock query response dynamodb.query = jest.fn().mockReturnValue({ Items: [ { pk: "Dashboard#123", sk: "Dashboard#123", type: "Dashboard", topicAreaId: `TopicArea#${topicAreaId}`, topicAreaName: "Topic 1", dashboardName: "Test name", description: "description test", createdBy: "test", updatedBy: "test", submittedBy: "test", publishedBy: "test", archivedBy: "test", deletedBy: "test", updatedAt: now.toISOString(), state: "Draft", }, ], }); const list = await repo.listDashboardsInTopicArea(topicAreaId); expect(list.length).toEqual(1); expect(list[0]).toEqual({ id: "123", name: "Test name", topicAreaId: topicAreaId, topicAreaName: "Topic 1", description: "description test", createdBy: "test", updatedBy: "test", submittedBy: "test", publishedBy: "test", archivedBy: "test", deletedBy: "test", updatedAt: now, state: "Draft", }); }); }); describe("getDashboardWithWidgets", () => { it("throws an error when dashboardId is not found", () => { dynamodb.query = jest.fn().mockReturnValue({ Items: [] }); return expect(repo.getDashboardWithWidgets("123")).rejects.toThrowError(); }); it("returns a dashboard with no widgets", async () => { dynamodb.query = jest.fn().mockReturnValue({ Items: [ { pk: "Dashboard#123", sk: "Dashboard#123", name: "AWS Dashboard", type: "Dashboard", topicAreaId: "TopicArea#cb9ad", }, ], }); const dashboard = await repo.getDashboardWithWidgets("123"); expect(dashboard.id).toEqual("123"); expect(dashboard.widgets).toHaveLength(0); }); it("returns a dashboard with widgets", async () => { dynamodb.query = jest.fn().mockReturnValue({ Items: [ { pk: "Dashboard#123", sk: "Dashboard#123", name: "AWS Dashboard", type: "Dashboard", topicAreaId: "TopicArea#cb9ad", }, { pk: "Dashboard#123", sk: "Widget#abc", type: "Widget", name: "Some name", widgetType: "Text", content: {}, }, ], }); const dashboard = await repo.getDashboardWithWidgets("123"); expect(dashboard.widgets).toHaveLength(1); }); }); describe("listPublishedDashboards", () => { it("returns empty array when no published dashboards found", async () => { dynamodb.query = jest.fn().mockReturnValue({ Items: [] }); const dashboards = await repo.listPublishedDashboards(); expect(dashboards.length).toEqual(0); }); it("performs a query and filters by state=Published", async () => { await repo.listPublishedDashboards(); expect(dynamodb.query).toBeCalledWith({ TableName: tableName, IndexName: "byType", KeyConditionExpression: "#type = :type", FilterExpression: "#state = :state", ExpressionAttributeNames: { "#type": "type", "#state": "state", }, ExpressionAttributeValues: { ":type": "Dashboard", ":state": DashboardState.Published, }, }); }); }); describe("getCurrentDraft", () => { it("returns null when there is no draft", async () => { dynamodb.query = jest.fn().mockReturnValue({ Items: [] }); const draft = await repo.getCurrentDraft("123"); expect(draft).toBeNull(); }); it("performs a query using GSI and a filter by state", async () => { await repo.getCurrentDraft("123"); expect(dynamodb.query).toBeCalledWith({ TableName: tableName, IndexName: "byParentDashboard", KeyConditionExpression: "parentDashboardId = :parentDashboardId", FilterExpression: "#state = :state", ExpressionAttributeNames: { "#state": "state", }, ExpressionAttributeValues: { ":parentDashboardId": "123", ":state": DashboardState.Draft, }, }); }); it("returns a dashboard when a draft is found", async () => { const existingDraft: DashboardItem = { pk: "Dashboard#xyz", sk: "Dashboard#xyz", type: "Dashboard", version: 2, parentDashboardId: "123", topicAreaId: "TopicArea#abc", topicAreaName: "Health", displayTableOfContents: false, dashboardName: "My Health Dashboard", description: "A relevant description", createdBy: "johndoe", updatedAt: new Date().toISOString(), state: "Draft", releaseNotes: "", }; dynamodb.query = jest.fn().mockReturnValue({ Items: [existingDraft] }); const dashboard = DashboardFactory.fromItem(existingDraft); const draft = await repo.getCurrentDraft("123"); expect(draft).toEqual(dashboard); }); }); describe("DashboardRepository.saveDashboardAndWidgets", () => { it("should call saveDashboardAndWidgets with the correct key", async () => { const now = new Date(); jest.useFakeTimers("modern"); jest.setSystemTime(now); const dashboard: Dashboard = { id: "123", version: 1, name: "Dashboard1", topicAreaId: "456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Draft, parentDashboardId: "123", createdBy: user.userId, updatedAt: now, releaseNotes: "", widgets: [ { id: "abc", dashboardId: "123", widgetType: WidgetType.Text, order: 0, updatedAt: new Date(), name: "AWS", content: {}, }, ], }; await repo.saveDashboardAndWidgets(dashboard); expect(dynamodb.transactWrite).toHaveBeenCalledWith( expect.objectContaining({ TransactItems: [ { Put: { TableName: tableName, Item: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), version: 1, dashboardName: "Dashboard1", topicAreaId: "TopicArea#456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Draft, type: "Dashboard", parentDashboardId: "123", createdBy: user.userId, updatedAt: now.toISOString(), releaseNotes: "", }, }, }, { Put: { Item: { content: {}, name: "AWS", order: 0, pk: "Dashboard#123", sk: "Widget#abc", type: "Widget", updatedAt: now.toISOString(), widgetType: "Text", }, TableName: "MainTable", }, }, ], }) ); }); }); describe("DashboardRepository.deleteDashboardsAndWidgets", () => { it("should call delete dashboard with the correct key", async () => { repo.getDashboardWithWidgets = jest .fn() .mockReturnValueOnce({ id: "123", state: DashboardState.Draft, widgets: [ { id: "abc", }, ], }) .mockReturnValueOnce({ id: "456", state: DashboardState.Draft, }); await repo.deleteDashboardsAndWidgets(["123", "456"], user); expect(dynamodb.transactWrite).toHaveBeenCalledWith( expect.objectContaining({ TransactItems: [ { Update: { TableName: tableName, Key: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), }, UpdateExpression: "set #deletedBy = :userId", ExpressionAttributeValues: { ":userId": user.userId, }, ExpressionAttributeNames: { "#deletedBy": "deletedBy", }, }, }, { Update: { TableName: tableName, Key: { pk: DashboardFactory.itemId("456"), sk: DashboardFactory.itemId("456"), }, UpdateExpression: "set #deletedBy = :userId", ExpressionAttributeValues: { ":userId": user.userId, }, ExpressionAttributeNames: { "#deletedBy": "deletedBy", }, }, }, ], }) ); expect(dynamodb.transactWrite).toHaveBeenCalledWith( expect.objectContaining({ TransactItems: [ { Delete: { TableName: tableName, Key: { pk: DashboardFactory.itemId("123"), sk: DashboardFactory.itemId("123"), }, }, }, { Delete: { TableName: tableName, Key: { pk: WidgetFactory.itemPk("123"), sk: WidgetFactory.itemSk("abc"), }, }, }, { Delete: { TableName: tableName, Key: { pk: DashboardFactory.itemId("456"), sk: DashboardFactory.itemId("456"), }, }, }, ], }) ); }); }); describe("getNextVersionNumber", () => { let getDashboardVersions: jest.SpyInstance; beforeEach(() => { getDashboardVersions = jest.spyOn(repo, "getDashboardVersions"); }); afterEach(() => { getDashboardVersions.mockRestore(); }); it("returns 1 when no dashboards are found", async () => { getDashboardVersions.mockImplementation(() => Promise.resolve([])); const nextVersion = await repo.getNextVersionNumber("123"); expect(nextVersion).toEqual(1); }); it("returns the maximum version plus one", async () => { const dashboards: Array<Dashboard> = [ { id: "xyz", version: 1, name: "Dashboard v1", topicAreaId: "456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Draft, parentDashboardId: "123", createdBy: user.userId, updatedAt: new Date(), }, { id: "abc", version: 2, name: "Dashboard v2", topicAreaId: "456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Published, parentDashboardId: "123", createdBy: user.userId, updatedAt: new Date(), }, ]; getDashboardVersions.mockImplementation(() => Promise.resolve(dashboards)); const nextVersion = await repo.getNextVersionNumber("123"); expect(nextVersion).toEqual(3); }); it("handles incorrect versions gracefully", async () => { const dashboards: Array<Dashboard> = [ { id: "xyz", version: undefined as unknown as number, // incorrect version name: "Dashboard v1", topicAreaId: "456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Draft, parentDashboardId: "123", createdBy: user.userId, updatedAt: new Date(), }, ]; getDashboardVersions.mockImplementation(() => Promise.resolve(dashboards)); const nextVersion = await repo.getNextVersionNumber("123"); expect(nextVersion).toEqual(1); }); it("handles a mix of incorrect and correct versions", async () => { const dashboards: Array<Dashboard> = [ { id: "xyz", version: undefined as unknown as number, // incorrect version name: "Dashboard v1", topicAreaId: "456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Draft, parentDashboardId: "123", createdBy: user.userId, updatedAt: new Date(), }, { id: "abc", version: 1, name: "Dashboard v1", topicAreaId: "456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Draft, parentDashboardId: "123", createdBy: user.userId, updatedAt: new Date(), }, ]; getDashboardVersions.mockImplementation(() => Promise.resolve(dashboards)); const nextVersion = await repo.getNextVersionNumber("123"); expect(nextVersion).toEqual(2); }); }); describe("updateTopicAreaName", () => { it("updates all dashboards with new topic area name", async () => { const dashboards = [ { id: "abc", version: 1, name: "Dashboard v1", topicAreaId: "456", topicAreaName: "Topic1", displayTableOfContents: false, description: "Description Test", state: DashboardState.Draft, parentDashboardId: "123", createdBy: user.userId, updatedAt: new Date(), }, ]; await repo.updateTopicAreaName(dashboards, "New Topic Area Name", user); expect(dynamodb.transactWrite).toBeCalledWith({ TransactItems: expect.arrayContaining([ expect.objectContaining({ Update: { TableName: tableName, Key: { pk: "Dashboard#abc", sk: "Dashboard#abc", }, UpdateExpression: "set topicAreaName = :topicAreaName, #updatedBy = :updatedBy", ExpressionAttributeNames: { "#updatedBy": "updatedBy", }, ExpressionAttributeValues: { ":topicAreaName": "New Topic Area Name", ":updatedBy": user.userId, }, }, }), ]), }); }); }); describe("getDashboardByFriendlyURL", () => { it("queries the correct GSI", async () => { await repo.getDashboardByFriendlyURL("my-friendly-url"); expect(dynamodb.query).toBeCalledWith( expect.objectContaining({ TableName: tableName, IndexName: "byFriendlyURL", }) ); }); it("returns the dashboard associated to the friendlyURL", async () => { const items: DashboardItem[] = [ { pk: "Dashboard#123", sk: "Dashboard#123", type: "Dashboard", parentDashboardId: "123", version: 1, description: "", createdBy: "johndoe", state: "Published", dashboardName: "My Dashboard", topicAreaId: "001", topicAreaName: "Environment", displayTableOfContents: false, updatedAt: new Date().toISOString(), friendlyURL: "my-friendly-url", }, ]; dynamodb.query = jest.fn().mockReturnValue({ Items: items }); const dashboard = await repo.getDashboardByFriendlyURL("my-friendly-url"); expect(dashboard?.friendlyURL).toEqual("my-friendly-url"); }); });
the_stack