text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
export namespace Types {
interface I {}
type StringAlias = string;
type ArrayAlias = Array<string>;
type InterfaceAlias = I;
type ObjectAlias = typeof object;
type AliasWithTypeParam<K, V> = Map<K, V>;
type TupleReference = [string[], string];
type TupleReferenceHomogenous = [number, number, number];
type TupleReferenceNested = [number, string, [boolean, boolean[]]];
type AliasAlias<X> = AliasWithTypeParam<string, X>;
type TypeUnion = string | number;
type LongUnion = string | number | boolean | symbol;
type ConstUnion = 'a' | 3;
type ConstUnionHomogenous = 'a' | 'b';
type NullNumberUnion = number | null; // translates to Null<Float>
type UndefinedNumberUnion = number | undefined; // translates to Null<Float>
type Intersection = number & string;
type NullOrUndefined = null | undefined;
type StructureType = {
field: number;
sub: {
subField: string;
}
}
type StructureWithTypeParam<T> = {
t: T;
optionalT?: T;
nullableT: T | null;
undefinedT: T | undefined;
}
type FunctionVarConversion = {
exampleWithOverload: {
(p: string): number;
(p: boolean): number;
},
nullableExampleWithOverload: {
(p: string): number;
(p: boolean): number;
} | null;
optionalExampleWithOverload?: {
(p: string): number;
(p: boolean): number;
}
}
type Recursive<T> = {
recursive: Recursive<T>;
recursiveRecursive: Recursive<Recursive<T>>;
recursiveString: Recursive<string>;
recursiveArray: Recursive<T>[];
structureType: StructureType;
t: T;
}
class ThisUnion {
thisOrString: this | string;
}
// from JQueryStatic
class ThisIntersection<T> {
_this: this;
thisAndAnon: this & {field: string};
thisAndAnon2: this & {};
thisAndString: this & string;
thisAndTp: this & T;
thisAndTpArg<T>(arg: this & T): void;
thisAndTpRet<T>(): this & T;
}
// Mapped type recursion from babylon.js
type Primitive = undefined | null | boolean | string | number | Function;
export type Immutable<T> = T extends Primitive ? T : T extends Array<infer U> ? ReadonlyArray<U> : DeepImmutable<T>;
export type DeepImmutable<T> = T extends Primitive ? T : T extends Array<infer U> ? DeepImmutableArray<U> : DeepImmutableObject<T>;
interface DeepImmutableArray<T> extends ReadonlyArray<DeepImmutable<T>> { }
type DeepImmutableObject<T> = {
readonly [K in keyof T]: DeepImmutable<T[K]>;
};
class Color3 {
equals(otherColor: DeepImmutable<Color3>): boolean;
toColor4(alpha?: number): DeepImmutable<Color4>;
}
class Color4 {
equals(otherColor: DeepImmutable<Color4>): boolean;
toColor3(alpha?: number): DeepImmutable<Color3>;
}
/**
* haxe doesn't support function-types with type parameters
* this should translate to:
* typedef FunctionTypeWithTypeParam<T> = {
* @:selfCall
* function call<K>(a:T, b:K):K;
* };
*/
type FunctionTypeWithTypeParam<T> = <K>(a: T, b: K) => K;
function functionWithOptional(a: string, b?: boolean): number;
type FunctionTypeWithOptional = (a: string, b?: boolean) => number;
type FunctionWithRest = (...a: number[]) => string;
// Primitive Types
// implicit
const implicitInt = 2; // number
const implicitFloat = 2.2; // number
const implicitBool = true; // boolean
const implicitStr = 'example'; // string
// const implicitBigInt = 9007199254740991n; ESNext+
const noType;
// explicit
const numberPrimitive: number;
const booleanPrimitive: boolean;
const stringPrimitive: string;
const stringObject: String;
const numberObject: Number;
const booleanObject: Boolean;
const symbolPrimitive: symbol;
const symbolObject: Symbol;
const any: any;
const typeInParentheses: ( number );
const unionInParentheses: ( number | string );
// void fields are legal in TypeScript, not legal in haxe
const voidType: void;
const voidUnionType: void | number;
const voidTypeParam: Array<void>;
const voidObjField: {
x: void,
}
const voidArg: (a: void) => void;
// literals
const intLiteral: 1;
const intLiteralAlt: -1; // in the AST the type is wrapped in a PrefixUnaryExpression
const floatLiteral: 1.1;
const booleanLiteral: false;
const stringLiteral: 'example';
const typeReferenceStringAlias: StringAlias;
const typeReferenceArrayAlias: ArrayAlias;
const typeReferenceObjectAlias: ObjectAlias;
const typeReferenceAliasWithTypeParam: AliasWithTypeParam<string, number>;
// Object Types
const object: {
fieldA: number,
fieldB: number,
fieldArrayAlias: ArrayAlias,
fieldOptional?: number,
macro: string,
nestedTuple: [number, string, [boolean, boolean[]]],
['computedFieldName']: string,
sub: {a: number, b: number},
methodSignatureComplex<T extends string | number>(a: number, opt?: string): T;
methodSignatureWithOverload<T>(a: T): void,
methodSignatureWithOverload(a: number): void, // overload
methodProperty: <T>(a: T) => void,
methodSignatureOptional?(): string,
readonly readonlyField: string,
};
const objectSingleField: { a };
const arrayString: Array<string>;
const arrayStringAlt: string[];
const stringObj: String;
const arrayNumberStringUnion: Array<number | string>;
const tupleNumberString: [number, string];
// Index Signatures
// - see https://basarat.gitbooks.io/typescript/docs/types/index-signatures.html
/**
* @expect haxe.DynamicAccess<Float>
*/
const stringNumberMap: {
[key: string]: number
};
const readonlyStringNumberMap: {
readonly [key: string]: number
};
// can be supported by generating an abstract and overloading @:op([]) and @:op(a.b)
const stringNumberMapWithField: {
[key: string]: number
field: number,
};
/**
* @expect ArrayAccess<String>
*/
const numberStringMap: {
[key: number]: string
};
/**
* @expect ReadonlyArray<String>
*/
const readonlyNumberStringMap: {
readonly [key: number]: string
};
const numberStringMapWithField: {
[key: number]: string
field: string,
};
const stringAndNumberMapWithField: {
[key: string]: string;
[index: number]: string;
length: string;
};
// Mapped Types
const mappedStringIndex: {
[K in "hello" | "world"]: string;
};
const partial: Partial<{a: number, b: string}>; // macro Partial or evaluate
function partialTypeParam<T>(x: Partial<T>): void; // not sure there's any way to support this
const readonlyAnon: Readonly<Anon>;
// limit allowed fields
type Index = 'a' | 'b' | 'c'
type FromIndex = { [k in Index]?: number }
type FromSomeIndex<K extends string> = { [key in K]: number }
type RecordOfIndex = Record<Index, boolean>;
// Functions
const arrowNumberStringVoid: (a: number, noType) => void;
const arrowNumberTVoidTypeParam: <T>(a: number, tParam: T, arrayTParam: Array<T>) => void;
const arrowParamWithRest: (a: number, b: number, ...rest: Array<number>) => void;
const arrowParamWithRestOr: (a: number, b: number, ...rest: [] | [number]) => void;
const arrowParamWithRestUnion: (a: number, b: number, ...rest: number[] | boolean[]) => void;
const arrowParamWithRestTuple: (a: number, b: number, ...rest: [number]) => void;
const arrowParamWithRestTupleUnion: (a: number, b: number, ...rest: [number] | [boolean]) => void;
const arrowParamObjectBindingPattern: ({ x: number , y: string }) => void;
function functionImplicit(x, y);
function functionNumberStringVoidAlt (a: number, b: string): void;
function functionNumberTVoidTypeParamAlt<T>(a: number, tparam: T): void;
function overloadedFunction(a: number);
function overloadedFunction(a: string);
function overloadedFunction(a: Array<symbol>);
function overloadedFunction<T, U>(a: Array<symbol>, u: U): T;
function typeParameterWithConstraint<T extends Array<number>>(x: T);
const constructorType: new (a: string) => void;
// Union Types
const nullableNumber: null | number;
const undefineableNumber: undefined | number;
const undefineableNullableNumber: undefined | null | number;
// Intersection Types
const intersectionWithSubIntersection: { x: {a: number} } & { x: {b: string} };
const intersectionXY: { x: number } & { y: number };
const intersectionRedefinitionSame: { x: number } & { x: number };
const intersectionRedefinitionDifferent: { x: number } & { x: string };
const intersectionWithTypeof: typeof object & { extendedField: number };
const intersectionWithAny: { x: number } & any;
const intersectionWithArray: { x: number } & Array<number>;
const intersectionStringNumber: string & number;
const intersectionTripleAnon: {x: number} & {y: number} & {z: number};
const intersectionWithUnion: {a: string} & {b: boolean} | {c: number};
const intersectionWithCallSignatures: {(callParamA: string): number; call(): number} & {(callParamB: boolean): string[]; b: number};
type Anon = { a: string, r: Record<Index, boolean> };
type AliasedAnon = Anon;
const intersectionAnonAlias: AliasedAnon & {b: boolean};
class IntersectionA {fieldA: number}
class IntersectionB {fieldB: number}
const intersectionBetweenClasses: IntersectionA & IntersectionB;
function intersectionBetweenTypeParams<A, B>(p: A & B): void;
// Type Query
const typeQueryImplicitStr: typeof implicitStr;
const typeQueryObject: typeof object;
const typeQueryNoType: typeof noType;
const typeQueryFunction: typeof functionImplicit;
const typeQueryFunctionWithOverloads: typeof overloadedFunction;
const typeQueryClassLike: typeof ClassLikeConstructorType;
const typeQueryClassLikeOrNull: null | typeof ClassLikeConstructorType;
interface ClassLikeConstructorType { }
const ClassLikeConstructorType: {
new(): ClassLikeConstructorType;
field: string;
}
// Type reference enum
type EnumValueAlias = ExampleEnum.A;
type EnumSubset = ExampleEnum.A | ExampleEnum.B;
enum ExampleEnum {
A = 1,
B = 2,
C = 3
}
// FirstTypeNode
function firstTypeFunction(node: {}): node is string;
// Testing work around for haxe compiler bug https://github.com/HaxeFoundation/haxe/issues/9397
// simplified from lib.dom.d.ts
type ParentNode = {
exampleField: number;
}
type INode<T> = {
/**
* To work around #9397, parent type should just be INode<T>
*/
parent: INode<T> & ParentNode;
}
/**
* Should translate to _Lowercasename
*/
type _lowercasename = string;
type StringEnum = 'secret' | 'public' | 'private';
class Issue26 {
nonOptionalEnumField: ExampleEnum;
optionalEnumField?: ExampleEnum;
nullOrEnumField: ExampleEnum | null;
undefinedOrEnumField: ExampleEnum | undefined;
undefinedNullEnumField: ExampleEnum | undefined | null;
nonOptionalEnumField2: StringEnum;
optionalEnumField2?: StringEnum;
nullOrEnumField2: StringEnum | null;
undefinedOrEnumField2: StringEnum | undefined;
undefinedNullEnumField2: StringEnum | undefined | null;
method(optionalEnum?:ExampleEnum): ExampleEnum | null;
method2(optionalEnum?:StringEnum): StringEnum | null;
}
type Issue26Tp<X,Y> = Issue26TpB<X> | Issue26TpC<Y>;
type Issue26TpB<X> = {}
type Issue26TpC<Y> = {}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/machinesMappers";
import * as Parameters from "../models/parameters";
import { HybridComputeManagementClientContext } from "../hybridComputeManagementClientContext";
/** Class representing a Machines. */
export class Machines {
private readonly client: HybridComputeManagementClientContext;
/**
* Create a Machines.
* @param {HybridComputeManagementClientContext} client Reference to the service client.
*/
constructor(client: HybridComputeManagementClientContext) {
this.client = client;
}
/**
* The operation to remove a hybrid machine identity in Azure.
* @param resourceGroupName The name of the resource group.
* @param name The name of the hybrid machine.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, name: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param name The name of the hybrid machine.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, name: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param name The name of the hybrid machine.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, name: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, name: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
name,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Retrieves information about the model view or the instance view of a hybrid machine.
* @param resourceGroupName The name of the resource group.
* @param name The name of the hybrid machine.
* @param [options] The optional parameters
* @returns Promise<Models.MachinesGetResponse>
*/
get(resourceGroupName: string, name: string, options?: Models.MachinesGetOptionalParams): Promise<Models.MachinesGetResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param name The name of the hybrid machine.
* @param callback The callback
*/
get(resourceGroupName: string, name: string, callback: msRest.ServiceCallback<Models.Machine>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param name The name of the hybrid machine.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, name: string, options: Models.MachinesGetOptionalParams, callback: msRest.ServiceCallback<Models.Machine>): void;
get(resourceGroupName: string, name: string, options?: Models.MachinesGetOptionalParams | msRest.ServiceCallback<Models.Machine>, callback?: msRest.ServiceCallback<Models.Machine>): Promise<Models.MachinesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
name,
options
},
getOperationSpec,
callback) as Promise<Models.MachinesGetResponse>;
}
/**
* Lists all the hybrid machines in the specified resource group. Use the nextLink property in the
* response to get the next page of hybrid machines.
* @param resourceGroupName The name of the resource group.
* @param [options] The optional parameters
* @returns Promise<Models.MachinesListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.MachinesListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.MachineListResult>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MachineListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MachineListResult>, callback?: msRest.ServiceCallback<Models.MachineListResult>): Promise<Models.MachinesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.MachinesListByResourceGroupResponse>;
}
/**
* Lists all the hybrid machines in the specified subscription. Use the nextLink property in the
* response to get the next page of hybrid machines.
* @param [options] The optional parameters
* @returns Promise<Models.MachinesListBySubscriptionResponse>
*/
listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.MachinesListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.MachineListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MachineListResult>): void;
listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MachineListResult>, callback?: msRest.ServiceCallback<Models.MachineListResult>): Promise<Models.MachinesListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.MachinesListBySubscriptionResponse>;
}
/**
* Lists all the hybrid machines in the specified resource group. Use the nextLink property in the
* response to get the next page of hybrid machines.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.MachinesListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.MachinesListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.MachineListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MachineListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MachineListResult>, callback?: msRest.ServiceCallback<Models.MachineListResult>): Promise<Models.MachinesListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.MachinesListByResourceGroupNextResponse>;
}
/**
* Lists all the hybrid machines in the specified subscription. Use the nextLink property in the
* response to get the next page of hybrid machines.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.MachinesListBySubscriptionNextResponse>
*/
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.MachinesListBySubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.MachineListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MachineListResult>): void;
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MachineListResult>, callback?: msRest.ServiceCallback<Models.MachineListResult>): Promise<Models.MachinesListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listBySubscriptionNextOperationSpec,
callback) as Promise<Models.MachinesListBySubscriptionNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/machines/{name}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/machines/{name}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name
],
queryParameters: [
Parameters.apiVersion,
Parameters.expand
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Machine
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/machines",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MachineListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.HybridCompute/machines",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MachineListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MachineListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listBySubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MachineListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
BatchDeleteDocumentCommand,
BatchDeleteDocumentCommandInput,
BatchDeleteDocumentCommandOutput,
} from "./commands/BatchDeleteDocumentCommand";
import {
BatchGetDocumentStatusCommand,
BatchGetDocumentStatusCommandInput,
BatchGetDocumentStatusCommandOutput,
} from "./commands/BatchGetDocumentStatusCommand";
import {
BatchPutDocumentCommand,
BatchPutDocumentCommandInput,
BatchPutDocumentCommandOutput,
} from "./commands/BatchPutDocumentCommand";
import {
ClearQuerySuggestionsCommand,
ClearQuerySuggestionsCommandInput,
ClearQuerySuggestionsCommandOutput,
} from "./commands/ClearQuerySuggestionsCommand";
import {
CreateDataSourceCommand,
CreateDataSourceCommandInput,
CreateDataSourceCommandOutput,
} from "./commands/CreateDataSourceCommand";
import { CreateFaqCommand, CreateFaqCommandInput, CreateFaqCommandOutput } from "./commands/CreateFaqCommand";
import { CreateIndexCommand, CreateIndexCommandInput, CreateIndexCommandOutput } from "./commands/CreateIndexCommand";
import {
CreateQuerySuggestionsBlockListCommand,
CreateQuerySuggestionsBlockListCommandInput,
CreateQuerySuggestionsBlockListCommandOutput,
} from "./commands/CreateQuerySuggestionsBlockListCommand";
import {
CreateThesaurusCommand,
CreateThesaurusCommandInput,
CreateThesaurusCommandOutput,
} from "./commands/CreateThesaurusCommand";
import {
DeleteDataSourceCommand,
DeleteDataSourceCommandInput,
DeleteDataSourceCommandOutput,
} from "./commands/DeleteDataSourceCommand";
import { DeleteFaqCommand, DeleteFaqCommandInput, DeleteFaqCommandOutput } from "./commands/DeleteFaqCommand";
import { DeleteIndexCommand, DeleteIndexCommandInput, DeleteIndexCommandOutput } from "./commands/DeleteIndexCommand";
import {
DeletePrincipalMappingCommand,
DeletePrincipalMappingCommandInput,
DeletePrincipalMappingCommandOutput,
} from "./commands/DeletePrincipalMappingCommand";
import {
DeleteQuerySuggestionsBlockListCommand,
DeleteQuerySuggestionsBlockListCommandInput,
DeleteQuerySuggestionsBlockListCommandOutput,
} from "./commands/DeleteQuerySuggestionsBlockListCommand";
import {
DeleteThesaurusCommand,
DeleteThesaurusCommandInput,
DeleteThesaurusCommandOutput,
} from "./commands/DeleteThesaurusCommand";
import {
DescribeDataSourceCommand,
DescribeDataSourceCommandInput,
DescribeDataSourceCommandOutput,
} from "./commands/DescribeDataSourceCommand";
import { DescribeFaqCommand, DescribeFaqCommandInput, DescribeFaqCommandOutput } from "./commands/DescribeFaqCommand";
import {
DescribeIndexCommand,
DescribeIndexCommandInput,
DescribeIndexCommandOutput,
} from "./commands/DescribeIndexCommand";
import {
DescribePrincipalMappingCommand,
DescribePrincipalMappingCommandInput,
DescribePrincipalMappingCommandOutput,
} from "./commands/DescribePrincipalMappingCommand";
import {
DescribeQuerySuggestionsBlockListCommand,
DescribeQuerySuggestionsBlockListCommandInput,
DescribeQuerySuggestionsBlockListCommandOutput,
} from "./commands/DescribeQuerySuggestionsBlockListCommand";
import {
DescribeQuerySuggestionsConfigCommand,
DescribeQuerySuggestionsConfigCommandInput,
DescribeQuerySuggestionsConfigCommandOutput,
} from "./commands/DescribeQuerySuggestionsConfigCommand";
import {
DescribeThesaurusCommand,
DescribeThesaurusCommandInput,
DescribeThesaurusCommandOutput,
} from "./commands/DescribeThesaurusCommand";
import {
GetQuerySuggestionsCommand,
GetQuerySuggestionsCommandInput,
GetQuerySuggestionsCommandOutput,
} from "./commands/GetQuerySuggestionsCommand";
import {
ListDataSourcesCommand,
ListDataSourcesCommandInput,
ListDataSourcesCommandOutput,
} from "./commands/ListDataSourcesCommand";
import {
ListDataSourceSyncJobsCommand,
ListDataSourceSyncJobsCommandInput,
ListDataSourceSyncJobsCommandOutput,
} from "./commands/ListDataSourceSyncJobsCommand";
import { ListFaqsCommand, ListFaqsCommandInput, ListFaqsCommandOutput } from "./commands/ListFaqsCommand";
import {
ListGroupsOlderThanOrderingIdCommand,
ListGroupsOlderThanOrderingIdCommandInput,
ListGroupsOlderThanOrderingIdCommandOutput,
} from "./commands/ListGroupsOlderThanOrderingIdCommand";
import { ListIndicesCommand, ListIndicesCommandInput, ListIndicesCommandOutput } from "./commands/ListIndicesCommand";
import {
ListQuerySuggestionsBlockListsCommand,
ListQuerySuggestionsBlockListsCommandInput,
ListQuerySuggestionsBlockListsCommandOutput,
} from "./commands/ListQuerySuggestionsBlockListsCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
ListThesauriCommand,
ListThesauriCommandInput,
ListThesauriCommandOutput,
} from "./commands/ListThesauriCommand";
import {
PutPrincipalMappingCommand,
PutPrincipalMappingCommandInput,
PutPrincipalMappingCommandOutput,
} from "./commands/PutPrincipalMappingCommand";
import { QueryCommand, QueryCommandInput, QueryCommandOutput } from "./commands/QueryCommand";
import {
StartDataSourceSyncJobCommand,
StartDataSourceSyncJobCommandInput,
StartDataSourceSyncJobCommandOutput,
} from "./commands/StartDataSourceSyncJobCommand";
import {
StopDataSourceSyncJobCommand,
StopDataSourceSyncJobCommandInput,
StopDataSourceSyncJobCommandOutput,
} from "./commands/StopDataSourceSyncJobCommand";
import {
SubmitFeedbackCommand,
SubmitFeedbackCommandInput,
SubmitFeedbackCommandOutput,
} from "./commands/SubmitFeedbackCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateDataSourceCommand,
UpdateDataSourceCommandInput,
UpdateDataSourceCommandOutput,
} from "./commands/UpdateDataSourceCommand";
import { UpdateIndexCommand, UpdateIndexCommandInput, UpdateIndexCommandOutput } from "./commands/UpdateIndexCommand";
import {
UpdateQuerySuggestionsBlockListCommand,
UpdateQuerySuggestionsBlockListCommandInput,
UpdateQuerySuggestionsBlockListCommandOutput,
} from "./commands/UpdateQuerySuggestionsBlockListCommand";
import {
UpdateQuerySuggestionsConfigCommand,
UpdateQuerySuggestionsConfigCommandInput,
UpdateQuerySuggestionsConfigCommandOutput,
} from "./commands/UpdateQuerySuggestionsConfigCommand";
import {
UpdateThesaurusCommand,
UpdateThesaurusCommandInput,
UpdateThesaurusCommandOutput,
} from "./commands/UpdateThesaurusCommand";
import { KendraClient } from "./KendraClient";
/**
* <p>Amazon Kendra is a service for indexing large document sets.</p>
*/
export class Kendra extends KendraClient {
/**
* <p>Removes one or more documents from an index. The documents must have
* been added with the <code>BatchPutDocument</code> operation.</p>
* <p>The documents are deleted asynchronously. You can see the progress of
* the deletion by using Amazon Web Services CloudWatch. Any error messages related to the
* processing of the batch are sent to you CloudWatch log.</p>
*/
public batchDeleteDocument(
args: BatchDeleteDocumentCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchDeleteDocumentCommandOutput>;
public batchDeleteDocument(
args: BatchDeleteDocumentCommandInput,
cb: (err: any, data?: BatchDeleteDocumentCommandOutput) => void
): void;
public batchDeleteDocument(
args: BatchDeleteDocumentCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchDeleteDocumentCommandOutput) => void
): void;
public batchDeleteDocument(
args: BatchDeleteDocumentCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchDeleteDocumentCommandOutput) => void),
cb?: (err: any, data?: BatchDeleteDocumentCommandOutput) => void
): Promise<BatchDeleteDocumentCommandOutput> | void {
const command = new BatchDeleteDocumentCommand(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 the indexing status for one or more documents submitted
* with the <a href="https://docs.aws.amazon.com/kendra/latest/dg/API_BatchPutDocument.html">
* BatchPutDocument</a> operation.</p>
* <p>When you use the <code>BatchPutDocument</code> operation,
* documents are indexed asynchronously. You can use the
* <code>BatchGetDocumentStatus</code> operation to get the current
* status of a list of documents so that you can determine if they have
* been successfully indexed.</p>
* <p>You can also use the <code>BatchGetDocumentStatus</code> operation
* to check the status of the <a href="https://docs.aws.amazon.com/kendra/latest/dg/API_BatchDeleteDocument.html">
* BatchDeleteDocument</a> operation. When a document is
* deleted from the index, Amazon Kendra returns <code>NOT_FOUND</code> as the
* status.</p>
*/
public batchGetDocumentStatus(
args: BatchGetDocumentStatusCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchGetDocumentStatusCommandOutput>;
public batchGetDocumentStatus(
args: BatchGetDocumentStatusCommandInput,
cb: (err: any, data?: BatchGetDocumentStatusCommandOutput) => void
): void;
public batchGetDocumentStatus(
args: BatchGetDocumentStatusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchGetDocumentStatusCommandOutput) => void
): void;
public batchGetDocumentStatus(
args: BatchGetDocumentStatusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchGetDocumentStatusCommandOutput) => void),
cb?: (err: any, data?: BatchGetDocumentStatusCommandOutput) => void
): Promise<BatchGetDocumentStatusCommandOutput> | void {
const command = new BatchGetDocumentStatusCommand(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>Adds one or more documents to an index.</p>
* <p>The <code>BatchPutDocument</code> operation enables you to ingest
* inline documents or a set of documents stored in an Amazon S3 bucket. Use
* this operation to ingest your text and unstructured text into an index,
* add custom attributes to the documents, and to attach an access control
* list to the documents added to the index.</p>
* <p>The documents are indexed asynchronously. You can see the progress of
* the batch using Amazon Web Services CloudWatch. Any error messages related to processing
* the batch are sent to your Amazon Web Services CloudWatch log.</p>
*/
public batchPutDocument(
args: BatchPutDocumentCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchPutDocumentCommandOutput>;
public batchPutDocument(
args: BatchPutDocumentCommandInput,
cb: (err: any, data?: BatchPutDocumentCommandOutput) => void
): void;
public batchPutDocument(
args: BatchPutDocumentCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchPutDocumentCommandOutput) => void
): void;
public batchPutDocument(
args: BatchPutDocumentCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchPutDocumentCommandOutput) => void),
cb?: (err: any, data?: BatchPutDocumentCommandOutput) => void
): Promise<BatchPutDocumentCommandOutput> | void {
const command = new BatchPutDocumentCommand(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>Clears existing query suggestions from an index.</p>
* <p>This deletes existing suggestions only, not the queries
* in the query log. After you clear suggestions, Amazon Kendra learns
* new suggestions based on new queries added to the query log
* from the time you cleared suggestions. If you do not see any
* new suggestions, then please allow Amazon Kendra to collect
* enough queries to learn new suggestions.</p>
*/
public clearQuerySuggestions(
args: ClearQuerySuggestionsCommandInput,
options?: __HttpHandlerOptions
): Promise<ClearQuerySuggestionsCommandOutput>;
public clearQuerySuggestions(
args: ClearQuerySuggestionsCommandInput,
cb: (err: any, data?: ClearQuerySuggestionsCommandOutput) => void
): void;
public clearQuerySuggestions(
args: ClearQuerySuggestionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ClearQuerySuggestionsCommandOutput) => void
): void;
public clearQuerySuggestions(
args: ClearQuerySuggestionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ClearQuerySuggestionsCommandOutput) => void),
cb?: (err: any, data?: ClearQuerySuggestionsCommandOutput) => void
): Promise<ClearQuerySuggestionsCommandOutput> | void {
const command = new ClearQuerySuggestionsCommand(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>Creates a data source that you want to use with an Amazon Kendra index. </p>
* <p>You specify a name, data source connector type and description for
* your data source. You also specify configuration information for the
* data source connector.</p>
* <p>
* <code>CreateDataSource</code> is a synchronous operation. The
* operation returns 200 if the data source was successfully created.
* Otherwise, an exception is raised.</p>
*/
public createDataSource(
args: CreateDataSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateDataSourceCommandOutput>;
public createDataSource(
args: CreateDataSourceCommandInput,
cb: (err: any, data?: CreateDataSourceCommandOutput) => void
): void;
public createDataSource(
args: CreateDataSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateDataSourceCommandOutput) => void
): void;
public createDataSource(
args: CreateDataSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDataSourceCommandOutput) => void),
cb?: (err: any, data?: CreateDataSourceCommandOutput) => void
): Promise<CreateDataSourceCommandOutput> | void {
const command = new CreateDataSourceCommand(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>Creates an new set of frequently asked question (FAQ) questions and answers.</p>
*/
public createFaq(args: CreateFaqCommandInput, options?: __HttpHandlerOptions): Promise<CreateFaqCommandOutput>;
public createFaq(args: CreateFaqCommandInput, cb: (err: any, data?: CreateFaqCommandOutput) => void): void;
public createFaq(
args: CreateFaqCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateFaqCommandOutput) => void
): void;
public createFaq(
args: CreateFaqCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateFaqCommandOutput) => void),
cb?: (err: any, data?: CreateFaqCommandOutput) => void
): Promise<CreateFaqCommandOutput> | void {
const command = new CreateFaqCommand(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>Creates a new Amazon Kendra index. Index creation is an asynchronous
* operation. To determine if index creation has completed, check the
* <code>Status</code> field returned from a call to
* <code>DescribeIndex</code>. The <code>Status</code> field is set to
* <code>ACTIVE</code> when the index is ready to use.</p>
* <p>Once the index is active you can index your documents using the
* <code>BatchPutDocument</code> operation or using one of the supported
* data sources. </p>
*/
public createIndex(args: CreateIndexCommandInput, options?: __HttpHandlerOptions): Promise<CreateIndexCommandOutput>;
public createIndex(args: CreateIndexCommandInput, cb: (err: any, data?: CreateIndexCommandOutput) => void): void;
public createIndex(
args: CreateIndexCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateIndexCommandOutput) => void
): void;
public createIndex(
args: CreateIndexCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateIndexCommandOutput) => void),
cb?: (err: any, data?: CreateIndexCommandOutput) => void
): Promise<CreateIndexCommandOutput> | void {
const command = new CreateIndexCommand(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>Creates a block list to exlcude certain queries from suggestions.</p>
* <p>Any query that contains words or phrases specified in the block
* list is blocked or filtered out from being shown as a suggestion.</p>
* <p>You need to provide the file location of your block list text file
* in your S3 bucket. In your text file, enter each block word or phrase
* on a separate line.</p>
* <p>For information on the current quota limits for block lists, see
* <a href="https://docs.aws.amazon.com/kendra/latest/dg/quotas.html">Quotas
* for Amazon Kendra</a>.</p>
*/
public createQuerySuggestionsBlockList(
args: CreateQuerySuggestionsBlockListCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateQuerySuggestionsBlockListCommandOutput>;
public createQuerySuggestionsBlockList(
args: CreateQuerySuggestionsBlockListCommandInput,
cb: (err: any, data?: CreateQuerySuggestionsBlockListCommandOutput) => void
): void;
public createQuerySuggestionsBlockList(
args: CreateQuerySuggestionsBlockListCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateQuerySuggestionsBlockListCommandOutput) => void
): void;
public createQuerySuggestionsBlockList(
args: CreateQuerySuggestionsBlockListCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateQuerySuggestionsBlockListCommandOutput) => void),
cb?: (err: any, data?: CreateQuerySuggestionsBlockListCommandOutput) => void
): Promise<CreateQuerySuggestionsBlockListCommandOutput> | void {
const command = new CreateQuerySuggestionsBlockListCommand(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>Creates a thesaurus for an index. The thesaurus
* contains a list of synonyms in Solr format.</p>
*/
public createThesaurus(
args: CreateThesaurusCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateThesaurusCommandOutput>;
public createThesaurus(
args: CreateThesaurusCommandInput,
cb: (err: any, data?: CreateThesaurusCommandOutput) => void
): void;
public createThesaurus(
args: CreateThesaurusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateThesaurusCommandOutput) => void
): void;
public createThesaurus(
args: CreateThesaurusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateThesaurusCommandOutput) => void),
cb?: (err: any, data?: CreateThesaurusCommandOutput) => void
): Promise<CreateThesaurusCommandOutput> | void {
const command = new CreateThesaurusCommand(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>Deletes an Amazon Kendra data source. An exception is not thrown if the
* data source is already being deleted. While the data source is being
* deleted, the <code>Status</code> field returned by a call to the
* <code>DescribeDataSource</code> operation is set to
* <code>DELETING</code>. For more information, see <a href="https://docs.aws.amazon.com/kendra/latest/dg/delete-data-source.html">Deleting Data Sources</a>.</p>
*/
public deleteDataSource(
args: DeleteDataSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteDataSourceCommandOutput>;
public deleteDataSource(
args: DeleteDataSourceCommandInput,
cb: (err: any, data?: DeleteDataSourceCommandOutput) => void
): void;
public deleteDataSource(
args: DeleteDataSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteDataSourceCommandOutput) => void
): void;
public deleteDataSource(
args: DeleteDataSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDataSourceCommandOutput) => void),
cb?: (err: any, data?: DeleteDataSourceCommandOutput) => void
): Promise<DeleteDataSourceCommandOutput> | void {
const command = new DeleteDataSourceCommand(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 an FAQ from an index.</p>
*/
public deleteFaq(args: DeleteFaqCommandInput, options?: __HttpHandlerOptions): Promise<DeleteFaqCommandOutput>;
public deleteFaq(args: DeleteFaqCommandInput, cb: (err: any, data?: DeleteFaqCommandOutput) => void): void;
public deleteFaq(
args: DeleteFaqCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteFaqCommandOutput) => void
): void;
public deleteFaq(
args: DeleteFaqCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteFaqCommandOutput) => void),
cb?: (err: any, data?: DeleteFaqCommandOutput) => void
): Promise<DeleteFaqCommandOutput> | void {
const command = new DeleteFaqCommand(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>Deletes an existing Amazon Kendra index. An exception is not thrown if
* the index is already being deleted. While the index is being deleted, the
* <code>Status</code> field returned by a call to the
* <code>DescribeIndex</code> operation is set to
* <code>DELETING</code>.</p>
*/
public deleteIndex(args: DeleteIndexCommandInput, options?: __HttpHandlerOptions): Promise<DeleteIndexCommandOutput>;
public deleteIndex(args: DeleteIndexCommandInput, cb: (err: any, data?: DeleteIndexCommandOutput) => void): void;
public deleteIndex(
args: DeleteIndexCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteIndexCommandOutput) => void
): void;
public deleteIndex(
args: DeleteIndexCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteIndexCommandOutput) => void),
cb?: (err: any, data?: DeleteIndexCommandOutput) => void
): Promise<DeleteIndexCommandOutput> | void {
const command = new DeleteIndexCommand(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>Deletes a group so that all users and sub groups that belong to the group can
* no longer access documents only available to that group.</p>
* <p>For example, after deleting the group "Summer Interns", all interns who
* belonged to that group no longer see intern-only documents in their search
* results.</p>
* <p>If you want to delete or replace users or sub groups of a group, you need to
* use the <code>PutPrincipalMapping</code> operation. For example, if a user in
* the group "Engineering" leaves the engineering team and another user takes
* their place, you provide an updated list of users or sub groups that belong
* to the "Engineering" group when calling <code>PutPrincipalMapping</code>. You
* can update your internal list of users or sub groups and input this list
* when calling <code>PutPrincipalMapping</code>.</p>
*/
public deletePrincipalMapping(
args: DeletePrincipalMappingCommandInput,
options?: __HttpHandlerOptions
): Promise<DeletePrincipalMappingCommandOutput>;
public deletePrincipalMapping(
args: DeletePrincipalMappingCommandInput,
cb: (err: any, data?: DeletePrincipalMappingCommandOutput) => void
): void;
public deletePrincipalMapping(
args: DeletePrincipalMappingCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeletePrincipalMappingCommandOutput) => void
): void;
public deletePrincipalMapping(
args: DeletePrincipalMappingCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeletePrincipalMappingCommandOutput) => void),
cb?: (err: any, data?: DeletePrincipalMappingCommandOutput) => void
): Promise<DeletePrincipalMappingCommandOutput> | void {
const command = new DeletePrincipalMappingCommand(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>Deletes a block list used for query suggestions for an index.</p>
* <p>A deleted block list might not take effect right away. Amazon Kendra
* needs to refresh the entire suggestions list to add back the
* queries that were previously blocked.</p>
*/
public deleteQuerySuggestionsBlockList(
args: DeleteQuerySuggestionsBlockListCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteQuerySuggestionsBlockListCommandOutput>;
public deleteQuerySuggestionsBlockList(
args: DeleteQuerySuggestionsBlockListCommandInput,
cb: (err: any, data?: DeleteQuerySuggestionsBlockListCommandOutput) => void
): void;
public deleteQuerySuggestionsBlockList(
args: DeleteQuerySuggestionsBlockListCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteQuerySuggestionsBlockListCommandOutput) => void
): void;
public deleteQuerySuggestionsBlockList(
args: DeleteQuerySuggestionsBlockListCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteQuerySuggestionsBlockListCommandOutput) => void),
cb?: (err: any, data?: DeleteQuerySuggestionsBlockListCommandOutput) => void
): Promise<DeleteQuerySuggestionsBlockListCommandOutput> | void {
const command = new DeleteQuerySuggestionsBlockListCommand(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>Deletes an existing Amazon Kendra thesaurus.
* </p>
*/
public deleteThesaurus(
args: DeleteThesaurusCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteThesaurusCommandOutput>;
public deleteThesaurus(
args: DeleteThesaurusCommandInput,
cb: (err: any, data?: DeleteThesaurusCommandOutput) => void
): void;
public deleteThesaurus(
args: DeleteThesaurusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteThesaurusCommandOutput) => void
): void;
public deleteThesaurus(
args: DeleteThesaurusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteThesaurusCommandOutput) => void),
cb?: (err: any, data?: DeleteThesaurusCommandOutput) => void
): Promise<DeleteThesaurusCommandOutput> | void {
const command = new DeleteThesaurusCommand(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>Gets information about a Amazon Kendra data source.</p>
*/
public describeDataSource(
args: DescribeDataSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeDataSourceCommandOutput>;
public describeDataSource(
args: DescribeDataSourceCommandInput,
cb: (err: any, data?: DescribeDataSourceCommandOutput) => void
): void;
public describeDataSource(
args: DescribeDataSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeDataSourceCommandOutput) => void
): void;
public describeDataSource(
args: DescribeDataSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDataSourceCommandOutput) => void),
cb?: (err: any, data?: DescribeDataSourceCommandOutput) => void
): Promise<DescribeDataSourceCommandOutput> | void {
const command = new DescribeDataSourceCommand(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>Gets information about an FAQ list.</p>
*/
public describeFaq(args: DescribeFaqCommandInput, options?: __HttpHandlerOptions): Promise<DescribeFaqCommandOutput>;
public describeFaq(args: DescribeFaqCommandInput, cb: (err: any, data?: DescribeFaqCommandOutput) => void): void;
public describeFaq(
args: DescribeFaqCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeFaqCommandOutput) => void
): void;
public describeFaq(
args: DescribeFaqCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeFaqCommandOutput) => void),
cb?: (err: any, data?: DescribeFaqCommandOutput) => void
): Promise<DescribeFaqCommandOutput> | void {
const command = new DescribeFaqCommand(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>Describes an existing Amazon Kendra index</p>
*/
public describeIndex(
args: DescribeIndexCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeIndexCommandOutput>;
public describeIndex(
args: DescribeIndexCommandInput,
cb: (err: any, data?: DescribeIndexCommandOutput) => void
): void;
public describeIndex(
args: DescribeIndexCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeIndexCommandOutput) => void
): void;
public describeIndex(
args: DescribeIndexCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeIndexCommandOutput) => void),
cb?: (err: any, data?: DescribeIndexCommandOutput) => void
): Promise<DescribeIndexCommandOutput> | void {
const command = new DescribeIndexCommand(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>Describes the processing of <code>PUT</code> and <code>DELETE</code> actions
* for mapping users to their groups. This includes information on the status of
* actions currently processing or yet to be processed, when actions were last updated,
* when actions were received by Amazon Kendra, the latest action that should process
* and apply after other actions, and useful error messages if an action could
* not be processed.</p>
*/
public describePrincipalMapping(
args: DescribePrincipalMappingCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribePrincipalMappingCommandOutput>;
public describePrincipalMapping(
args: DescribePrincipalMappingCommandInput,
cb: (err: any, data?: DescribePrincipalMappingCommandOutput) => void
): void;
public describePrincipalMapping(
args: DescribePrincipalMappingCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribePrincipalMappingCommandOutput) => void
): void;
public describePrincipalMapping(
args: DescribePrincipalMappingCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribePrincipalMappingCommandOutput) => void),
cb?: (err: any, data?: DescribePrincipalMappingCommandOutput) => void
): Promise<DescribePrincipalMappingCommandOutput> | void {
const command = new DescribePrincipalMappingCommand(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>Describes a block list used for query suggestions for an index.</p>
* <p>This is used to check the current settings that are applied to a
* block list.</p>
*/
public describeQuerySuggestionsBlockList(
args: DescribeQuerySuggestionsBlockListCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeQuerySuggestionsBlockListCommandOutput>;
public describeQuerySuggestionsBlockList(
args: DescribeQuerySuggestionsBlockListCommandInput,
cb: (err: any, data?: DescribeQuerySuggestionsBlockListCommandOutput) => void
): void;
public describeQuerySuggestionsBlockList(
args: DescribeQuerySuggestionsBlockListCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeQuerySuggestionsBlockListCommandOutput) => void
): void;
public describeQuerySuggestionsBlockList(
args: DescribeQuerySuggestionsBlockListCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeQuerySuggestionsBlockListCommandOutput) => void),
cb?: (err: any, data?: DescribeQuerySuggestionsBlockListCommandOutput) => void
): Promise<DescribeQuerySuggestionsBlockListCommandOutput> | void {
const command = new DescribeQuerySuggestionsBlockListCommand(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>Describes the settings of query suggestions for an index.</p>
* <p>This is used to check the current settings applied
* to query suggestions.</p>
*/
public describeQuerySuggestionsConfig(
args: DescribeQuerySuggestionsConfigCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeQuerySuggestionsConfigCommandOutput>;
public describeQuerySuggestionsConfig(
args: DescribeQuerySuggestionsConfigCommandInput,
cb: (err: any, data?: DescribeQuerySuggestionsConfigCommandOutput) => void
): void;
public describeQuerySuggestionsConfig(
args: DescribeQuerySuggestionsConfigCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeQuerySuggestionsConfigCommandOutput) => void
): void;
public describeQuerySuggestionsConfig(
args: DescribeQuerySuggestionsConfigCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeQuerySuggestionsConfigCommandOutput) => void),
cb?: (err: any, data?: DescribeQuerySuggestionsConfigCommandOutput) => void
): Promise<DescribeQuerySuggestionsConfigCommandOutput> | void {
const command = new DescribeQuerySuggestionsConfigCommand(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>Describes an existing Amazon Kendra thesaurus.</p>
*/
public describeThesaurus(
args: DescribeThesaurusCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeThesaurusCommandOutput>;
public describeThesaurus(
args: DescribeThesaurusCommandInput,
cb: (err: any, data?: DescribeThesaurusCommandOutput) => void
): void;
public describeThesaurus(
args: DescribeThesaurusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeThesaurusCommandOutput) => void
): void;
public describeThesaurus(
args: DescribeThesaurusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeThesaurusCommandOutput) => void),
cb?: (err: any, data?: DescribeThesaurusCommandOutput) => void
): Promise<DescribeThesaurusCommandOutput> | void {
const command = new DescribeThesaurusCommand(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>Fetches the queries that are suggested to your users.</p>
*/
public getQuerySuggestions(
args: GetQuerySuggestionsCommandInput,
options?: __HttpHandlerOptions
): Promise<GetQuerySuggestionsCommandOutput>;
public getQuerySuggestions(
args: GetQuerySuggestionsCommandInput,
cb: (err: any, data?: GetQuerySuggestionsCommandOutput) => void
): void;
public getQuerySuggestions(
args: GetQuerySuggestionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetQuerySuggestionsCommandOutput) => void
): void;
public getQuerySuggestions(
args: GetQuerySuggestionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetQuerySuggestionsCommandOutput) => void),
cb?: (err: any, data?: GetQuerySuggestionsCommandOutput) => void
): Promise<GetQuerySuggestionsCommandOutput> | void {
const command = new GetQuerySuggestionsCommand(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>Lists the data sources that you have created.</p>
*/
public listDataSources(
args: ListDataSourcesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListDataSourcesCommandOutput>;
public listDataSources(
args: ListDataSourcesCommandInput,
cb: (err: any, data?: ListDataSourcesCommandOutput) => void
): void;
public listDataSources(
args: ListDataSourcesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListDataSourcesCommandOutput) => void
): void;
public listDataSources(
args: ListDataSourcesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDataSourcesCommandOutput) => void),
cb?: (err: any, data?: ListDataSourcesCommandOutput) => void
): Promise<ListDataSourcesCommandOutput> | void {
const command = new ListDataSourcesCommand(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>Gets statistics about synchronizing Amazon Kendra with a data
* source.</p>
*/
public listDataSourceSyncJobs(
args: ListDataSourceSyncJobsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListDataSourceSyncJobsCommandOutput>;
public listDataSourceSyncJobs(
args: ListDataSourceSyncJobsCommandInput,
cb: (err: any, data?: ListDataSourceSyncJobsCommandOutput) => void
): void;
public listDataSourceSyncJobs(
args: ListDataSourceSyncJobsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListDataSourceSyncJobsCommandOutput) => void
): void;
public listDataSourceSyncJobs(
args: ListDataSourceSyncJobsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDataSourceSyncJobsCommandOutput) => void),
cb?: (err: any, data?: ListDataSourceSyncJobsCommandOutput) => void
): Promise<ListDataSourceSyncJobsCommandOutput> | void {
const command = new ListDataSourceSyncJobsCommand(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>Gets a list of FAQ lists associated with an index.</p>
*/
public listFaqs(args: ListFaqsCommandInput, options?: __HttpHandlerOptions): Promise<ListFaqsCommandOutput>;
public listFaqs(args: ListFaqsCommandInput, cb: (err: any, data?: ListFaqsCommandOutput) => void): void;
public listFaqs(
args: ListFaqsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListFaqsCommandOutput) => void
): void;
public listFaqs(
args: ListFaqsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListFaqsCommandOutput) => void),
cb?: (err: any, data?: ListFaqsCommandOutput) => void
): Promise<ListFaqsCommandOutput> | void {
const command = new ListFaqsCommand(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>Provides a list of groups that are mapped to users before a
* given ordering or timestamp identifier.</p>
*/
public listGroupsOlderThanOrderingId(
args: ListGroupsOlderThanOrderingIdCommandInput,
options?: __HttpHandlerOptions
): Promise<ListGroupsOlderThanOrderingIdCommandOutput>;
public listGroupsOlderThanOrderingId(
args: ListGroupsOlderThanOrderingIdCommandInput,
cb: (err: any, data?: ListGroupsOlderThanOrderingIdCommandOutput) => void
): void;
public listGroupsOlderThanOrderingId(
args: ListGroupsOlderThanOrderingIdCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListGroupsOlderThanOrderingIdCommandOutput) => void
): void;
public listGroupsOlderThanOrderingId(
args: ListGroupsOlderThanOrderingIdCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListGroupsOlderThanOrderingIdCommandOutput) => void),
cb?: (err: any, data?: ListGroupsOlderThanOrderingIdCommandOutput) => void
): Promise<ListGroupsOlderThanOrderingIdCommandOutput> | void {
const command = new ListGroupsOlderThanOrderingIdCommand(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>Lists the Amazon Kendra indexes that you have created.</p>
*/
public listIndices(args: ListIndicesCommandInput, options?: __HttpHandlerOptions): Promise<ListIndicesCommandOutput>;
public listIndices(args: ListIndicesCommandInput, cb: (err: any, data?: ListIndicesCommandOutput) => void): void;
public listIndices(
args: ListIndicesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListIndicesCommandOutput) => void
): void;
public listIndices(
args: ListIndicesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListIndicesCommandOutput) => void),
cb?: (err: any, data?: ListIndicesCommandOutput) => void
): Promise<ListIndicesCommandOutput> | void {
const command = new ListIndicesCommand(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>Lists the block lists used for query suggestions for an index.</p>
* <p>For information on the current quota limits for block lists, see
* <a href="https://docs.aws.amazon.com/kendra/latest/dg/quotas.html">Quotas
* for Amazon Kendra</a>.</p>
*/
public listQuerySuggestionsBlockLists(
args: ListQuerySuggestionsBlockListsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListQuerySuggestionsBlockListsCommandOutput>;
public listQuerySuggestionsBlockLists(
args: ListQuerySuggestionsBlockListsCommandInput,
cb: (err: any, data?: ListQuerySuggestionsBlockListsCommandOutput) => void
): void;
public listQuerySuggestionsBlockLists(
args: ListQuerySuggestionsBlockListsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListQuerySuggestionsBlockListsCommandOutput) => void
): void;
public listQuerySuggestionsBlockLists(
args: ListQuerySuggestionsBlockListsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListQuerySuggestionsBlockListsCommandOutput) => void),
cb?: (err: any, data?: ListQuerySuggestionsBlockListsCommandOutput) => void
): Promise<ListQuerySuggestionsBlockListsCommandOutput> | void {
const command = new ListQuerySuggestionsBlockListsCommand(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>Gets a list of tags associated with a specified resource. Indexes,
* FAQs, and data sources can have tags associated with them.</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>Lists the Amazon Kendra thesauri associated with an index.</p>
*/
public listThesauri(
args: ListThesauriCommandInput,
options?: __HttpHandlerOptions
): Promise<ListThesauriCommandOutput>;
public listThesauri(args: ListThesauriCommandInput, cb: (err: any, data?: ListThesauriCommandOutput) => void): void;
public listThesauri(
args: ListThesauriCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListThesauriCommandOutput) => void
): void;
public listThesauri(
args: ListThesauriCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListThesauriCommandOutput) => void),
cb?: (err: any, data?: ListThesauriCommandOutput) => void
): Promise<ListThesauriCommandOutput> | void {
const command = new ListThesauriCommand(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>Maps users to their groups so that you only need to provide
* the user ID when you issue the query.</p>
* <p>You can also map sub groups to groups.
* For example, the group "Company Intellectual Property Teams" includes
* sub groups "Research" and "Engineering". These sub groups include their
* own list of users or people who work in these teams. Only users who work
* in research and engineering, and therefore belong in the intellectual
* property group, can see top-secret company documents in their search
* results.</p>
* <p>You map users to their groups when you want to filter search results
* for different users based on their group’s access to documents. For more
* information on filtering search results for different users, see
* <a href="https://docs.aws.amazon.com/kendra/latest/dg/user-context-filter.html">Filtering
* on user context</a>.</p>
* <p>If more than five <code>PUT</code> actions for a group are currently
* processing, a validation exception is thrown.</p>
*/
public putPrincipalMapping(
args: PutPrincipalMappingCommandInput,
options?: __HttpHandlerOptions
): Promise<PutPrincipalMappingCommandOutput>;
public putPrincipalMapping(
args: PutPrincipalMappingCommandInput,
cb: (err: any, data?: PutPrincipalMappingCommandOutput) => void
): void;
public putPrincipalMapping(
args: PutPrincipalMappingCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutPrincipalMappingCommandOutput) => void
): void;
public putPrincipalMapping(
args: PutPrincipalMappingCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutPrincipalMappingCommandOutput) => void),
cb?: (err: any, data?: PutPrincipalMappingCommandOutput) => void
): Promise<PutPrincipalMappingCommandOutput> | void {
const command = new PutPrincipalMappingCommand(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>Searches an active index. Use this API to search your documents
* using query. The <code>Query</code> operation enables to do faceted
* search and to filter results based on document attributes.</p>
* <p>It also enables you to provide user context that Amazon Kendra uses
* to enforce document access control in the search results. </p>
* <p>Amazon Kendra searches your index for text content and question and
* answer (FAQ) content. By default the response contains three types of
* results.</p>
* <ul>
* <li>
* <p>Relevant passages</p>
* </li>
* <li>
* <p>Matching FAQs</p>
* </li>
* <li>
* <p>Relevant documents</p>
* </li>
* </ul>
* <p>You can specify that the query return only one type of result using
* the <code>QueryResultTypeConfig</code> parameter.</p>
* <p>Each query returns the 100 most relevant results. </p>
*/
public query(args: QueryCommandInput, options?: __HttpHandlerOptions): Promise<QueryCommandOutput>;
public query(args: QueryCommandInput, cb: (err: any, data?: QueryCommandOutput) => void): void;
public query(
args: QueryCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: QueryCommandOutput) => void
): void;
public query(
args: QueryCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: QueryCommandOutput) => void),
cb?: (err: any, data?: QueryCommandOutput) => void
): Promise<QueryCommandOutput> | void {
const command = new QueryCommand(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>Starts a synchronization job for a data source. If a synchronization
* job is already in progress, Amazon Kendra returns a
* <code>ResourceInUseException</code> exception.</p>
*/
public startDataSourceSyncJob(
args: StartDataSourceSyncJobCommandInput,
options?: __HttpHandlerOptions
): Promise<StartDataSourceSyncJobCommandOutput>;
public startDataSourceSyncJob(
args: StartDataSourceSyncJobCommandInput,
cb: (err: any, data?: StartDataSourceSyncJobCommandOutput) => void
): void;
public startDataSourceSyncJob(
args: StartDataSourceSyncJobCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StartDataSourceSyncJobCommandOutput) => void
): void;
public startDataSourceSyncJob(
args: StartDataSourceSyncJobCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartDataSourceSyncJobCommandOutput) => void),
cb?: (err: any, data?: StartDataSourceSyncJobCommandOutput) => void
): Promise<StartDataSourceSyncJobCommandOutput> | void {
const command = new StartDataSourceSyncJobCommand(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 a running synchronization job. You can't stop a scheduled
* synchronization job.</p>
*/
public stopDataSourceSyncJob(
args: StopDataSourceSyncJobCommandInput,
options?: __HttpHandlerOptions
): Promise<StopDataSourceSyncJobCommandOutput>;
public stopDataSourceSyncJob(
args: StopDataSourceSyncJobCommandInput,
cb: (err: any, data?: StopDataSourceSyncJobCommandOutput) => void
): void;
public stopDataSourceSyncJob(
args: StopDataSourceSyncJobCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StopDataSourceSyncJobCommandOutput) => void
): void;
public stopDataSourceSyncJob(
args: StopDataSourceSyncJobCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StopDataSourceSyncJobCommandOutput) => void),
cb?: (err: any, data?: StopDataSourceSyncJobCommandOutput) => void
): Promise<StopDataSourceSyncJobCommandOutput> | void {
const command = new StopDataSourceSyncJobCommand(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>Enables you to provide feedback to Amazon Kendra to improve the
* performance of your index. </p>
*/
public submitFeedback(
args: SubmitFeedbackCommandInput,
options?: __HttpHandlerOptions
): Promise<SubmitFeedbackCommandOutput>;
public submitFeedback(
args: SubmitFeedbackCommandInput,
cb: (err: any, data?: SubmitFeedbackCommandOutput) => void
): void;
public submitFeedback(
args: SubmitFeedbackCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SubmitFeedbackCommandOutput) => void
): void;
public submitFeedback(
args: SubmitFeedbackCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SubmitFeedbackCommandOutput) => void),
cb?: (err: any, data?: SubmitFeedbackCommandOutput) => void
): Promise<SubmitFeedbackCommandOutput> | void {
const command = new SubmitFeedbackCommand(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>Adds the specified tag to the specified index, FAQ, or data source
* resource. If the tag already exists, the existing value is replaced with
* the new value.</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 a tag from an index, FAQ, or a data source.</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>Updates an existing Amazon Kendra data source.</p>
*/
public updateDataSource(
args: UpdateDataSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateDataSourceCommandOutput>;
public updateDataSource(
args: UpdateDataSourceCommandInput,
cb: (err: any, data?: UpdateDataSourceCommandOutput) => void
): void;
public updateDataSource(
args: UpdateDataSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateDataSourceCommandOutput) => void
): void;
public updateDataSource(
args: UpdateDataSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateDataSourceCommandOutput) => void),
cb?: (err: any, data?: UpdateDataSourceCommandOutput) => void
): Promise<UpdateDataSourceCommandOutput> | void {
const command = new UpdateDataSourceCommand(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>Updates an existing Amazon Kendra index.</p>
*/
public updateIndex(args: UpdateIndexCommandInput, options?: __HttpHandlerOptions): Promise<UpdateIndexCommandOutput>;
public updateIndex(args: UpdateIndexCommandInput, cb: (err: any, data?: UpdateIndexCommandOutput) => void): void;
public updateIndex(
args: UpdateIndexCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateIndexCommandOutput) => void
): void;
public updateIndex(
args: UpdateIndexCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateIndexCommandOutput) => void),
cb?: (err: any, data?: UpdateIndexCommandOutput) => void
): Promise<UpdateIndexCommandOutput> | void {
const command = new UpdateIndexCommand(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>Updates a block list used for query suggestions for an index.</p>
* <p>Updates to a block list might not take effect right away. Amazon Kendra
* needs to refresh the entire suggestions list to apply any updates to the
* block list. Other changes not related to the block list apply immediately.</p>
* <p>If a block list is updating, then you need to wait for the first update to
* finish before submitting another update.</p>
* <p>Amazon Kendra supports partial updates, so you only need to provide the fields
* you want to update.</p>
*/
public updateQuerySuggestionsBlockList(
args: UpdateQuerySuggestionsBlockListCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateQuerySuggestionsBlockListCommandOutput>;
public updateQuerySuggestionsBlockList(
args: UpdateQuerySuggestionsBlockListCommandInput,
cb: (err: any, data?: UpdateQuerySuggestionsBlockListCommandOutput) => void
): void;
public updateQuerySuggestionsBlockList(
args: UpdateQuerySuggestionsBlockListCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateQuerySuggestionsBlockListCommandOutput) => void
): void;
public updateQuerySuggestionsBlockList(
args: UpdateQuerySuggestionsBlockListCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateQuerySuggestionsBlockListCommandOutput) => void),
cb?: (err: any, data?: UpdateQuerySuggestionsBlockListCommandOutput) => void
): Promise<UpdateQuerySuggestionsBlockListCommandOutput> | void {
const command = new UpdateQuerySuggestionsBlockListCommand(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>Updates the settings of query suggestions for an index.</p>
* <p>Amazon Kendra supports partial updates, so you only need to provide
* the fields you want to update.</p>
* <p>If an update is currently processing (i.e. 'happening'), you
* need to wait for the update to finish before making another update.</p>
* <p>Updates to query suggestions settings might not take effect right away.
* The time for your updated settings to take effect depends on the updates
* made and the number of search queries in your index.</p>
* <p>You can still enable/disable query suggestions at any time.</p>
*/
public updateQuerySuggestionsConfig(
args: UpdateQuerySuggestionsConfigCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateQuerySuggestionsConfigCommandOutput>;
public updateQuerySuggestionsConfig(
args: UpdateQuerySuggestionsConfigCommandInput,
cb: (err: any, data?: UpdateQuerySuggestionsConfigCommandOutput) => void
): void;
public updateQuerySuggestionsConfig(
args: UpdateQuerySuggestionsConfigCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateQuerySuggestionsConfigCommandOutput) => void
): void;
public updateQuerySuggestionsConfig(
args: UpdateQuerySuggestionsConfigCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateQuerySuggestionsConfigCommandOutput) => void),
cb?: (err: any, data?: UpdateQuerySuggestionsConfigCommandOutput) => void
): Promise<UpdateQuerySuggestionsConfigCommandOutput> | void {
const command = new UpdateQuerySuggestionsConfigCommand(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>Updates a thesaurus file associated with an index.</p>
*/
public updateThesaurus(
args: UpdateThesaurusCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateThesaurusCommandOutput>;
public updateThesaurus(
args: UpdateThesaurusCommandInput,
cb: (err: any, data?: UpdateThesaurusCommandOutput) => void
): void;
public updateThesaurus(
args: UpdateThesaurusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateThesaurusCommandOutput) => void
): void;
public updateThesaurus(
args: UpdateThesaurusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateThesaurusCommandOutput) => void),
cb?: (err: any, data?: UpdateThesaurusCommandOutput) => void
): Promise<UpdateThesaurusCommandOutput> | void {
const command = new UpdateThesaurusCommand(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 { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { IconLoaderService } from '../../../index';
import { AmexioGridItemComponent } from './griditem.component';
import { AmexioGridComponent } from './grid.component';
import { AmexioGridLayoutService } from './amexiogridlayoutservice.service';
describe('amexio-layout-grid', () => {
let comp: AmexioGridComponent;
let fixture: ComponentFixture<AmexioGridComponent>;
let layoutData: any
let deviceName: any;
let desktopWidth: any;
let mobileWidth: any;
let tabletWidth: any;
let gridConstants: any;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [AmexioGridComponent, AmexioGridItemComponent],
providers: [IconLoaderService, AmexioGridLayoutService],
});
fixture = TestBed.createComponent(AmexioGridComponent);
comp = fixture.componentInstance;
comp.isInit = false;
desktopWidth = '(min-width: 1025px)';
mobileWidth = '(max-width: 767px)';
tabletWidth = '(min-width: 768px) and (max-width: 1024px)';
layoutData =
{
"name": "collapsiblegridlayoutdemo3",
"layoutType": "desktop",
"count": 6,
'mobile': [],
'tab': [],
"desktop": [
["west", "north", "north", "north", "north", "east"],
["west", "center", "center", "center", "center", "east"],
["west", "south", "south", "south", "south", "east"]
]
};
deviceName = [
["west", "north", "north", "north", "north", "east"],
["west", "center", "center", "center", "center", "east"],
["west", "south", "south", "south", "south", "east"]
];
gridConstants = {
Tablet: 'tab',
Desktop: 'desktop',
Mobile: 'mobile',
};
});
it('check variable check', () => {
comp.gridItemCollapsible = false;
comp.gridtemplatecolumnconfig = '';
expect(comp.gridItemCollapsible).toEqual(false);
expect(comp.gridtemplatecolumnconfig).toBe('');
});
// it('layout input should set layout() if condition', () => {
// let value = 'amexio';
// comp.isInit = true;
// expect(value).not.toBeNull();
// comp._layout = value;
// expect(comp.isInit).toEqual(true);
// // comp.gridInit();
// });
// it('layout input should set layout() if true & else condition', () => {
// let value = 'amexio';
// comp.isInit = false;
// expect(value).not.toBeNull();
// comp._layout = value;
// expect(comp.isInit).toEqual(false);
// });
// it('gridInit() method check', () => {
// comp.containerClass = '';
// comp.className = '';
// comp.cssGenreration(comp._gridlayoutService.getLayoutData(comp.layout));
// comp.gridInit();
// })
it('cssGenerationNoDesktop() method check dekstop if and if tab ', () => {
comp.colCount = layoutData.count;
comp.className = comp.className + '' + layoutData.name;
comp.cssGenerationNoDesktop(layoutData);
expect(layoutData.desktop.length).toBeGreaterThan(0);
comp.cssGenerationCommonMethod(layoutData, desktopWidth, gridConstants.Desktop);
expect(layoutData.tab.length).toEqual(0);
comp.cssGenerationCommonMethod(layoutData, comp.tabletWidth, gridConstants.Desktop);
});
it('cssGenerationNoDesktop() method check dekstop if and else tab ', () => {
let layoutData =
{
"name": "collapsiblegridlayoutdemo3",
"layoutType": "desktop",
"count": 6,
'mobile': [["west", "north", "north", "north", "north", "east"]],
'tab': [["west", "north", "north", "north", "north", "east"]],
"desktop": [
["west", "north", "north", "north", "north", "east"],
["west", "center", "center", "center", "center", "east"],
["west", "south", "south", "south", "south", "east"]
]
};
comp.colCount = layoutData.count;
comp.className = comp.className + '' + layoutData.name;
comp.cssGenerationNoDesktop(layoutData);
expect(layoutData.desktop.length).toBeGreaterThan(0);
comp.cssGenerationCommonMethod(layoutData, desktopWidth, gridConstants.Desktop);
expect(layoutData.tab.length).not.toEqual(0);
comp.cssGenerationCommonMethod(layoutData, tabletWidth, gridConstants.Tablet);
})
it('cssGenerationNoDesktop() method check dekstop if and tab if and mobile if ', () => {
comp.colCount = layoutData.count;
comp.className = comp.className + '' + layoutData.name;
comp.cssGenerationNoDesktop(layoutData);
expect(layoutData.desktop.length).toBeGreaterThan(0);
comp.cssGenerationCommonMethod(layoutData, desktopWidth, gridConstants.Desktop);
expect(layoutData.tab.length).toEqual(0);
expect(layoutData.mobile.length).toEqual(0);
comp.cssGenerationCommonMethod(layoutData, mobileWidth, gridConstants.Desktop);
});
it('cssGenerationNoDesktop() method check dekstop if and tab greater than 0 and mobile if ', () => {
let layoutData =
{
"name": "collapsiblegridlayoutdemo3",
"layoutType": "desktop",
"count": 6,
"mobile": "",
'tab': [["west", "north", "north", "north", "north", "east"]],
"desktop": [
["west", "north", "north", "north", "north", "east"],
["west", "center", "center", "center", "center", "east"],
["west", "south", "south", "south", "south", "east"]
]
};
comp.colCount = layoutData.count;
comp.className = comp.className + '' + layoutData.name;
comp.cssGenerationNoDesktop(layoutData);
expect(layoutData.desktop.length).toBeGreaterThan(0);
comp.cssGenerationCommonMethod(layoutData, desktopWidth, gridConstants.Desktop);
expect(layoutData.tab.length).toBeGreaterThan(0);
expect(layoutData.mobile.length).toEqual(0);
comp.cssGenerationCommonMethod(layoutData, mobileWidth, gridConstants.Tablet);
});
// it('cssGenerationNoDesktop() method check dekstop if and tab else and mobile if ', () => {
// let layoutData =
// {
// "name": "collapsiblegridlayoutdemo3",
// "layoutType": "desktop",
// "count": 6,
// "mobile": ["west", "north", "north", "north", "north", "east"],
// 'tab': ["west", "north", "north", "north", "north", "east"],
// "desktop": [
// ["west", "north", "north", "north", "north", "east"],
// ["west", "center", "center", "center", "center", "east"],
// ["west", "south", "south", "south", "south", "east"]
// ]
// };
// comp.colCount = layoutData.count;
// comp.className = comp.className + '' + layoutData.name;
// comp.cssGenerationNoDesktop(layoutData);
// expect(layoutData.desktop.length).toBeGreaterThan(0);
// comp.cssGenerationCommonMethod(layoutData, desktopWidth, gridConstants.Desktop);
// expect(layoutData.tab.length).toBeGreaterThan(0);
// expect(layoutData.mobile.length).toBeGreaterThan(0);
// comp.cssGenerationCommonMethod(layoutData, mobileWidth, gridConstants.mobile);
// });
it('cssGenerationNoDesktop() method check dekstop else ', () => {
let layoutData =
{
"name": "collapsiblegridlayoutdemo3",
"layoutType": "desktop",
"count": 6,
"mobile": [["west", "north", "north", "north", "north", "east"]],
'tab': [["west", "north", "north", "north", "north", "east"]],
"desktop": ""
};
console.log(layoutData.desktop.length);
comp.colCount = layoutData.count;
comp.className = comp.className + '' + layoutData.name;
comp.cssGenerationNoDesktop(layoutData);
expect(layoutData.desktop.length).toBe(0);
comp.cssGenerationNoDesktop(layoutData);
});
it('getCssAttribute() if method ', () => {
comp.gridItemCollapsible = true;
comp.getCssAttribute();
expect(comp.gridItemCollapsible).toEqual(true);
return 'display: grid; border:1px solid lightgray;' + ' grid-gap: 0px;'
+ 'grid-template-columns: repeat(' + comp.colCount + ', 1fr);';
});
it('getCssAttribute() else method ', () => {
comp.gridItemCollapsible = false;
comp.getCssAttribute();
expect(comp.gridItemCollapsible).toEqual(false);
return 'display: grid;' + ' grid-gap: 5px;'
+ 'grid-template-columns: repeat(' + comp.colCount + ', 1fr);';
})
it('dataCreation() method ', () => {
comp.containerClass = '';
comp.dataCreation(deviceName);
deviceName.forEach((ele: any) => {
comp.containerClass = comp.containerClass + '"' + ele.join(' ') + '"';
});
return comp.containerClass;
})
it('cssGenerationCommonMethod() method ', () => {
comp.screenWidth = '(min-width: 1025px)';
let deviceType = 'desktop';
comp.cssGenerationCommonMethod(layoutData, comp.screenWidth, deviceType);
comp.insertStyleSheetRuleParent('@' + 'media' + comp.screenWidth + '{' + '.' + layoutData.name +
'{' + comp.getCssAttribute() + ' grid-template-areas: ' +
comp.dataCreation(layoutData[deviceType]) + '}' + '}');
});
// it('insertStyleSheetRuleParent() method ', () => {
// comp.insertStyleSheetRuleParent(ruleText);
// });
}); | the_stack |
import React, { useState, useEffect, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import {
DeploymentCenterFieldProps,
DeploymentCenterCodeFormData,
RuntimeStackSetting,
RuntimeVersionOptions,
RuntimeStackOptions,
DotnetRuntimeVersion,
} from '../DeploymentCenter.types';
import { DeploymentCenterContext } from '../DeploymentCenterContext';
import DeploymentCenterData from '../DeploymentCenter.data';
import { getErrorMessage } from '../../../../ApiHelpers/ArmHelper';
import {
getDefaultVersionDisplayName,
getJavaContainerDisplayName,
getRuntimeStackDisplayName,
getRuntimeStackSetting,
getTelemetryInfo,
} from '../utility/DeploymentCenterUtility';
import { titleWithPaddingStyle } from '../DeploymentCenter.styles';
import { SiteStateContext } from '../../../../SiteState';
import { JavaContainers, WebAppRuntimes, WebAppStack } from '../../../../models/stacks/web-app-stacks';
import { RuntimeStacks } from '../../../../utils/stacks-utils';
import { FunctionAppRuntimes, FunctionAppStack } from '../../../../models/stacks/function-app-stacks';
import { AppStackOs } from '../../../../models/stacks/app-stacks';
import { PortalContext } from '../../../../PortalContext';
import { ArmArray } from '../../../../models/arm-obj';
import ReactiveFormControl from '../../../../components/form-controls/ReactiveFormControl';
import { KeyValue } from '../../../../models/portal-models';
type StackSettings = WebAppRuntimes & JavaContainers | FunctionAppRuntimes;
const DeploymentCenterCodeBuildRuntimeAndVersion: React.FC<DeploymentCenterFieldProps<DeploymentCenterCodeFormData>> = props => {
const { formProps } = props;
const { t } = useTranslation();
// NOTE(michinoy): Disabling preferred array literal rule to allow '.find' operation on the runtimeStacksData.
// tslint:disable-next-line: prefer-array-literal
const [runtimeStacksData, setRuntimeStacksData] = useState<Array<WebAppStack | FunctionAppStack>>([]);
const [defaultStack, setDefaultStack] = useState<string>('');
const [defaultVersion, setDefaultVersion] = useState<string>('');
const [javaContainer, setJavaContainer] = useState<string>('');
const deploymentCenterContext = useContext(DeploymentCenterContext);
const siteStateContext = useContext(SiteStateContext);
const portalContext = useContext(PortalContext);
const deploymentCenterData = new DeploymentCenterData();
const fetchStacks = async () => {
const appOs = siteStateContext.isLinuxApp || siteStateContext.isKubeApp ? AppStackOs.linux : AppStackOs.windows;
portalContext.log(
getTelemetryInfo('info', 'fetchStacks', 'submit', {
appType: siteStateContext.isFunctionApp ? 'functionApp' : 'webApp',
os: appOs,
})
);
const runtimeStacksResponse = siteStateContext.isFunctionApp
? await deploymentCenterData.getFunctionAppRuntimeStacks(appOs)
: await deploymentCenterData.getWebAppRuntimeStacks(appOs);
if (runtimeStacksResponse.metadata.success) {
// NOTE(michinoy): Disabling preferred array literal rule to allow '.map' operation on the runtimeStacksData.
// tslint:disable-next-line: prefer-array-literal
const runtimeStacks = (runtimeStacksResponse.data as ArmArray<WebAppStack | FunctionAppStack>).value.map(stack => stack.properties);
setRuntimeStacksData(runtimeStacks);
} else {
portalContext.log(
getTelemetryInfo('error', 'runtimeStacksResponse', 'failed', {
message: getErrorMessage(runtimeStacksResponse.metadata.error),
errorAsString: JSON.stringify(runtimeStacksResponse.metadata.error),
})
);
}
};
const setDefaultValues = () => {
const defaultStackAndVersion: RuntimeStackSetting = getRuntimeStackSetting(
siteStateContext.isLinuxApp,
siteStateContext.isFunctionApp,
siteStateContext.isKubeApp,
deploymentCenterContext.siteConfig,
deploymentCenterContext.configMetadata,
deploymentCenterContext.applicationSettings
);
//Note (stpelleg): Java is different
if (defaultStackAndVersion.runtimeVersion.toLocaleLowerCase() === RuntimeVersionOptions.Java11) {
defaultStackAndVersion.runtimeVersion = '11.0';
} else if (
defaultStackAndVersion.runtimeVersion.toLocaleLowerCase() === RuntimeVersionOptions.Java8 ||
defaultStackAndVersion.runtimeVersion.toLocaleLowerCase() === RuntimeVersionOptions.Java8Linux
) {
defaultStackAndVersion.runtimeVersion = '8.0';
}
formProps.setFieldValue('runtimeStack', defaultStackAndVersion.runtimeStack);
formProps.setFieldValue('runtimeVersion', defaultStackAndVersion.runtimeVersion.toLocaleLowerCase());
setDefaultStack(getRuntimeStackDisplayName(defaultStackAndVersion.runtimeStack));
setDefaultVersion(getDefaultVersionDisplayName(defaultStackAndVersion.runtimeVersion, siteStateContext.isLinuxApp));
};
const updateJavaContainer = () => {
if (deploymentCenterContext.siteConfig && formProps.values.runtimeStack && formProps.values.runtimeStack === RuntimeStacks.java) {
const siteConfigJavaContainer = siteStateContext.isLinuxApp
? deploymentCenterContext.siteConfig.properties.linuxFxVersion.toLowerCase().split('|')[0]
: deploymentCenterContext.siteConfig.properties.javaContainer &&
deploymentCenterContext.siteConfig.properties.javaContainer.toLowerCase();
formProps.setFieldValue('javaContainer', siteConfigJavaContainer);
setJavaContainer(getJavaContainerDisplayName(siteConfigJavaContainer));
} else {
formProps.setFieldValue('javaContainer', '');
setJavaContainer('');
}
};
const setGitHubActionsRecommendedVersion = () => {
// NOTE(michinoy): Try our best to get the GitHub Action recommended version from the stacks API. At worst case,
// select the minor version. Do not fail at this point, like this in case if a new stack is incorrectly added, we can
// always fall back on the minor version instead of blocking or messing customers workflow file.
const gitHubActionRuntimeVersionMapping: KeyValue<string> = {};
const curStack = formProps.values.runtimeStack || '';
const runtimeStack = runtimeStacksData.find(stack => stack.value.toLocaleLowerCase() === curStack);
if (runtimeStack) {
runtimeStack.majorVersions.forEach(majorVersion => {
majorVersion.minorVersions.forEach(minorVersion => {
let value = minorVersion.value;
value =
(siteStateContext.isLinuxApp || siteStateContext.isKubeApp) &&
minorVersion.stackSettings.linuxRuntimeSettings &&
minorVersion.stackSettings.linuxRuntimeSettings.runtimeVersion
? minorVersion.stackSettings.linuxRuntimeSettings.runtimeVersion
: value;
value =
!siteStateContext.isLinuxApp &&
!siteStateContext.isKubeApp &&
minorVersion.stackSettings.windowsRuntimeSettings &&
minorVersion.stackSettings.windowsRuntimeSettings.runtimeVersion
? minorVersion.stackSettings.windowsRuntimeSettings.runtimeVersion
: value;
addGitHubActionRuntimeVersionMapping(
curStack,
value.toLocaleLowerCase(),
minorVersion.stackSettings,
gitHubActionRuntimeVersionMapping
);
});
});
}
//Note (stpelleg): Java is different
let curVersion = formProps.values.runtimeVersion || '';
if (curVersion === '11.0') {
curVersion = '11';
} else if (curVersion === '8.0') {
curVersion = '8';
}
const key = generateGitHubActionRuntimeVersionMappingKey(siteStateContext.isLinuxApp, curStack, curVersion);
const version = gitHubActionRuntimeVersionMapping[key] ? gitHubActionRuntimeVersionMapping[key] : curVersion;
formProps.setFieldValue('runtimeRecommendedVersion', version);
};
const addGitHubActionRuntimeVersionMapping = (
stack: string,
minorVersion: string,
stackSettings: StackSettings,
gitHubActionRuntimeVersionMapping: KeyValue<string>
) => {
// NOTE(michinoy): Try our best to get the GitHub Action recommended version from the stacks API. At worst case,
// select the minor version. Do not fail at this point, like this in case if a new stack is incorrectly added, we can
// always fall back on the minor version instead of blocking or messing customers workflow file.
const key = generateGitHubActionRuntimeVersionMappingKey(siteStateContext.isLinuxApp, stack, minorVersion);
let version = minorVersion;
if (stackSettings.linuxRuntimeSettings) {
version = stackSettings.linuxRuntimeSettings.gitHubActionSettings.supportedVersion
? stackSettings.linuxRuntimeSettings.gitHubActionSettings.supportedVersion
: minorVersion;
} else if (stackSettings.windowsRuntimeSettings) {
version = stackSettings.windowsRuntimeSettings.gitHubActionSettings.supportedVersion
? stackSettings.windowsRuntimeSettings.gitHubActionSettings.supportedVersion
: minorVersion;
//NOTE(stpelleg): Need to get Dotnet version from runtime settings if ASPNET
if (!!stack && stack.toLocaleLowerCase() === RuntimeStackOptions.Dotnet) {
const dotnetversion =
!!stackSettings.windowsRuntimeSettings && !!stackSettings.windowsRuntimeSettings.runtimeVersion
? stackSettings.windowsRuntimeSettings.runtimeVersion
: '';
if (!!dotnetversion && (dotnetversion === DotnetRuntimeVersion.aspNetv4 || dotnetversion === DotnetRuntimeVersion.aspNetv2)) {
version = dotnetversion;
}
}
}
gitHubActionRuntimeVersionMapping[key] = version;
};
const generateGitHubActionRuntimeVersionMappingKey = (isLinuxApp: boolean, stack: string, minorVersion: string): string => {
const os = isLinuxApp ? AppStackOs.linux : AppStackOs.windows;
return `${os}-${stack.toLocaleLowerCase()}-${minorVersion.toLocaleLowerCase()}`;
};
const initializeFormValues = () => {
formProps.setFieldValue('runtimeStack', '');
formProps.setFieldValue('runtimeVersion', '');
formProps.setFieldValue('runtimeRecommendedVersion', '');
formProps.setFieldValue('javaContainer', '');
};
useEffect(() => {
initializeFormValues();
fetchStacks();
setDefaultValues();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!!defaultStack && runtimeStacksData.length > 0) {
updateJavaContainer();
setGitHubActionsRecommendedVersion();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [defaultStack, runtimeStacksData]);
return (
<>
<h3 className={titleWithPaddingStyle}>{t('deploymentCenterSettingsBuildTitle')}</h3>
<ReactiveFormControl id="deployment-center-code-settings-runtime-stack" label={t('deploymentCenterSettingsRuntimeLabel')}>
<div>{defaultStack}</div>
</ReactiveFormControl>
<ReactiveFormControl id="deployment-center-code-settings-runtime-version" label={t('deploymentCenterSettingsRuntimeVersionLabel')}>
<div>{defaultVersion}</div>
</ReactiveFormControl>
{javaContainer && (
<ReactiveFormControl id="deployment-center-code-settings-java-container" label={t('deploymentCenterJavaWebServerStack')}>
<div>{javaContainer}</div>
</ReactiveFormControl>
)}
</>
);
};
export default DeploymentCenterCodeBuildRuntimeAndVersion; | the_stack |
import { Observable } from 'rxjs';
/**
* Namespace nt_module_user.
* @exports nt_module_user
* @namespace
*/
export namespace nt_module_user {
/**
* Contains all the RPC service clients.
* @exports nt_module_user.ClientFactory
* @interface
*/
export interface ClientFactory {
/**
* Returns the InfoGroupService service client.
* @returns {nt_module_user.InfoGroupService}
*/
getInfoGroupService(): nt_module_user.InfoGroupService;
/**
* Returns the InfoItemService service client.
* @returns {nt_module_user.InfoItemService}
*/
getInfoItemService(): nt_module_user.InfoItemService;
/**
* Returns the OrganizationService service client.
* @returns {nt_module_user.OrganizationService}
*/
getOrganizationService(): nt_module_user.OrganizationService;
/**
* Returns the SystemModuleService service client.
* @returns {nt_module_user.SystemModuleService}
*/
getSystemModuleService(): nt_module_user.SystemModuleService;
/**
* Returns the ResourceService service client.
* @returns {nt_module_user.ResourceService}
*/
getResourceService(): nt_module_user.ResourceService;
/**
* Returns the RoleService service client.
* @returns {nt_module_user.RoleService}
*/
getRoleService(): nt_module_user.RoleService;
/**
* Returns the UserService service client.
* @returns {nt_module_user.UserService}
*/
getUserService(): nt_module_user.UserService;
}
/**
* Builder for an RPC service server.
* @exports nt_module_user.ServerBuilder
* @interface
*/
export interface ServerBuilder {
/**
* Adds a InfoGroupService service implementation.
* @param {nt_module_user.InfoGroupService} impl InfoGroupService service implementation
* @returns {nt_module_user.ServerBuilder}
*/
addInfoGroupService(impl: nt_module_user.InfoGroupService): nt_module_user.ServerBuilder;
/**
* Adds a InfoItemService service implementation.
* @param {nt_module_user.InfoItemService} impl InfoItemService service implementation
* @returns {nt_module_user.ServerBuilder}
*/
addInfoItemService(impl: nt_module_user.InfoItemService): nt_module_user.ServerBuilder;
/**
* Adds a OrganizationService service implementation.
* @param {nt_module_user.OrganizationService} impl OrganizationService service implementation
* @returns {nt_module_user.ServerBuilder}
*/
addOrganizationService(impl: nt_module_user.OrganizationService): nt_module_user.ServerBuilder;
/**
* Adds a SystemModuleService service implementation.
* @param {nt_module_user.SystemModuleService} impl SystemModuleService service implementation
* @returns {nt_module_user.ServerBuilder}
*/
addSystemModuleService(impl: nt_module_user.SystemModuleService): nt_module_user.ServerBuilder;
/**
* Adds a ResourceService service implementation.
* @param {nt_module_user.ResourceService} impl ResourceService service implementation
* @returns {nt_module_user.ServerBuilder}
*/
addResourceService(impl: nt_module_user.ResourceService): nt_module_user.ServerBuilder;
/**
* Adds a RoleService service implementation.
* @param {nt_module_user.RoleService} impl RoleService service implementation
* @returns {nt_module_user.ServerBuilder}
*/
addRoleService(impl: nt_module_user.RoleService): nt_module_user.ServerBuilder;
/**
* Adds a UserService service implementation.
* @param {nt_module_user.UserService} impl UserService service implementation
* @returns {nt_module_user.ServerBuilder}
*/
addUserService(impl: nt_module_user.UserService): nt_module_user.ServerBuilder;
}
/**
* Constructs a new PlaceholderRequest.
* @exports nt_module_user.PlaceholderRequest
* @interface
*/
export interface PlaceholderRequest {
}
/**
* Constructs a new StringDataResponse.
* @exports nt_module_user.StringDataResponse
* @interface
*/
export interface StringDataResponse {
/**
* StringDataResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* StringDataResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* StringDataResponse data.
* @type {string|undefined}
*/
data?: string;
}
/**
* Constructs a new FindDataByPageRequest.
* @exports nt_module_user.FindDataByPageRequest
* @interface
*/
export interface FindDataByPageRequest {
/**
* FindDataByPageRequest pageNumber.
* @type {number|undefined}
*/
pageNumber?: number;
/**
* FindDataByPageRequest pageSize.
* @type {number|undefined}
*/
pageSize?: number;
}
/**
* Constructs a new InfoGroupService service.
* @exports nt_module_user.InfoGroupService
* @interface
*/
export interface InfoGroupService {
/**
* Calls CreateInfoGroup.
* @param {nt_module_user.CreateInfoGroupRequest} request CreateInfoGroupRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
createInfoGroup(request: nt_module_user.CreateInfoGroupRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeleteInfoGroup.
* @param {nt_module_user.DeleteInfoGroupRequest} request DeleteInfoGroupRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deleteInfoGroup(request: nt_module_user.DeleteInfoGroupRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls UpdateInfoGroup.
* @param {nt_module_user.UpdateInfoGroupRequest} request UpdateInfoGroupRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
updateInfoGroup(request: nt_module_user.UpdateInfoGroupRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls AddInfoItemToInfoGroup.
* @param {nt_module_user.AddInfoItemToInfoGroupRequest} request AddInfoItemToInfoGroupRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
addInfoItemToInfoGroup(request: nt_module_user.AddInfoItemToInfoGroupRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeleteIntoItemFromInfoGroup.
* @param {nt_module_user.DeleteIntoItemFromInfoGroupRequest} request DeleteIntoItemFromInfoGroupRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deleteIntoItemFromInfoGroup(request: nt_module_user.DeleteIntoItemFromInfoGroupRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls FindAllInfoGroup.
* @param {nt_module_user.FindDataByPageRequest} request FindDataByPageRequest message or plain object
* @returns {Observable<nt_module_user.FindAllInfoGroupResponse>}
*/
findAllInfoGroup(request: nt_module_user.FindDataByPageRequest): Observable<nt_module_user.FindAllInfoGroupResponse>;
/**
* Calls FindInfoItemsByGroupId.
* @param {nt_module_user.FindInfoItemsByGroupIdRequest} request FindInfoItemsByGroupIdRequest message or plain object
* @returns {Observable<nt_module_user.FindInfoItemsByGroupIdResponse>}
*/
findInfoItemsByGroupId(request: nt_module_user.FindInfoItemsByGroupIdRequest): Observable<nt_module_user.FindInfoItemsByGroupIdResponse>;
}
/**
* Constructs a new CreateInfoGroupRequest.
* @exports nt_module_user.CreateInfoGroupRequest
* @interface
*/
export interface CreateInfoGroupRequest {
/**
* CreateInfoGroupRequest name.
* @type {string|undefined}
*/
name?: string;
/**
* CreateInfoGroupRequest roleId.
* @type {number|undefined}
*/
roleId?: number;
}
/**
* Constructs a new DeleteInfoGroupRequest.
* @exports nt_module_user.DeleteInfoGroupRequest
* @interface
*/
export interface DeleteInfoGroupRequest {
/**
* DeleteInfoGroupRequest groupId.
* @type {number|undefined}
*/
groupId?: number;
}
/**
* Constructs a new UpdateInfoGroupRequest.
* @exports nt_module_user.UpdateInfoGroupRequest
* @interface
*/
export interface UpdateInfoGroupRequest {
/**
* UpdateInfoGroupRequest groupId.
* @type {number|undefined}
*/
groupId?: number;
/**
* UpdateInfoGroupRequest name.
* @type {string|undefined}
*/
name?: string;
/**
* UpdateInfoGroupRequest roleId.
* @type {number|undefined}
*/
roleId?: number;
}
/**
* Constructs a new AddInfoItemToInfoGroupRequest.
* @exports nt_module_user.AddInfoItemToInfoGroupRequest
* @interface
*/
export interface AddInfoItemToInfoGroupRequest {
/**
* AddInfoItemToInfoGroupRequest infoGroupId.
* @type {number|undefined}
*/
infoGroupId?: number;
/**
* AddInfoItemToInfoGroupRequest infoItemIds.
* @type {Array.<number>|undefined}
*/
infoItemIds?: number[];
}
/**
* Constructs a new DeleteIntoItemFromInfoGroupRequest.
* @exports nt_module_user.DeleteIntoItemFromInfoGroupRequest
* @interface
*/
export interface DeleteIntoItemFromInfoGroupRequest {
/**
* DeleteIntoItemFromInfoGroupRequest infoGroupId.
* @type {number|undefined}
*/
infoGroupId?: number;
/**
* DeleteIntoItemFromInfoGroupRequest infoItemIds.
* @type {Array.<number>|undefined}
*/
infoItemIds?: number[];
}
/**
* Constructs a new FindAllInfoGroupResponse.
* @exports nt_module_user.FindAllInfoGroupResponse
* @interface
*/
export interface FindAllInfoGroupResponse {
/**
* FindAllInfoGroupResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindAllInfoGroupResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindAllInfoGroupResponse data.
* @type {Array.<nt_module_user.InfoGroup>|undefined}
*/
data?: nt_module_user.InfoGroup[];
/**
* FindAllInfoGroupResponse count.
* @type {number|undefined}
*/
count?: number;
}
/**
* Constructs a new InfoGroup.
* @exports nt_module_user.InfoGroup
* @interface
*/
export interface InfoGroup {
/**
* InfoGroup id.
* @type {number|undefined}
*/
id?: number;
/**
* InfoGroup name.
* @type {string|undefined}
*/
name?: string;
}
/**
* Constructs a new FindInfoItemsByGroupIdRequest.
* @exports nt_module_user.FindInfoItemsByGroupIdRequest
* @interface
*/
export interface FindInfoItemsByGroupIdRequest {
/**
* FindInfoItemsByGroupIdRequest infoGroupId.
* @type {number|undefined}
*/
infoGroupId?: number;
}
/**
* Constructs a new FindInfoItemsByGroupIdResponse.
* @exports nt_module_user.FindInfoItemsByGroupIdResponse
* @interface
*/
export interface FindInfoItemsByGroupIdResponse {
/**
* FindInfoItemsByGroupIdResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindInfoItemsByGroupIdResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindInfoItemsByGroupIdResponse data.
* @type {Array.<nt_module_user.InfoItem>|undefined}
*/
data?: nt_module_user.InfoItem[];
}
/**
* Constructs a new InfoItem.
* @exports nt_module_user.InfoItem
* @interface
*/
export interface InfoItem {
/**
* InfoItem id.
* @type {number|undefined}
*/
id?: number;
/**
* InfoItem name.
* @type {string|undefined}
*/
name?: string;
/**
* InfoItem description.
* @type {string|undefined}
*/
description?: string;
/**
* InfoItem type.
* @type {string|undefined}
*/
type?: string;
/**
* InfoItem registerDisplay.
* @type {boolean|undefined}
*/
registerDisplay?: boolean;
/**
* InfoItem informationDisplay.
* @type {boolean|undefined}
*/
informationDisplay?: boolean;
/**
* InfoItem order.
* @type {number|undefined}
*/
order?: number;
}
/**
* Constructs a new InfoItemService service.
* @exports nt_module_user.InfoItemService
* @interface
*/
export interface InfoItemService {
/**
* Calls CreateInfoItem.
* @param {nt_module_user.CreateInfoItemRequest} request CreateInfoItemRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
createInfoItem(request: nt_module_user.CreateInfoItemRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeleteInfoItem.
* @param {nt_module_user.DeleteInfoItemRequest} request DeleteInfoItemRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deleteInfoItem(request: nt_module_user.DeleteInfoItemRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls UpdateInfoItem.
* @param {nt_module_user.UpdateInfoItemRequest} request UpdateInfoItemRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
updateInfoItem(request: nt_module_user.UpdateInfoItemRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls FindAllInfoItem.
* @param {nt_module_user.FindDataByPageRequest} request FindDataByPageRequest message or plain object
* @returns {Observable<nt_module_user.FindAllInfoItemResponse>}
*/
findAllInfoItem(request: nt_module_user.FindDataByPageRequest): Observable<nt_module_user.FindAllInfoItemResponse>;
}
/**
* Constructs a new CreateInfoItemRequest.
* @exports nt_module_user.CreateInfoItemRequest
* @interface
*/
export interface CreateInfoItemRequest {
/**
* CreateInfoItemRequest infoItemInput.
* @type {nt_module_user.InfoItem|undefined}
*/
infoItemInput?: nt_module_user.InfoItem;
}
export namespace CreateInfoItemRequest {
/**
* Constructs a new InfoItemInput.
* @exports nt_module_user.CreateInfoItemRequest.InfoItemInput
* @interface
*/
export interface InfoItemInput {
/**
* InfoItemInput name.
* @type {string|undefined}
*/
name?: string;
/**
* InfoItemInput description.
* @type {string|undefined}
*/
description?: string;
/**
* InfoItemInput type.
* @type {string|undefined}
*/
type?: string;
/**
* InfoItemInput registerDisplay.
* @type {boolean|undefined}
*/
registerDisplay?: boolean;
/**
* InfoItemInput informationDisplay.
* @type {boolean|undefined}
*/
informationDisplay?: boolean;
/**
* InfoItemInput order.
* @type {number|undefined}
*/
order?: number;
}
}
/**
* Constructs a new DeleteInfoItemRequest.
* @exports nt_module_user.DeleteInfoItemRequest
* @interface
*/
export interface DeleteInfoItemRequest {
/**
* DeleteInfoItemRequest infoItemId.
* @type {number|undefined}
*/
infoItemId?: number;
}
/**
* Constructs a new UpdateInfoItemRequest.
* @exports nt_module_user.UpdateInfoItemRequest
* @interface
*/
export interface UpdateInfoItemRequest {
/**
* UpdateInfoItemRequest updateInfoItemInput.
* @type {nt_module_user.InfoItem|undefined}
*/
updateInfoItemInput?: nt_module_user.InfoItem;
}
/**
* Constructs a new FindAllInfoItemResponse.
* @exports nt_module_user.FindAllInfoItemResponse
* @interface
*/
export interface FindAllInfoItemResponse {
/**
* FindAllInfoItemResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindAllInfoItemResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindAllInfoItemResponse data.
* @type {Array.<nt_module_user.InfoItem>|undefined}
*/
data?: nt_module_user.InfoItem[];
/**
* FindAllInfoItemResponse count.
* @type {number|undefined}
*/
count?: number;
}
/**
* Constructs a new OrganizationService service.
* @exports nt_module_user.OrganizationService
* @interface
*/
export interface OrganizationService {
/**
* Calls CreateOrganization.
* @param {nt_module_user.CreateOrganizationRequest} request CreateOrganizationRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
createOrganization(request: nt_module_user.CreateOrganizationRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls AddUsersToOrganization.
* @param {nt_module_user.AddUsersToOrganizationRequest} request AddUsersToOrganizationRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
addUsersToOrganization(request: nt_module_user.AddUsersToOrganizationRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeleteOrganization.
* @param {nt_module_user.DeleteOrganizationRequest} request DeleteOrganizationRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deleteOrganization(request: nt_module_user.DeleteOrganizationRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeleteUserFromOrganization.
* @param {nt_module_user.DeleteUserFromOrganizationRequest} request DeleteUserFromOrganizationRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deleteUserFromOrganization(request: nt_module_user.DeleteUserFromOrganizationRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls UpdateOrganization.
* @param {nt_module_user.UpdateOrganizationRequest} request UpdateOrganizationRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
updateOrganization(request: nt_module_user.UpdateOrganizationRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls FindRootOrganizations.
* @param {nt_module_user.PlaceholderRequest} request PlaceholderRequest message or plain object
* @returns {Observable<nt_module_user.FindRootOrganizationsResponse>}
*/
findRootOrganizations(request: nt_module_user.PlaceholderRequest): Observable<nt_module_user.FindRootOrganizationsResponse>;
/**
* Calls FindAllOrganizations.
* @param {nt_module_user.PlaceholderRequest} request PlaceholderRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
findAllOrganizations(request: nt_module_user.PlaceholderRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls FindChildrenOrganizations.
* @param {nt_module_user.FindChildrenOrganizationsRequest} request FindChildrenOrganizationsRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
findChildrenOrganizations(request: nt_module_user.FindChildrenOrganizationsRequest): Observable<nt_module_user.StringDataResponse>;
}
/**
* Constructs a new CreateOrganizationRequest.
* @exports nt_module_user.CreateOrganizationRequest
* @interface
*/
export interface CreateOrganizationRequest {
/**
* CreateOrganizationRequest name.
* @type {string|undefined}
*/
name?: string;
/**
* CreateOrganizationRequest parentId.
* @type {number|undefined}
*/
parentId?: number;
}
/**
* Constructs a new AddUsersToOrganizationRequest.
* @exports nt_module_user.AddUsersToOrganizationRequest
* @interface
*/
export interface AddUsersToOrganizationRequest {
/**
* AddUsersToOrganizationRequest id.
* @type {number|undefined}
*/
id?: number;
/**
* AddUsersToOrganizationRequest userIds.
* @type {Array.<number>|undefined}
*/
userIds?: number[];
}
/**
* Constructs a new DeleteOrganizationRequest.
* @exports nt_module_user.DeleteOrganizationRequest
* @interface
*/
export interface DeleteOrganizationRequest {
/**
* DeleteOrganizationRequest id.
* @type {number|undefined}
*/
id?: number;
}
/**
* Constructs a new DeleteUserFromOrganizationRequest.
* @exports nt_module_user.DeleteUserFromOrganizationRequest
* @interface
*/
export interface DeleteUserFromOrganizationRequest {
/**
* DeleteUserFromOrganizationRequest id.
* @type {number|undefined}
*/
id?: number;
/**
* DeleteUserFromOrganizationRequest userIds.
* @type {Array.<number>|undefined}
*/
userIds?: number[];
}
/**
* Constructs a new UpdateOrganizationRequest.
* @exports nt_module_user.UpdateOrganizationRequest
* @interface
*/
export interface UpdateOrganizationRequest {
/**
* UpdateOrganizationRequest id.
* @type {number|undefined}
*/
id?: number;
/**
* UpdateOrganizationRequest name.
* @type {string|undefined}
*/
name?: string;
/**
* UpdateOrganizationRequest parentId.
* @type {number|undefined}
*/
parentId?: number;
}
/**
* Constructs a new FindRootOrganizationsResponse.
* @exports nt_module_user.FindRootOrganizationsResponse
* @interface
*/
export interface FindRootOrganizationsResponse {
/**
* FindRootOrganizationsResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindRootOrganizationsResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindRootOrganizationsResponse data.
* @type {Array.<nt_module_user.Organization>|undefined}
*/
data?: nt_module_user.Organization[];
}
/**
* Constructs a new Organization.
* @exports nt_module_user.Organization
* @interface
*/
export interface Organization {
/**
* Organization id.
* @type {number|undefined}
*/
id?: number;
/**
* Organization name.
* @type {string|undefined}
*/
name?: string;
}
/**
* Constructs a new FindChildrenOrganizationsRequest.
* @exports nt_module_user.FindChildrenOrganizationsRequest
* @interface
*/
export interface FindChildrenOrganizationsRequest {
/**
* FindChildrenOrganizationsRequest id.
* @type {number|undefined}
*/
id?: number;
}
/**
* Constructs a new SystemModuleService service.
* @exports nt_module_user.SystemModuleService
* @interface
*/
export interface SystemModuleService {
/**
* Calls FindSystemModules.
* @param {nt_module_user.FindDataByPageRequest} request FindDataByPageRequest message or plain object
* @returns {Observable<nt_module_user.FindSystemModuleResponse>}
*/
findSystemModules(request: nt_module_user.FindDataByPageRequest): Observable<nt_module_user.FindSystemModuleResponse>;
}
/**
* Constructs a new FindSystemModuleResponse.
* @exports nt_module_user.FindSystemModuleResponse
* @interface
*/
export interface FindSystemModuleResponse {
/**
* FindSystemModuleResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindSystemModuleResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindSystemModuleResponse data.
* @type {Array.<nt_module_user.FindSystemModuleResponse.SystemModule>|undefined}
*/
data?: nt_module_user.FindSystemModuleResponse.SystemModule[];
/**
* FindSystemModuleResponse count.
* @type {number|undefined}
*/
count?: number;
}
export namespace FindSystemModuleResponse {
/**
* Constructs a new SystemModule.
* @exports nt_module_user.FindSystemModuleResponse.SystemModule
* @interface
*/
export interface SystemModule {
/**
* SystemModule id.
* @type {number|undefined}
*/
id?: number;
/**
* SystemModule name.
* @type {string|undefined}
*/
name?: string;
}
}
/**
* Constructs a new ResourceService service.
* @exports nt_module_user.ResourceService
* @interface
*/
export interface ResourceService {
/**
* Calls FindResources.
* @param {nt_module_user.FindResourcesRequest} request FindResourcesRequest message or plain object
* @returns {Observable<nt_module_user.FindResourcesResponse>}
*/
findResources(request: nt_module_user.FindResourcesRequest): Observable<nt_module_user.FindResourcesResponse>;
/**
* Calls SaveResourcesAndPermissions.
* @param {nt_module_user.SaveResourcesAndPermissionsRequest} request SaveResourcesAndPermissionsRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
saveResourcesAndPermissions(request: nt_module_user.SaveResourcesAndPermissionsRequest): Observable<nt_module_user.StringDataResponse>;
}
/**
* Constructs a new FindResourcesRequest.
* @exports nt_module_user.FindResourcesRequest
* @interface
*/
export interface FindResourcesRequest {
/**
* FindResourcesRequest systemModuleId.
* @type {number|undefined}
*/
systemModuleId?: number;
/**
* FindResourcesRequest pageNumber.
* @type {number|undefined}
*/
pageNumber?: number;
/**
* FindResourcesRequest pageSize.
* @type {number|undefined}
*/
pageSize?: number;
}
/**
* Constructs a new SaveResourcesAndPermissionsRequest.
* @exports nt_module_user.SaveResourcesAndPermissionsRequest
* @interface
*/
export interface SaveResourcesAndPermissionsRequest {
/**
* SaveResourcesAndPermissionsRequest metadata.
* @type {string|undefined}
*/
metadata?: string;
}
/**
* Constructs a new FindResourcesResponse.
* @exports nt_module_user.FindResourcesResponse
* @interface
*/
export interface FindResourcesResponse {
/**
* FindResourcesResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindResourcesResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindResourcesResponse data.
* @type {Array.<nt_module_user.FindResourcesResponse.Resource>|undefined}
*/
data?: nt_module_user.FindResourcesResponse.Resource[];
/**
* FindResourcesResponse count.
* @type {number|undefined}
*/
count?: number;
}
export namespace FindResourcesResponse {
/**
* Constructs a new Resource.
* @exports nt_module_user.FindResourcesResponse.Resource
* @interface
*/
export interface Resource {
/**
* Resource id.
* @type {number|undefined}
*/
id?: number;
/**
* Resource name.
* @type {string|undefined}
*/
name?: string;
/**
* Resource identify.
* @type {string|undefined}
*/
identify?: string;
/**
* Resource permissions.
* @type {Array.<nt_module_user.Permission>|undefined}
*/
permissions?: nt_module_user.Permission[];
}
}
/**
* Constructs a new Permission.
* @exports nt_module_user.Permission
* @interface
*/
export interface Permission {
/**
* Permission id.
* @type {number|undefined}
*/
id?: number;
/**
* Permission name.
* @type {string|undefined}
*/
name?: string;
/**
* Permission action.
* @type {string|undefined}
*/
action?: string;
/**
* Permission identify.
* @type {string|undefined}
*/
identify?: string;
}
/**
* Constructs a new RoleService service.
* @exports nt_module_user.RoleService
* @interface
*/
export interface RoleService {
/**
* Calls CreateRole.
* @param {nt_module_user.CreateRoleRequest} request CreateRoleRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
createRole(request: nt_module_user.CreateRoleRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeleteRole.
* @param {nt_module_user.DeleteRoleRequest} request DeleteRoleRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deleteRole(request: nt_module_user.DeleteRoleRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls UpdateRole.
* @param {nt_module_user.UpdateRoleRequest} request UpdateRoleRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
updateRole(request: nt_module_user.UpdateRoleRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls RemovePermissionOfRole.
* @param {nt_module_user.RemovePermissionRequest} request RemovePermissionRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
removePermissionOfRole(request: nt_module_user.RemovePermissionRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls SetPermissionsToRole.
* @param {nt_module_user.SetPermissionToRoleRequest} request SetPermissionToRoleRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
setPermissionsToRole(request: nt_module_user.SetPermissionToRoleRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls FindRoles.
* @param {nt_module_user.FindDataByPageRequest} request FindDataByPageRequest message or plain object
* @returns {Observable<nt_module_user.FindRolesResponse>}
*/
findRoles(request: nt_module_user.FindDataByPageRequest): Observable<nt_module_user.FindRolesResponse>;
/**
* Calls FindOneRoleInfo.
* @param {nt_module_user.FindOneRoleInfoRequest} request FindOneRoleInfoRequest message or plain object
* @returns {Observable<nt_module_user.FindOneRoleInfoResponse>}
*/
findOneRoleInfo(request: nt_module_user.FindOneRoleInfoRequest): Observable<nt_module_user.FindOneRoleInfoResponse>;
}
/**
* Constructs a new CreateRoleRequest.
* @exports nt_module_user.CreateRoleRequest
* @interface
*/
export interface CreateRoleRequest {
/**
* CreateRoleRequest name.
* @type {string|undefined}
*/
name?: string;
}
/**
* Constructs a new DeleteRoleRequest.
* @exports nt_module_user.DeleteRoleRequest
* @interface
*/
export interface DeleteRoleRequest {
/**
* DeleteRoleRequest id.
* @type {number|undefined}
*/
id?: number;
}
/**
* Constructs a new UpdateRoleRequest.
* @exports nt_module_user.UpdateRoleRequest
* @interface
*/
export interface UpdateRoleRequest {
/**
* UpdateRoleRequest id.
* @type {number|undefined}
*/
id?: number;
/**
* UpdateRoleRequest name.
* @type {string|undefined}
*/
name?: string;
}
/**
* Constructs a new RemovePermissionRequest.
* @exports nt_module_user.RemovePermissionRequest
* @interface
*/
export interface RemovePermissionRequest {
/**
* RemovePermissionRequest roleId.
* @type {number|undefined}
*/
roleId?: number;
/**
* RemovePermissionRequest permissionId.
* @type {number|undefined}
*/
permissionId?: number;
}
/**
* Constructs a new SetPermissionToRoleRequest.
* @exports nt_module_user.SetPermissionToRoleRequest
* @interface
*/
export interface SetPermissionToRoleRequest {
/**
* SetPermissionToRoleRequest roleId.
* @type {number|undefined}
*/
roleId?: number;
/**
* SetPermissionToRoleRequest permissionIds.
* @type {Array.<number>|undefined}
*/
permissionIds?: number[];
}
/**
* Constructs a new FindRolesResponse.
* @exports nt_module_user.FindRolesResponse
* @interface
*/
export interface FindRolesResponse {
/**
* FindRolesResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindRolesResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindRolesResponse data.
* @type {Array.<nt_module_user.RoleData>|undefined}
*/
data?: nt_module_user.RoleData[];
/**
* FindRolesResponse count.
* @type {number|undefined}
*/
count?: number;
}
/**
* Constructs a new RoleData.
* @exports nt_module_user.RoleData
* @interface
*/
export interface RoleData {
/**
* RoleData id.
* @type {number|undefined}
*/
id?: number;
/**
* RoleData name.
* @type {string|undefined}
*/
name?: string;
}
/**
* Constructs a new FindOneRoleInfoRequest.
* @exports nt_module_user.FindOneRoleInfoRequest
* @interface
*/
export interface FindOneRoleInfoRequest {
/**
* FindOneRoleInfoRequest roleId.
* @type {number|undefined}
*/
roleId?: number;
}
/**
* Constructs a new FindOneRoleInfoResponse.
* @exports nt_module_user.FindOneRoleInfoResponse
* @interface
*/
export interface FindOneRoleInfoResponse {
/**
* FindOneRoleInfoResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindOneRoleInfoResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindOneRoleInfoResponse data.
* @type {nt_module_user.OneRoleInfoData|undefined}
*/
data?: nt_module_user.OneRoleInfoData;
}
/**
* Constructs a new OneRoleInfoData.
* @exports nt_module_user.OneRoleInfoData
* @interface
*/
export interface OneRoleInfoData {
/**
* OneRoleInfoData id.
* @type {number|undefined}
*/
id?: number;
/**
* OneRoleInfoData name.
* @type {string|undefined}
*/
name?: string;
/**
* OneRoleInfoData permissions.
* @type {Array.<nt_module_user.Permission>|undefined}
*/
permissions?: nt_module_user.Permission[];
/**
* OneRoleInfoData infoItems.
* @type {Array.<nt_module_user.InfoItem>|undefined}
*/
infoItems?: nt_module_user.InfoItem[];
}
/**
* Constructs a new UserService service.
* @exports nt_module_user.UserService
* @interface
*/
export interface UserService {
/**
* Calls Login.
* @param {nt_module_user.LoginRequest} request LoginRequest message or plain object
* @returns {Observable<nt_module_user.LoginResponse>}
*/
login(request: nt_module_user.LoginRequest): Observable<nt_module_user.LoginResponse>;
/**
* Calls Register.
* @param {nt_module_user.RegisterRequest} request RegisterRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
register(request: nt_module_user.RegisterRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls CreateUser.
* @param {nt_module_user.CreateUserRequest} request CreateUserRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
createUser(request: nt_module_user.CreateUserRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls AddUserRole.
* @param {nt_module_user.AddOrDeleteUserRoleRequest} request AddOrDeleteUserRoleRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
addUserRole(request: nt_module_user.AddOrDeleteUserRoleRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeleteUserRole.
* @param {nt_module_user.AddOrDeleteUserRoleRequest} request AddOrDeleteUserRoleRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deleteUserRole(request: nt_module_user.AddOrDeleteUserRoleRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls BanUser.
* @param {nt_module_user.DeleteUserRequest} request DeleteUserRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
banUser(request: nt_module_user.DeleteUserRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls RecycleUser.
* @param {nt_module_user.DeleteUserRequest} request DeleteUserRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
recycleUser(request: nt_module_user.DeleteUserRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeleteRecycledUser.
* @param {nt_module_user.DeleteUserRequest} request DeleteUserRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deleteRecycledUser(request: nt_module_user.DeleteUserRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls RevertBannedUser.
* @param {nt_module_user.DeleteUserRequest} request DeleteUserRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
revertBannedUser(request: nt_module_user.DeleteUserRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls RevertRecycledUser.
* @param {nt_module_user.DeleteUserRequest} request DeleteUserRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
revertRecycledUser(request: nt_module_user.DeleteUserRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls UpdateUserInfoById.
* @param {nt_module_user.UpdateUserInfoByIdRequest} request UpdateUserInfoByIdRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
updateUserInfoById(request: nt_module_user.UpdateUserInfoByIdRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls UpdateCurrentUserInfo.
* @param {nt_module_user.UpdateCurrentUserInfoRequest} request UpdateCurrentUserInfoRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
updateCurrentUserInfo(request: nt_module_user.UpdateCurrentUserInfoRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls FindUserInfoByIds.
* @param {nt_module_user.FindUserInfoByIdsRequest} request FindUserInfoByIdsRequest message or plain object
* @returns {Observable<nt_module_user.FindUserInfoByIdsResponse>}
*/
findUserInfoByIds(request: nt_module_user.FindUserInfoByIdsRequest): Observable<nt_module_user.FindUserInfoByIdsResponse>;
/**
* Calls FindCurrentUserInfo.
* @param {nt_module_user.FindCurrentUserInfoRequest} request FindCurrentUserInfoRequest message or plain object
* @returns {Observable<nt_module_user.FindCurrentUserInfoResponse>}
*/
findCurrentUserInfo(request: nt_module_user.FindCurrentUserInfoRequest): Observable<nt_module_user.FindCurrentUserInfoResponse>;
/**
* Calls FindRegisterUserInputInfo.
* @param {nt_module_user.PlaceholderRequest} request PlaceholderRequest message or plain object
* @returns {Observable<nt_module_user.FindRegisterUserInputInfoResponse>}
*/
findRegisterUserInputInfo(request: nt_module_user.PlaceholderRequest): Observable<nt_module_user.FindRegisterUserInputInfoResponse>;
/**
* Calls FindAllUsers.
* @param {nt_module_user.FindDataByPageRequest} request FindDataByPageRequest message or plain object
* @returns {Observable<nt_module_user.FindAllUsersResponse>}
*/
findAllUsers(request: nt_module_user.FindDataByPageRequest): Observable<nt_module_user.FindAllUsersResponse>;
/**
* Calls FindUsersInRole.
* @param {nt_module_user.FindUsersInRoleRequest} request FindUsersInRoleRequest message or plain object
* @returns {Observable<nt_module_user.FindUsersInRoleResponse>}
*/
findUsersInRole(request: nt_module_user.FindUsersInRoleRequest): Observable<nt_module_user.FindUsersInRoleResponse>;
/**
* Calls FindUsersInOrganization.
* @param {nt_module_user.FindUsersInOrganizationRequest} request FindUsersInOrganizationRequest message or plain object
* @returns {Observable<nt_module_user.FindUsersInOrganizationResponse>}
*/
findUsersInOrganization(request: nt_module_user.FindUsersInOrganizationRequest): Observable<nt_module_user.FindUsersInOrganizationResponse>;
/**
* Calls FindOneWithRolesAndPermissions.
* @param {nt_module_user.FindOneWithRolesAndPermissionsRequest} request FindOneWithRolesAndPermissionsRequest message or plain object
* @returns {Observable<nt_module_user.FindOneWithRolesAndPermissionsResponse>}
*/
findOneWithRolesAndPermissions(request: nt_module_user.FindOneWithRolesAndPermissionsRequest): Observable<nt_module_user.FindOneWithRolesAndPermissionsResponse>;
/**
* Calls AddPermissionToUser.
* @param {nt_module_user.AddOrDeleteUserPermRequest} request AddOrDeleteUserPermRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
addPermissionToUser(request: nt_module_user.AddOrDeleteUserPermRequest): Observable<nt_module_user.StringDataResponse>;
/**
* Calls DeletePermissionOfUser.
* @param {nt_module_user.AddOrDeleteUserPermRequest} request AddOrDeleteUserPermRequest message or plain object
* @returns {Observable<nt_module_user.StringDataResponse>}
*/
deletePermissionOfUser(request: nt_module_user.AddOrDeleteUserPermRequest): Observable<nt_module_user.StringDataResponse>;
}
/**
* Constructs a new LoginRequest.
* @exports nt_module_user.LoginRequest
* @interface
*/
export interface LoginRequest {
/**
* LoginRequest username.
* @type {string|undefined}
*/
username?: string;
/**
* LoginRequest password.
* @type {string|undefined}
*/
password?: string;
}
/**
* Constructs a new LoginResponse.
* @exports nt_module_user.LoginResponse
* @interface
*/
export interface LoginResponse {
/**
* LoginResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* LoginResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* LoginResponse data.
* @type {nt_module_user.LoginResponse.LoginResponseData|undefined}
*/
data?: nt_module_user.LoginResponse.LoginResponseData;
}
export namespace LoginResponse {
/**
* Constructs a new LoginResponseData.
* @exports nt_module_user.LoginResponse.LoginResponseData
* @interface
*/
export interface LoginResponseData {
/**
* LoginResponseData tokenInfo.
* @type {nt_module_user.LoginResponse.TokenInfo|undefined}
*/
tokenInfo?: nt_module_user.LoginResponse.TokenInfo;
/**
* LoginResponseData userInfoData.
* @type {nt_module_user.UserData|undefined}
*/
userInfoData?: nt_module_user.UserData;
}
/**
* Constructs a new TokenInfo.
* @exports nt_module_user.LoginResponse.TokenInfo
* @interface
*/
export interface TokenInfo {
/**
* TokenInfo accessToken.
* @type {string|undefined}
*/
accessToken?: string;
/**
* TokenInfo expiresIn.
* @type {number|undefined}
*/
expiresIn?: number;
}
}
/**
* Constructs a new RegisterRequest.
* @exports nt_module_user.RegisterRequest
* @interface
*/
export interface RegisterRequest {
/**
* RegisterRequest registerUserInput.
* @type {nt_module_user.RegisterRequest.RegisterUserInput|undefined}
*/
registerUserInput?: nt_module_user.RegisterRequest.RegisterUserInput;
}
export namespace RegisterRequest {
/**
* Constructs a new RegisterUserInput.
* @exports nt_module_user.RegisterRequest.RegisterUserInput
* @interface
*/
export interface RegisterUserInput {
/**
* RegisterUserInput username.
* @type {string|undefined}
*/
username?: string;
/**
* RegisterUserInput email.
* @type {string|undefined}
*/
email?: string;
/**
* RegisterUserInput mobile.
* @type {string|undefined}
*/
mobile?: string;
/**
* RegisterUserInput password.
* @type {string|undefined}
*/
password?: string;
/**
* RegisterUserInput infoKVs.
* @type {Array.<nt_module_user.CreateUserInfoInfoKV>|undefined}
*/
infoKVs?: nt_module_user.CreateUserInfoInfoKV[];
}
}
/**
* Constructs a new CreateUserRequest.
* @exports nt_module_user.CreateUserRequest
* @interface
*/
export interface CreateUserRequest {
/**
* CreateUserRequest createUserInput.
* @type {nt_module_user.CreateUserRequest.CreateUserInput|undefined}
*/
createUserInput?: nt_module_user.CreateUserRequest.CreateUserInput;
}
export namespace CreateUserRequest {
/**
* Constructs a new CreateUserInput.
* @exports nt_module_user.CreateUserRequest.CreateUserInput
* @interface
*/
export interface CreateUserInput {
/**
* CreateUserInput username.
* @type {string|undefined}
*/
username?: string;
/**
* CreateUserInput email.
* @type {string|undefined}
*/
email?: string;
/**
* CreateUserInput mobile.
* @type {string|undefined}
*/
mobile?: string;
/**
* CreateUserInput password.
* @type {string|undefined}
*/
password?: string;
/**
* CreateUserInput banned.
* @type {boolean|undefined}
*/
banned?: boolean;
/**
* CreateUserInput infoKVs.
* @type {Array.<nt_module_user.CreateUserInfoInfoKV>|undefined}
*/
infoKVs?: nt_module_user.CreateUserInfoInfoKV[];
/**
* CreateUserInput roleIds.
* @type {Array.<number>|undefined}
*/
roleIds?: number[];
/**
* CreateUserInput organizationIds.
* @type {Array.<number>|undefined}
*/
organizationIds?: number[];
}
}
/**
* Constructs a new CreateUserInfoInfoKV.
* @exports nt_module_user.CreateUserInfoInfoKV
* @interface
*/
export interface CreateUserInfoInfoKV {
/**
* CreateUserInfoInfoKV infoItemId.
* @type {number|undefined}
*/
infoItemId?: number;
/**
* CreateUserInfoInfoKV userInfoValue.
* @type {string|undefined}
*/
userInfoValue?: string;
}
/**
* Constructs a new AddOrDeleteUserRoleRequest.
* @exports nt_module_user.AddOrDeleteUserRoleRequest
* @interface
*/
export interface AddOrDeleteUserRoleRequest {
/**
* AddOrDeleteUserRoleRequest userId.
* @type {number|undefined}
*/
userId?: number;
/**
* AddOrDeleteUserRoleRequest roleId.
* @type {number|undefined}
*/
roleId?: number;
}
/**
* Constructs a new DeleteUserRequest.
* @exports nt_module_user.DeleteUserRequest
* @interface
*/
export interface DeleteUserRequest {
/**
* DeleteUserRequest userId.
* @type {number|undefined}
*/
userId?: number;
}
/**
* Constructs a new UpdateUserInfoByIdRequest.
* @exports nt_module_user.UpdateUserInfoByIdRequest
* @interface
*/
export interface UpdateUserInfoByIdRequest {
/**
* UpdateUserInfoByIdRequest userId.
* @type {number|undefined}
*/
userId?: number;
/**
* UpdateUserInfoByIdRequest updateUserInput.
* @type {nt_module_user.UpdateUserInput|undefined}
*/
updateUserInput?: nt_module_user.UpdateUserInput;
}
/**
* Constructs a new UpdateUserInput.
* @exports nt_module_user.UpdateUserInput
* @interface
*/
export interface UpdateUserInput {
/**
* UpdateUserInput username.
* @type {string|undefined}
*/
username?: string;
/**
* UpdateUserInput email.
* @type {string|undefined}
*/
email?: string;
/**
* UpdateUserInput mobile.
* @type {string|undefined}
*/
mobile?: string;
/**
* UpdateUserInput password.
* @type {string|undefined}
*/
password?: string;
/**
* UpdateUserInput banned.
* @type {boolean|undefined}
*/
banned?: boolean;
/**
* UpdateUserInput recycle.
* @type {boolean|undefined}
*/
recycle?: boolean;
/**
* UpdateUserInput infoKVs.
* @type {Array.<nt_module_user.UpdateUserInfoKV>|undefined}
*/
infoKVs?: nt_module_user.UpdateUserInfoKV[];
/**
* UpdateUserInput roleIds.
* @type {Array.<nt_module_user.UpdateUserInput.ChangedUserRoleOrOrganization>|undefined}
*/
roleIds?: nt_module_user.UpdateUserInput.ChangedUserRoleOrOrganization[];
/**
* UpdateUserInput organizationIds.
* @type {Array.<nt_module_user.UpdateUserInput.ChangedUserRoleOrOrganization>|undefined}
*/
organizationIds?: nt_module_user.UpdateUserInput.ChangedUserRoleOrOrganization[];
}
export namespace UpdateUserInput {
/**
* Constructs a new ChangedUserRoleOrOrganization.
* @exports nt_module_user.UpdateUserInput.ChangedUserRoleOrOrganization
* @interface
*/
export interface ChangedUserRoleOrOrganization {
/**
* ChangedUserRoleOrOrganization before.
* @type {number|undefined}
*/
before?: number;
/**
* ChangedUserRoleOrOrganization after.
* @type {number|undefined}
*/
after?: number;
}
}
/**
* Constructs a new UpdateUserInfoKV.
* @exports nt_module_user.UpdateUserInfoKV
* @interface
*/
export interface UpdateUserInfoKV {
/**
* UpdateUserInfoKV userInfoId.
* @type {number|undefined}
*/
userInfoId?: number;
/**
* UpdateUserInfoKV userInfoValue.
* @type {string|undefined}
*/
userInfoValue?: string;
/**
* UpdateUserInfoKV infoItemId.
* @type {number|undefined}
*/
infoItemId?: number;
}
/**
* Constructs a new UpdateCurrentUserInfoRequest.
* @exports nt_module_user.UpdateCurrentUserInfoRequest
* @interface
*/
export interface UpdateCurrentUserInfoRequest {
/**
* UpdateCurrentUserInfoRequest userId.
* @type {number|undefined}
*/
userId?: number;
/**
* UpdateCurrentUserInfoRequest updateCurrentUserInput.
* @type {nt_module_user.UpdateCurrentUserInput|undefined}
*/
updateCurrentUserInput?: nt_module_user.UpdateCurrentUserInput;
}
/**
* Constructs a new UpdateCurrentUserInput.
* @exports nt_module_user.UpdateCurrentUserInput
* @interface
*/
export interface UpdateCurrentUserInput {
/**
* UpdateCurrentUserInput username.
* @type {string|undefined}
*/
username?: string;
/**
* UpdateCurrentUserInput email.
* @type {string|undefined}
*/
email?: string;
/**
* UpdateCurrentUserInput mobile.
* @type {string|undefined}
*/
mobile?: string;
/**
* UpdateCurrentUserInput password.
* @type {string|undefined}
*/
password?: string;
/**
* UpdateCurrentUserInput infoKVs.
* @type {Array.<nt_module_user.UpdateUserInfoKV>|undefined}
*/
infoKVs?: nt_module_user.UpdateUserInfoKV[];
}
/**
* Constructs a new FindUserInfoByIdsRequest.
* @exports nt_module_user.FindUserInfoByIdsRequest
* @interface
*/
export interface FindUserInfoByIdsRequest {
/**
* FindUserInfoByIdsRequest userIds.
* @type {Array.<number>|undefined}
*/
userIds?: number[];
}
/**
* Constructs a new FindUserInfoByIdsResponse.
* @exports nt_module_user.FindUserInfoByIdsResponse
* @interface
*/
export interface FindUserInfoByIdsResponse {
/**
* FindUserInfoByIdsResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindUserInfoByIdsResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindUserInfoByIdsResponse data.
* @type {Array.<nt_module_user.UserData>|undefined}
*/
data?: nt_module_user.UserData[];
}
/**
* Constructs a new UserData.
* @exports nt_module_user.UserData
* @interface
*/
export interface UserData {
/**
* UserData id.
* @type {number|undefined}
*/
id?: number;
/**
* UserData username.
* @type {string|undefined}
*/
username?: string;
/**
* UserData email.
* @type {string|undefined}
*/
email?: string;
/**
* UserData mobile.
* @type {string|undefined}
*/
mobile?: string;
/**
* UserData banned.
* @type {boolean|undefined}
*/
banned?: boolean;
/**
* UserData recycle.
* @type {boolean|undefined}
*/
recycle?: boolean;
/**
* UserData createdAt.
* @type {string|undefined}
*/
createdAt?: string;
/**
* UserData updatedAt.
* @type {string|undefined}
*/
updatedAt?: string;
/**
* UserData userRoles.
* @type {Array.<nt_module_user.UserRoleData>|undefined}
*/
userRoles?: nt_module_user.UserRoleData[];
/**
* UserData userOrganizations.
* @type {Array.<nt_module_user.UserOrganizationData>|undefined}
*/
userOrganizations?: nt_module_user.UserOrganizationData[];
/**
* UserData userInfos.
* @type {Array.<nt_module_user.UserInfoData>|undefined}
*/
userInfos?: nt_module_user.UserInfoData[];
}
/**
* Constructs a new UserRoleData.
* @exports nt_module_user.UserRoleData
* @interface
*/
export interface UserRoleData {
/**
* UserRoleData id.
* @type {number|undefined}
*/
id?: number;
/**
* UserRoleData name.
* @type {string|undefined}
*/
name?: string;
}
/**
* Constructs a new UserOrganizationData.
* @exports nt_module_user.UserOrganizationData
* @interface
*/
export interface UserOrganizationData {
/**
* UserOrganizationData id.
* @type {number|undefined}
*/
id?: number;
/**
* UserOrganizationData name.
* @type {string|undefined}
*/
name?: string;
}
/**
* Constructs a new UserInfoData.
* @exports nt_module_user.UserInfoData
* @interface
*/
export interface UserInfoData {
/**
* UserInfoData id.
* @type {number|undefined}
*/
id?: number;
/**
* UserInfoData order.
* @type {number|undefined}
*/
order?: number;
/**
* UserInfoData infoItemId.
* @type {number|undefined}
*/
infoItemId?: number;
/**
* UserInfoData type.
* @type {string|undefined}
*/
type?: string;
/**
* UserInfoData name.
* @type {string|undefined}
*/
name?: string;
/**
* UserInfoData value.
* @type {string|undefined}
*/
value?: string;
/**
* UserInfoData description.
* @type {string|undefined}
*/
description?: string;
/**
* UserInfoData registerDisplay.
* @type {boolean|undefined}
*/
registerDisplay?: boolean;
/**
* UserInfoData informationDisplay.
* @type {boolean|undefined}
*/
informationDisplay?: boolean;
}
/**
* Constructs a new FindCurrentUserInfoRequest.
* @exports nt_module_user.FindCurrentUserInfoRequest
* @interface
*/
export interface FindCurrentUserInfoRequest {
/**
* FindCurrentUserInfoRequest userId.
* @type {number|undefined}
*/
userId?: number;
}
/**
* Constructs a new FindCurrentUserInfoResponse.
* @exports nt_module_user.FindCurrentUserInfoResponse
* @interface
*/
export interface FindCurrentUserInfoResponse {
/**
* FindCurrentUserInfoResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindCurrentUserInfoResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindCurrentUserInfoResponse data.
* @type {nt_module_user.UserData|undefined}
*/
data?: nt_module_user.UserData;
}
/**
* Constructs a new FindRegisterUserInputInfoResponse.
* @exports nt_module_user.FindRegisterUserInputInfoResponse
* @interface
*/
export interface FindRegisterUserInputInfoResponse {
/**
* FindRegisterUserInputInfoResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindRegisterUserInputInfoResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindRegisterUserInputInfoResponse data.
* @type {Array.<nt_module_user.InfoItem>|undefined}
*/
data?: nt_module_user.InfoItem[];
}
/**
* Constructs a new FindAllUsersResponse.
* @exports nt_module_user.FindAllUsersResponse
* @interface
*/
export interface FindAllUsersResponse {
/**
* FindAllUsersResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindAllUsersResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindAllUsersResponse data.
* @type {Array.<nt_module_user.UserData>|undefined}
*/
data?: nt_module_user.UserData[];
/**
* FindAllUsersResponse count.
* @type {number|undefined}
*/
count?: number;
}
/**
* Constructs a new FindUsersInRoleRequest.
* @exports nt_module_user.FindUsersInRoleRequest
* @interface
*/
export interface FindUsersInRoleRequest {
/**
* FindUsersInRoleRequest roleId.
* @type {number|undefined}
*/
roleId?: number;
/**
* FindUsersInRoleRequest pageNumber.
* @type {number|undefined}
*/
pageNumber?: number;
/**
* FindUsersInRoleRequest pageSize.
* @type {number|undefined}
*/
pageSize?: number;
}
/**
* Constructs a new FindUsersInRoleResponse.
* @exports nt_module_user.FindUsersInRoleResponse
* @interface
*/
export interface FindUsersInRoleResponse {
/**
* FindUsersInRoleResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindUsersInRoleResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindUsersInRoleResponse data.
* @type {Array.<nt_module_user.UserData>|undefined}
*/
data?: nt_module_user.UserData[];
/**
* FindUsersInRoleResponse count.
* @type {number|undefined}
*/
count?: number;
}
/**
* Constructs a new FindUsersInOrganizationRequest.
* @exports nt_module_user.FindUsersInOrganizationRequest
* @interface
*/
export interface FindUsersInOrganizationRequest {
/**
* FindUsersInOrganizationRequest organizationId.
* @type {number|undefined}
*/
organizationId?: number;
/**
* FindUsersInOrganizationRequest pageNumber.
* @type {number|undefined}
*/
pageNumber?: number;
/**
* FindUsersInOrganizationRequest pageSize.
* @type {number|undefined}
*/
pageSize?: number;
}
/**
* Constructs a new FindUsersInOrganizationResponse.
* @exports nt_module_user.FindUsersInOrganizationResponse
* @interface
*/
export interface FindUsersInOrganizationResponse {
/**
* FindUsersInOrganizationResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindUsersInOrganizationResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindUsersInOrganizationResponse data.
* @type {Array.<nt_module_user.UserData>|undefined}
*/
data?: nt_module_user.UserData[];
/**
* FindUsersInOrganizationResponse count.
* @type {number|undefined}
*/
count?: number;
}
/**
* Constructs a new FindOneWithRolesAndPermissionsRequest.
* @exports nt_module_user.FindOneWithRolesAndPermissionsRequest
* @interface
*/
export interface FindOneWithRolesAndPermissionsRequest {
/**
* FindOneWithRolesAndPermissionsRequest username.
* @type {string|undefined}
*/
username?: string;
}
/**
* Constructs a new FindOneWithRolesAndPermissionsResponse.
* @exports nt_module_user.FindOneWithRolesAndPermissionsResponse
* @interface
*/
export interface FindOneWithRolesAndPermissionsResponse {
/**
* FindOneWithRolesAndPermissionsResponse code.
* @type {number|undefined}
*/
code?: number;
/**
* FindOneWithRolesAndPermissionsResponse message.
* @type {string|undefined}
*/
message?: string;
/**
* FindOneWithRolesAndPermissionsResponse data.
* @type {nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData|undefined}
*/
data?: nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData;
}
export namespace FindOneWithRolesAndPermissionsResponse {
/**
* Constructs a new UserRoleAndPermissionData.
* @exports nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData
* @interface
*/
export interface UserRoleAndPermissionData {
/**
* UserRoleAndPermissionData id.
* @type {number|undefined}
*/
id?: number;
/**
* UserRoleAndPermissionData username.
* @type {string|undefined}
*/
username?: string;
/**
* UserRoleAndPermissionData email.
* @type {string|undefined}
*/
email?: string;
/**
* UserRoleAndPermissionData mobile.
* @type {string|undefined}
*/
mobile?: string;
/**
* UserRoleAndPermissionData banned.
* @type {boolean|undefined}
*/
banned?: boolean;
/**
* UserRoleAndPermissionData recycle.
* @type {boolean|undefined}
*/
recycle?: boolean;
/**
* UserRoleAndPermissionData createdAt.
* @type {string|undefined}
*/
createdAt?: string;
/**
* UserRoleAndPermissionData updatedAt.
* @type {string|undefined}
*/
updatedAt?: string;
/**
* UserRoleAndPermissionData roles.
* @type {Array.<nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData.UserRole>|undefined}
*/
roles?: nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData.UserRole[];
/**
* UserRoleAndPermissionData personalPermissions.
* @type {Array.<nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData.PersonalPermission>|undefined}
*/
personalPermissions?: nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData.PersonalPermission[];
}
export namespace UserRoleAndPermissionData {
/**
* Constructs a new UserRole.
* @exports nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData.UserRole
* @interface
*/
export interface UserRole {
/**
* UserRole id.
* @type {number|undefined}
*/
id?: number;
/**
* UserRole name.
* @type {string|undefined}
*/
name?: string;
/**
* UserRole permissions.
* @type {Array.<nt_module_user.Permission>|undefined}
*/
permissions?: nt_module_user.Permission[];
}
/**
* Constructs a new PersonalPermission.
* @exports nt_module_user.FindOneWithRolesAndPermissionsResponse.UserRoleAndPermissionData.PersonalPermission
* @interface
*/
export interface PersonalPermission {
/**
* PersonalPermission id.
* @type {number|undefined}
*/
id?: number;
/**
* PersonalPermission status.
* @type {string|undefined}
*/
status?: string;
/**
* PersonalPermission permission.
* @type {nt_module_user.Permission|undefined}
*/
permission?: nt_module_user.Permission;
}
}
}
/**
* Constructs a new AddOrDeleteUserPermRequest.
* @exports nt_module_user.AddOrDeleteUserPermRequest
* @interface
*/
export interface AddOrDeleteUserPermRequest {
/**
* AddOrDeleteUserPermRequest userId.
* @type {number|undefined}
*/
userId?: number;
/**
* AddOrDeleteUserPermRequest permissionId.
* @type {number|undefined}
*/
permissionId?: number;
}
}
/**
* Namespace notadd_rpc_demo.
* @exports notadd_rpc_demo
* @namespace
*/
export namespace notadd_rpc_demo {
/**
* Contains all the RPC service clients.
* @exports notadd_rpc_demo.ClientFactory
* @interface
*/
export interface ClientFactory {
/**
* Returns the RootService service client.
* @returns {notadd_rpc_demo.RootService}
*/
getRootService(): notadd_rpc_demo.RootService;
}
/**
* Builder for an RPC service server.
* @exports notadd_rpc_demo.ServerBuilder
* @interface
*/
export interface ServerBuilder {
/**
* Adds a RootService service implementation.
* @param {notadd_rpc_demo.RootService} impl RootService service implementation
* @returns {notadd_rpc_demo.ServerBuilder}
*/
addRootService(impl: notadd_rpc_demo.RootService): notadd_rpc_demo.ServerBuilder;
}
/**
* Constructs a new RootService service.
* @exports notadd_rpc_demo.RootService
* @interface
*/
export interface RootService {
/**
* Calls SayHello.
* @param {notadd_rpc_demo.SayHelloRequest} request SayHelloRequest message or plain object
* @returns {Observable<notadd_rpc_demo.SayHelloResponse>}
*/
sayHello(request: notadd_rpc_demo.SayHelloRequest): Observable<notadd_rpc_demo.SayHelloResponse>;
}
/**
* Constructs a new SayHelloRequest.
* @exports notadd_rpc_demo.SayHelloRequest
* @interface
*/
export interface SayHelloRequest {
/**
* SayHelloRequest name.
* @type {string|undefined}
*/
name?: string;
}
/**
* Constructs a new SayHelloResponse.
* @exports notadd_rpc_demo.SayHelloResponse
* @interface
*/
export interface SayHelloResponse {
/**
* SayHelloResponse msg.
* @type {string|undefined}
*/
msg?: string;
}
} | the_stack |
declare const chrome: any;
declare const setTimeout: any;
declare const require: any;
declare const fetch: any;
declare const btoa: any, atob: any;
declare const console: any;
declare const self: any;
declare const localStorage: any;
declare const URL: any;
const thenChrome = require("then-chrome");
var Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output =
output +
this._keyStr.charAt(enc1) +
this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) +
this._keyStr.charAt(enc4);
} // Whend
return output;
}, // End Function encode
// public method for decoding
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
} // Whend
output = Base64._utf8_decode(output);
return output;
}, // End Function decode
// private method for UTF-8 encoding
_utf8_encode: function (string) {
var utftext = "";
string = string.replace(/\r\n/g, "\n");
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if (c > 127 && c < 2048) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
} // Next n
return utftext;
}, // End Function _utf8_encode
// private method for UTF-8 decoding
_utf8_decode: function (utftext) {
var string = "";
var i = 0;
var c, c1, c2, c3;
c = c1 = c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if (c > 191 && c < 224) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(
((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
);
i += 3;
}
} // Whend
return string;
}, // End Function _utf8_decode
};
async function getBackendPort() {
function doGetBackendPort() {
return new Promise(async (resolve) => {
chrome.storage.sync.get(["backendPort"], function (result) {
let bePort = result.backendPort;
resolve(bePort);
});
});
}
let bePort = await doGetBackendPort();
if (!bePort) {
console.log("BE port not set, will wait 2s and try again");
await new Promise((resolve) => setTimeout(resolve, 2000));
}
if (!bePort) {
throw Error("BE port not found");
}
bePort = parseFloat(bePort as string);
return bePort;
}
function setBackendPort(backendPort) {
return new Promise((resolve) => {
console.log("setBackendPort", backendPort);
chrome.storage.sync.set({ backendPort }, function () {
resolve();
});
});
}
// const backendPort = 12100;
// const backendPort = 7000;
class TTab {
target: any;
tab: any;
cookiesBefore: any;
detached = false;
hasReceivedRequestInterceptedEvent = false;
constructor() {
this.onDetach = this.onDetach.bind(this);
this.onEvent = this.onEvent.bind(this);
}
async open(tab, pageUrl = "") {
this.tab = tab;
const backendPort = await getBackendPort();
if (!pageUrl) {
pageUrl = "http://localhost:" + backendPort + "/start/";
}
// navigate away first because we can't enable debugger while on chrome url
await thenChrome.tabs.update(tab.id, {
url: "http://localhost:" + backendPort + "/enableDebugger",
});
// wait for navigation away from chrome url
await new Promise((resolve) => setTimeout(resolve, 250));
const targets = await thenChrome.debugger.getTargets();
const target = targets.find((t) => t.type === "page" && t.tabId === tab.id);
this.target = target;
// const pageUrl =
// "http://localhost:1212/persistent-friendly-authority.glitch.me_2020-03-25_10-04-28.report.html";
// const pageUrl = "https://capable-ogre.glitch.me/";
// await thenChrome.tabs.update(tab.id, { url: pageUrl });
await this._setupDebugger();
console.log("Done set up debugger");
await thenChrome.debugger.sendCommand(this._getTargetArg(), "Page.enable");
await this._setupRequestInterception();
await thenChrome.tabs.update(tab.id, { url: pageUrl });
this.log("Will open", pageUrl);
}
_getTargetArg() {
return { targetId: this.target.id };
}
log(...args) {
console.log.apply(console, [
"[Tab: " + (this.tab && this.tab.id) + "]",
...args,
]);
}
onDetach = (source, reason) => {
this.detached = true;
if (source.targetId === this.target.id) {
this.log("Detached", { source, reason });
chrome.debugger.onDetach.removeListener(this.onDetach);
chrome.debugger.onEvent.removeListener(this.onEvent);
// this.onExit();
}
};
onEvent = (target, type, info) => {
// this.log("On Event", type, info);
if (target.targetId !== this.target.id) {
// Not sure why this happens
return;
}
if (type === "Network.requestIntercepted") {
this._handleInterceptedRequest(info);
this.hasReceivedRequestInterceptedEvent = true;
}
if (
!this.hasReceivedRequestInterceptedEvent &&
type === "Network.responseReceived"
) {
// Something is wrong and a non-intercepted response was sent
// This should not happen, but it does sometimes (in new Chrome profile? older versions?)
console.log("resposne received", info);
chrome.debugger.detach(this._getTargetArg());
chrome.tabs.update(this.tab.id, {
url: "http://example.com/?interceptFailed",
});
}
};
async _setupDebugger() {
return new Promise(async (resolve) => {
const targetArg = this._getTargetArg();
chrome.debugger.onDetach.addListener(this.onDetach);
await thenChrome.debugger.attach(targetArg, "1.3");
resolve();
});
}
async _setupRequestInterception() {
await thenChrome.debugger.sendCommand(
this._getTargetArg(),
"Network.enable"
);
await thenChrome.debugger.sendCommand(
this._getTargetArg(),
"Network.setRequestInterception",
{ patterns: [{ urlPattern: "*", interceptionStage: "Request" }] }
);
chrome.debugger.onEvent.addListener(this.onEvent);
}
async _handleInterceptedRequest(info) {
this.log("Request intercepted", info.request.url);
const interceptionId = info.interceptionId;
const targetArg = this._getTargetArg();
const backendPort = await getBackendPort();
console.log(info.request.url, backendPort);
if (
info.request.url === "about:blank" ||
info.request.url.startsWith("chrome-extension://") ||
info.request.url.includes("/storeLogs") ||
info.request.url.includes("favicon.ico") ||
// backend alrady knows not to instrument this,
// but this avoids the extra interception work
(info.request.url.includes(":" + backendPort) &&
!info.request.url.includes("/start") &&
// I don't really get this, but there's an empty.js
// file that needs to be loaded to do the html mapping in some cases
!info.request.url.includes("/fromJSInternal"))
) {
console.log("bypassing proxy", info.request.url);
chrome.debugger.sendCommand(
targetArg,
"Network.continueInterceptedRequest",
{
interceptionId,
}
);
return;
}
let rr;
const reqInfo = {
url: info.request.url,
method: info.request.method,
headers: info.request.headers,
postData: info.request.postData,
};
const res = await fetch(
"http://localhost:" + (await getBackendPort()) + "/makeProxyRequest",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(reqInfo),
}
)
.then((r) => {
rr = r;
return r.text();
})
.catch((err) => {
console.log("Error making request", reqInfo);
throw err;
});
let responseText = `HTTP/1.1 ${rr.status}
${Array.from(rr.headers)
.map(([headerKey, headerValue]) => {
return `${headerKey}: ${headerValue}`;
})
.join("\n")}
${res}`;
chrome.debugger.sendCommand(
targetArg,
"Network.continueInterceptedRequest",
{
interceptionId,
// use this instead of btoa to avoid https://stackoverflow.com/questions/23223718/failed-to-execute-btoa-on-window-the-string-to-be-encoded-contains-characte
rawResponse: Base64.encode(responseText),
}
);
}
}
// setTimeout(() => {
// chrome.tabs.create({ url: "https://example.com" }, tab => {
// // const tt = new TTab();
// // tt.open(tab);
// });
// }, 100);
let initInterval = setInterval(() => {
console.log("checking for init page");
chrome.tabs.query({ title: "fromJSInitPage" }, async (tabs) => {
if (tabs.length > 0) {
console.log("found init page");
clearInterval(initInterval);
let url = new URL(tabs[0].url);
let config = JSON.parse(url.searchParams.get("config"));
await setBackendPort(config.backendPort);
console.log("used config", config);
const tt = new TTab();
tt.open(tabs[0], config.redirectUrl);
}
});
}, 100);
// chrome.browserAction.onClicked.addListener(function (tab) {
// const tt = new TTab();
// tt.open(tab);
// });
chrome.tabs.onCreated.addListener((tab) => {
console.log("oncreated", tab);
const tt = new TTab();
tt.open(tab);
}); | the_stack |
import ProgressBar from '../../vue/component/ProgressBar.vue'
import TabSmall from '../../vue/component/TabSmall.vue'
import InputText from '../../vue/component/InputText.vue'
// import { MasterData } from '../main/on-master-read'
import { Vue, Component } from 'vue-property-decorator'
import type { DownloadPromise, ProgressInfo } from 'mishiro-core'
import { unpackTexture2D } from './unpack-texture-2d'
import getPath from '../common/get-path'
import configurer from './config'
import { getCardHash } from './ipc-back'
import type { MishiroConfig } from '../main/config'
import { error } from './log'
const { /* ipcRenderer, */shell } = window.node.electron
const fs = window.node.fs
const path = window.node.path
const { cardDir, voiceDir } = getPath
@Component({
components: {
ProgressBar,
TabSmall,
InputText
}
})
export default class extends Vue {
dler = new this.core.Downloader()
cardDownloadPromise: DownloadPromise<string> | null = null
voice: HTMLAudioElement = new Audio()
voiceDisable: boolean = false
queryString: string = ''
searchResult: any[] = []
activeCard: any = {}
activeCardPlus: any = {}
information: any = {}
imgProgress: number = 0
eventCard: any[] = []
currentPractice: string = 'idol.after'
practice: { before: string, after: string } = {
before: 'idol.before',
after: 'idol.after'
}
created (): void {
this.dler.setProxy(configurer.get('proxy') ?? '')
this.event.$on('optionSaved', (options: MishiroConfig) => {
this.dler.setProxy(options.proxy ?? '')
})
}
// @Prop({ default: () => ({}), type: Object }) master!: MasterData
blood (v: any): string {
switch (v) {
case 2001:
return 'A'
case 2002:
return 'B'
case 2003:
return 'AB'
case 2004:
return 'O'
default:
return ''
}
}
hand (v: any): string {
switch (v) {
case 3001:
return '右'
case 3002:
return '左'
case 3003:
return '両'
default:
return ''
}
}
threesize (v: any): string {
if (!v) return ''
if (v[0] === undefined || v[1] === undefined || v[2] === undefined) {
return ''
} else if (v[0] >= 1000 && v[1] >= 1000 && v[2] >= 1000) {
return '?/?/?'
} else {
return `${v[0]}/${v[1]}/${v[2]}`
}
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
get table () {
return [
[
{ text: this.$t('idol.id') },
{ text: this.information.id },
{ text: this.$t('idol.okurigana') },
{ text: this.information.charaData && this.information.charaData.name_kana }
],
[
{ text: this.$t('idol.card_name') },
{ text: this.information.name },
{ text: this.$t('idol.name') },
{ text: this.information.charaData && this.information.charaData.name }
],
[
{ text: this.$t('idol.chara_id') },
{ text: this.information.chara_id },
{ text: this.$t('idol.age') },
{ text: this.information.charaData && this.information.charaData.age }
],
[
{ text: this.$t('idol.rarity') },
{ text: this.rarity },
{ text: this.$t('idol.height') },
{ text: this.information.charaData && this.information.charaData.height }
],
[
{ text: this.$t('idol.hp'), class: 'hp' },
{ text: this.hp, class: 'hp' },
{ text: this.$t('idol.weight') },
{ text: this.information.charaData && this.information.charaData.weight }
],
[
{ text: this.$t('idol.vocal'), class: 'vocal' },
{ text: this.vocal, class: 'vocal' },
{ text: this.$t('idol.birth') },
{ text: this.information.charaData && (`${this.information.charaData.birth_month}月${this.information.charaData.birth_day}日`) }
],
[
{ text: this.$t('idol.dance'), class: 'dance' },
{ text: this.dance, class: 'dance' },
{ text: this.$t('idol.blood') },
{ text: this.blood(this.information.charaData && this.information.charaData.blood_type) }
],
[
{ text: this.$t('idol.visual'), class: 'visual' },
{ text: this.visual, class: 'visual' },
{ text: this.$t('idol.handedness') },
{ text: this.hand(this.information.charaData && this.information.charaData.hand) }
],
[
{ text: this.$t('idol.solo_live') },
{ text: this.solo },
{ text: this.$t('idol.threesize') },
{ text: this.threesize(this.information.charaData && [this.information.charaData.body_size_1, this.information.charaData.body_size_2, this.information.charaData.body_size_3]) }
],
[
{ text: this.$t('idol.skill_name') },
{ text: this.information.skill && this.information.skill.skill_name },
{ text: this.$t('idol.hometown') },
{ text: this.information.charaData && this.information.charaData.hometown }
],
[
{ text: this.information.skill && this.information.skill.explain, colspan: '2', class: 'text-left' },
{ text: this.$t('idol.constellation'), width: '15%' },
{ text: this.information.charaData && this.information.charaData.seiza }
],
[
{ text: this.$t('idol.leader_skill_name') },
{ text: this.information.leaderSkill && this.information.leaderSkill.name },
{ text: this.$t('idol.voice') },
{ text: (this.information.charaData && this.information.charaData.voice) || this.$t('idol.nashi') }
],
[
{ text: this.information.leaderSkill && this.information.leaderSkill.explain, colspan: '2', class: 'text-left' },
{ text: this.$t('idol.favorite'), width: '15%' },
{ text: this.information.charaData && this.information.charaData.favorite }
]
]
}
get cardData (): any[] {
return this.$store.state.master.cardData || []
}
get voiceManifest (): any[] {
return this.$store.state.master.voiceManifest || []
}
get rarity (): string {
switch (this.information.rarity) {
case 1:
return 'N'
case 2:
return 'N+'
case 3:
return 'R'
case 4:
return 'R+'
case 5:
return 'SR'
case 6:
return 'SR+'
case 7:
return 'SSR'
case 8:
return 'SSR+'
default:
return ''
}
}
get hp (): string {
if (this.information.hp_min && this.information.hp_max && this.information.bonus_hp) {
return `${this.information.hp_min}~${this.information.hp_max} (+${this.information.bonus_hp})`
} else {
return ''
}
}
get vocal (): string {
if (this.information.vocal_min && this.information.vocal_max && this.information.bonus_vocal) {
return `${this.information.vocal_min}~${this.information.vocal_max} (+${this.information.bonus_vocal})`
} else {
return ''
}
}
get dance (): string {
if (this.information.dance_min && this.information.dance_max && this.information.bonus_dance) {
return `${this.information.dance_min}~${this.information.dance_max} (+${this.information.bonus_dance})`
} else {
return ''
}
}
get visual (): string {
if (this.information.visual_min && this.information.visual_max && this.information.bonus_visual) {
return `${this.information.visual_min}~${this.information.visual_max} (+${this.information.bonus_visual})`
} else {
return ''
}
}
get solo (): string {
if (this.information.solo_live !== undefined) {
if (Number(this.information.solo_live) === 0) {
return this.$t('idol.nashi') as string
} else {
return 'お願い!シンデレラ'
}
} else {
return ''
}
}
query (): void {
this.searchResult.length = 0
this.playSe(this.enterSe)
if (this.queryString) {
for (let i = 0; i < this.cardData.length; i++) {
const card = this.cardData[i]
if (card.name.indexOf('+') !== card.name.length - 1) {
const re = new RegExp(this.queryString)
if (re.test(card.name)) {
this.searchResult.push(this.cardData[i])
continue
}
if (re.test(card.charaData.name_kana)) {
this.searchResult.push(this.cardData[i])
continue
}
if (re.test(card.chara_id)) {
this.searchResult.push(this.cardData[i])
continue
}
if (re.test(card.id)) {
this.searchResult.push(this.cardData[i])
continue
}
}
}
} else {
this.searchResult = this.cardData.filter(card => {
return this.eventCard.includes(Number(card.id))
})
}
}
selectedIdol (card: any): void {
if (Number(this.activeCard.id) !== Number(card.id)) {
this.playSe(this.enterSe)
this.activeCard = card
this.information = card
for (let i = 0; i < this.cardData.length; i++) {
if (Number(this.cardData[i].id) === Number(card.id) + 1) {
this.activeCardPlus = this.cardData[i]
break
}
}
this.currentPractice = 'idol.before'
if (navigator.onLine) {
this.changeBackground(card).catch(err => {
console.error(err)
error(`IDOL changeBackground: ${err.stack}`)
})
}
}
}
async changeBackground (card: any): Promise<void> {
this.imgProgress = 0
this.cardDownloadPromise?.download.abort()
if (Number(card.rarity) > 4) {
if (!fs.existsSync(cardDir(`bg_${card.id}.png`))) {
try {
const result = await this.downloadCard(card.id, 'idolSelect')
if (result/* && result !== 'await ipc' */) {
this.imgProgress = 0
this.event.$emit('idolSelect', card.id)
}
} catch (errorPath) {
this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string))
throw errorPath
}
} else {
this.event.$emit('idolSelect', card.id)
}
} else {
this.event.$emit('noBg')
}
}
async downloadVoice (): Promise<void> {
this.playSe(this.enterSe)
if (this.activeCard.charaData.voice) {
let charaDl = null
let cardDl = null
const id = this.currentPractice === 'idol.after' ? this.activeCardPlus.id : this.activeCard.id
const cid = this.activeCard.chara_id
const cardVoice = this.voiceManifest.filter(row => row.name === `v/card_${id}.acb`)
const charaVoice = this.voiceManifest.filter(row => row.name === `v/chara_${cid}.acb`)
const cardDir = voiceDir(`card_${id}`)
const charaDir = voiceDir(`chara_${cid}`)
const cardExist = fs.existsSync(cardDir)
const charaExist = fs.existsSync(charaDir)
if (!charaExist) {
fs.mkdirsSync(charaDir)
const hash = charaVoice[0].hash
try {
this.voiceDisable = true
// charaDl = await this.dler.downloadOne(
// this.getVoiceUrl(hash),
// voiceDir(`chara_${cid}`, `chara_${cid}.acb`),
// prog => { this.imgProgress = prog.loading / 4 }
// )
charaDl = await this.dler.downloadSound(
'v',
hash,
voiceDir(`chara_${cid}`, `chara_${cid}.acb`),
prog => { this.imgProgress = prog.loading / 4 }
)
this.imgProgress = 25
} catch (errorPath) {
fs.removeSync(charaDir)
this.voiceDisable = false
this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string))
return
}
}
if (!cardExist) {
fs.mkdirsSync(cardDir)
const hash = cardVoice[0].hash
try {
// cardDl = await this.dler.downloadOne(
// this.getVoiceUrl(hash),
// voiceDir(`card_${id}`, `card_${id}.acb`),
// prog => { this.imgProgress = prog.loading / 4 + 25 }
// )
cardDl = await this.dler.downloadSound(
'v',
hash,
voiceDir(`card_${id}`, `card_${id}.acb`),
prog => { this.imgProgress = 25 + prog.loading / 4 }
)
// if (cardDl) {
this.imgProgress = 50
// }
} catch (errorPath) {
fs.removeSync(cardDir)
this.voiceDisable = false
this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string))
return
}
}
if (charaDl && cardDl) {
await this.voiceDecode([charaDl, cardDl])
} else if (!charaDl && cardDl) {
await this.voiceDecode([cardDl])
} else if (charaDl && !cardDl) {
await this.voiceDecode([charaDl])
} else {
if (charaDl === null && cardDl === null) {
const cardVoiceFiles = fs.readdirSync(cardDir)
for (let i = 0; i < cardVoiceFiles.length; i++) {
cardVoiceFiles[i] = path.join(cardDir, cardVoiceFiles[i])
}
const charaVoiceFiles = fs.readdirSync(charaDir)
for (let i = 0; i < charaVoiceFiles.length; i++) {
charaVoiceFiles[i] = path.join(charaDir, charaVoiceFiles[i])
}
const voiceFiles = charaVoiceFiles.concat(cardVoiceFiles)
const localSource = voiceFiles[Math.floor(voiceFiles.length * Math.random())]
this.voice.src = process.env.NODE_ENV === 'production' ? localSource : ('/' + path.relative(getPath('..'), localSource).replace(new RegExp('\\' + path.sep, 'g'), '/'))
this.voice.play().catch(err => {
console.error(err)
error(`IDOL voice play: ${err.stack}`)
})
}
}
} else {
this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('idol.noVoice'))
}
}
async voiceDecode (acbs: string[]): Promise<void> {
let hcaFiles: string[] = []
const hcaDirs: string[] = []
for (let i = 0; i < acbs.length; i++) {
const acb = acbs[i]
const files = await this.core.audio.acb2hca(acb)
hcaDirs.push(files.dirname || path.dirname(files[0]))
hcaFiles = [...hcaFiles, ...files]
}
for (let i = 0; i < hcaFiles.length; i++) {
await this.core.audio.hca2mp3(hcaFiles[i], path.join(path.dirname(hcaFiles[i]), '..', path.parse(hcaFiles[i]).name + '.mp3'))
this.imgProgress = 50 + 50 * (i + 1) / hcaFiles.length
}
Promise.all([Promise.all(acbs.map(acb => fs.remove(acb))), Promise.all(hcaDirs.map(hcaDir => fs.remove(hcaDir)))]).then(() => {
this.imgProgress = 0
this.voiceDisable = false
}).catch(err => {
console.error(err)
error(`IDOL voiceDecode: ${err.stack}`)
})
}
async downloadCard (id: number | string, _data?: any, progressing?: (prog: ProgressInfo) => void): Promise<string> {
let downloadResult: string = ''
if (!fs.existsSync(cardDir(`bg_${id}.png`))) {
const card = configurer.get('card')
try {
if (!card || card === 'default') {
// let hash: string = ipcRenderer.sendSync('searchManifest', `card_bg_${id}.unity3d`)[0].hash
const hash = await getCardHash(id)
this.cardDownloadPromise = this.dler.downloadAsset(
hash,
cardDir(`card_bg_${id}`),
(progressing || (prog => { this.imgProgress = prog.loading }))
)
downloadResult = await this.cardDownloadPromise
this.cardDownloadPromise = null
if (downloadResult) {
this.imgProgress = 99.99
fs.removeSync(cardDir(`card_bg_${id}`))
await unpackTexture2D(cardDir(`card_bg_${id}.unity3d`))
return cardDir(`bg_${id}.png`)
} else {
// throw new Error('abort')
return ''
}
} else {
this.cardDownloadPromise = this.dler.downloadSpread(
id.toString(),
cardDir(`bg_${id}.png`),
(progressing || (prog => { this.imgProgress = prog.loading }))
)
downloadResult = await this.cardDownloadPromise
this.cardDownloadPromise = null
return downloadResult
}
} catch (_err) {
if (_err.message !== 'abort') {
this.cardDownloadPromise = this.dler.downloadSpread(
id.toString(),
cardDir(`bg_${id}.png`),
(progressing || (prog => { this.imgProgress = prog.loading }))
)
downloadResult = await this.cardDownloadPromise
this.cardDownloadPromise = null
return downloadResult
} else {
throw _err
}
}
}
return cardDir(`bg_${id}.png`)
}
toggle (practice: string): void {
switch (practice) {
case 'idol.before':
this.information = this.activeCard
if (navigator.onLine) {
this.changeBackground(this.activeCard).catch(err => {
console.error(err)
error(`IDOL changeBackground: ${err.stack}`)
})
}
break
case 'idol.after':
this.information = this.activeCardPlus
if (navigator.onLine) {
this.changeBackground(this.activeCardPlus).catch(err => {
console.error(err)
error(`IDOL changeBackground: ${err.stack}`)
})
}
break
default:
break
}
}
opendir (): void {
this.playSe(this.enterSe)
const dir = cardDir()
if (!fs.existsSync(dir)) fs.mkdirsSync(dir)
if (window.node.process.platform === 'win32') {
shell.openExternal(dir).catch(err => {
console.error(err)
error(`IDOL openExternal: ${err.stack}`)
})
} else {
shell.showItemInFolder(dir + '/.')
}
}
mounted (): void {
this.$nextTick(() => {
this.event.$on('eventBgReady', (id: number) => {
if (id % 2 === 0) {
this.currentPractice = 'idol.after'
for (let i = 0; i < this.cardData.length; i++) {
if (Number(this.cardData[i].id) === id - 1) {
this.activeCard = this.cardData[i]
continue
}
if (Number(this.cardData[i].id) === id) {
this.activeCardPlus = this.cardData[i]
this.information = this.cardData[i]
break
}
}
} else {
this.currentPractice = 'idol.before'
for (let i = 0; i < this.cardData.length; i++) {
if (Number(this.cardData[i].id) === id) {
this.activeCard = this.cardData[i]
this.information = this.cardData[i]
continue
}
if (Number(this.cardData[i].id) === id + 1) {
this.activeCardPlus = this.cardData[i]
break
}
}
}
})
this.event.$on('eventRewardCard', (cardId: number[]) => {
this.eventCard = cardId
this.searchResult = this.cardData.filter(card => {
return cardId.includes(Number(card.id))
})
})
this.event.$on('enterKey', (block: string) => {
if (block === 'idol') {
this.query()
}
})
})
}
} | the_stack |
import * as Atom from "atom"
import {CompositeDisposable} from "atom"
import {BusySignalService, DatatipService, SignatureHelpRegistry} from "atom-ide-base"
import {IndieDelegate} from "atom/linter"
import {StatusBar} from "atom/status-bar"
import {throttle} from "lodash"
import * as path from "path"
import {ClientResolver} from "../client"
import {handlePromise} from "../utils"
import {getCodeActionsProvider} from "./atom-ide/codeActionsProvider"
import {getCodeHighlightProvider} from "./atom-ide/codeHighlightProvider"
import {TSDatatipProvider} from "./atom-ide/datatipProvider"
import {getDefinitionProvider} from "./atom-ide/definitionsProvider"
import {getFindReferencesProvider} from "./atom-ide/findReferencesProvider"
import {getHyperclickProvider} from "./atom-ide/hyperclickProvider"
import {getOutlineProvider} from "./atom-ide/outlineProvider"
import {TSSigHelpProvider} from "./atom-ide/sigHelpProvider"
import {AutocompleteProvider} from "./atom/autoCompleteProvider"
import {CodefixProvider} from "./atom/codefix"
import {
getIntentionsHighlightsProvider,
getIntentionsProvider,
} from "./atom/codefix/intentionsProvider"
import {registerCommands} from "./atom/commands"
import {StatusPanel, TBuildStatus, TProgress} from "./atom/components/statusPanel"
import {EditorPositionHistoryManager} from "./atom/editorPositionHistoryManager"
import {OccurrenceManager} from "./atom/occurrence/manager"
import {SigHelpManager} from "./atom/sigHelp/manager"
import {TooltipManager} from "./atom/tooltips/manager"
import {isTypescriptEditorWithPath, spanToRange, TextSpan} from "./atom/utils"
import {SemanticViewController} from "./atom/views/outline/semanticViewController"
import {SymbolsViewController} from "./atom/views/symbols/symbolsViewController"
import {ErrorPusher} from "./errorPusher"
import {State} from "./packageState"
import {TypescriptEditorPane} from "./typescriptEditorPane"
export interface Change extends TextSpan {
newText: string
}
export interface Edit {
fileName: string
textChanges: ReadonlyArray<Readonly<Change>>
}
export type Edits = ReadonlyArray<Readonly<Edit>>
export type ApplyEdits = (edits: Edits) => Promise<void>
export type ReportBusyWhile = <T>(title: string, generator: () => Promise<T>) => Promise<T>
export class PluginManager {
// components
private subscriptions: CompositeDisposable
private clientResolver: ClientResolver
private statusPanel: StatusPanel
private errorPusher: ErrorPusher
private codefixProvider: CodefixProvider
private semanticViewController: SemanticViewController
private symbolsViewController: SymbolsViewController
private editorPosHist: EditorPositionHistoryManager
private tooltipManager: TooltipManager
private usingBuiltinTooltipManager = true
private sigHelpManager: SigHelpManager
private usingBuiltinSigHelpManager = true
private occurrenceManager: OccurrenceManager
private pending = new Set<{title: string}>()
private busySignalService?: BusySignalService
private typescriptPaneFactory: (editor: Atom.TextEditor) => TypescriptEditorPane
public constructor(state?: Partial<State>) {
this.subscriptions = new CompositeDisposable()
this.clientResolver = new ClientResolver(this.reportBusyWhile)
this.subscriptions.add(this.clientResolver)
this.statusPanel = new StatusPanel()
this.subscriptions.add(this.statusPanel)
this.errorPusher = new ErrorPusher()
this.subscriptions.add(this.errorPusher)
this.codefixProvider = new CodefixProvider(
this.clientResolver,
this.errorPusher,
this.applyEdits,
)
this.subscriptions.add(this.codefixProvider)
this.semanticViewController = new SemanticViewController(this.getClient)
this.subscriptions.add(this.semanticViewController)
this.editorPosHist = new EditorPositionHistoryManager(state && state.editorPosHistState)
this.subscriptions.add(this.editorPosHist)
this.symbolsViewController = new SymbolsViewController({
histGoForward: this.histGoForward,
getClient: this.getClient,
})
this.subscriptions.add(this.symbolsViewController)
this.tooltipManager = new TooltipManager(this.getClient)
this.subscriptions.add(this.tooltipManager)
this.sigHelpManager = new SigHelpManager({
getClient: this.getClient,
})
this.subscriptions.add(this.sigHelpManager)
this.occurrenceManager = new OccurrenceManager(this.getClient)
this.subscriptions.add(this.occurrenceManager)
this.typescriptPaneFactory = TypescriptEditorPane.createFactory({
clearFileErrors: this.clearFileErrors,
getClient: this.getClient,
reportBuildStatus: this.reportBuildStatus,
reportClientInfo: this.reportClientInfo,
})
this.subscribeEditors()
// Register the commands
this.subscriptions.add(
registerCommands({
getClient: this.getClient,
applyEdits: this.applyEdits,
clearErrors: this.clearErrors,
killAllServers: this.killAllServers,
reportProgress: this.reportProgress,
reportBuildStatus: this.reportBuildStatus,
toggleSemanticViewController: () => {
handlePromise(this.semanticViewController.toggle())
},
toggleFileSymbolsView: (ed) => {
this.symbolsViewController.toggleFileView(ed)
},
toggleProjectSymbolsView: (ed) => {
this.symbolsViewController.toggleProjectView(ed)
},
histGoForward: this.histGoForward,
histGoBack: () => this.editorPosHist.goBack(),
histShowHistory: () => this.editorPosHist.showHistory(),
showTooltipAt: this.showTooltipAt,
showSigHelpAt: this.showSigHelpAt,
hideSigHelpAt: this.hideSigHelpAt,
rotateSigHelp: this.rotateSigHelp,
}),
)
}
public destroy() {
this.subscriptions.dispose()
for (const ed of atom.workspace.getTextEditors()) {
const pane = TypescriptEditorPane.lookupPane(ed)
if (pane) pane.destroy()
}
this.clientResolver.dispose()
}
public serialize(): State {
return {
version: "0.1",
editorPosHistState: this.editorPosHist.serialize(),
}
}
public consumeLinter(register: (opts: {name: string}) => IndieDelegate) {
const linter = register({
name: "TypeScript",
})
this.errorPusher.setLinter(linter)
this.subscriptions.add(
this.clientResolver.on("diagnostics", ({type, filePath, diagnostics}) => {
this.errorPusher.setErrors(type, filePath, diagnostics)
}),
)
}
public consumeStatusBar(statusBar: StatusBar) {
let statusPriority = 100
for (const panel of statusBar.getRightTiles()) {
if (atom.views.getView(panel.getItem()).tagName === "GRAMMAR-SELECTOR-STATUS") {
statusPriority = panel.getPriority() - 1
}
}
const tile = statusBar.addRightTile({
item: this.statusPanel,
priority: statusPriority,
})
const disp = new Atom.Disposable(() => {
tile.destroy()
})
this.subscriptions.add(disp)
return disp
}
public consumeDatatipService(datatip: DatatipService) {
if (atom.config.get("atom-typescript").preferBuiltinTooltips) return
const disp = datatip.addProvider(new TSDatatipProvider(this.getClient))
this.subscriptions.add(disp)
this.tooltipManager.dispose()
this.usingBuiltinTooltipManager = false
return disp
}
public consumeSigHelpService(registry: SignatureHelpRegistry): void | Atom.DisposableLike {
if (atom.config.get("atom-typescript").preferBuiltinSigHelp) return
const provider = new TSSigHelpProvider(this.getClient)
const disp = registry(provider)
this.subscriptions.add(disp, provider)
this.sigHelpManager.dispose()
this.usingBuiltinSigHelpManager = false
return disp
}
public consumeBusySignal(busySignalService: BusySignalService): void | Atom.DisposableLike {
if (atom.config.get("atom-typescript").preferBuiltinBusySignal) return
this.busySignalService = busySignalService
const disp = {
dispose: () => {
if (this.busySignalService) this.busySignalService.dispose()
this.busySignalService = undefined
},
}
this.subscriptions.add(disp)
return disp
}
// Registering an autocomplete provider
public provideAutocomplete() {
return [new AutocompleteProvider(this.getClient, this.applyEdits)]
}
public provideIntentions() {
return getIntentionsProvider(this.codefixProvider)
}
public provideIntentionsHighlight() {
return getIntentionsHighlightsProvider(this.codefixProvider)
}
public provideCodeActions() {
return getCodeActionsProvider(this.codefixProvider)
}
public provideHyperclick() {
return getHyperclickProvider(this.getClient, this.histGoForward)
}
public provideReferences() {
return getFindReferencesProvider(this.getClient)
}
public provideOutlines() {
return getOutlineProvider(this.getClient)
}
public provideDefinitions() {
if (atom.config.get("atom-typescript").disableAtomIdeDefinitions) return
return getDefinitionProvider(this.getClient)
}
public provideCodeHighlight() {
if (atom.config.get("atom-typescript").preferBuiltinOccurrenceHighlight) return
this.occurrenceManager.dispose()
return getCodeHighlightProvider(this.getClient)
}
private clearErrors = () => {
this.errorPusher.clear()
}
private clearFileErrors = (filePath: string) => {
this.errorPusher.clearFileErrors(filePath)
}
private getClient = async (filePath: string) => {
return this.clientResolver.get(filePath)
}
private killAllServers = () => {
handlePromise(this.clientResolver.restartAllServers())
}
private withBuffer = async <T>(
filePath: string,
action: (buffer: Atom.TextBuffer) => Promise<T>,
) => {
const normalizedFilePath = path.normalize(filePath)
const ed = atom.workspace.getTextEditors().find((p) => p.getPath() === normalizedFilePath)
// found open buffer
if (ed) return action(ed.getBuffer())
// no open buffer
const buffer = await Atom.TextBuffer.load(normalizedFilePath)
try {
return await action(buffer)
} finally {
if (buffer.isModified()) await buffer.save()
buffer.destroy()
}
}
private reportBusyWhile: ReportBusyWhile = async (title, generator) => {
if (this.busySignalService) {
return this.busySignalService.reportBusyWhile(title, generator)
} else {
const event = {title}
try {
this.pending.add(event)
this.drawPending(Array.from(this.pending))
return await generator()
} finally {
this.pending.delete(event)
this.drawPending(Array.from(this.pending))
}
}
}
private reportProgress = (progress: TProgress) => {
handlePromise(this.statusPanel.update({progress}))
}
private reportBuildStatus = (buildStatus: TBuildStatus | undefined) => {
handlePromise(this.statusPanel.update({buildStatus}))
}
private reportClientInfo = (info: {clientVersion: string; tsConfigPath: string | undefined}) => {
handlePromise(this.statusPanel.update(info))
}
private applyEdits: ApplyEdits = async (edits) =>
void Promise.all(
edits.map((edit) =>
this.withBuffer(edit.fileName, async (buffer) => {
buffer.transact(() => {
const changes = edit.textChanges
.map((e) => ({range: spanToRange(e), newText: e.newText}))
.reverse() // NOTE: needs reverse for cases where ranges are same for two changes
.sort((a, b) => b.range.compare(a.range))
for (const change of changes) {
buffer.setTextInRange(change.range, change.newText)
}
})
}),
),
)
private showTooltipAt = async (ed: Atom.TextEditor): Promise<void> => {
if (this.usingBuiltinTooltipManager) this.tooltipManager.showExpressionAt(ed)
else await atom.commands.dispatch(atom.views.getView(ed), "datatip:toggle")
}
private showSigHelpAt = async (ed: Atom.TextEditor): Promise<void> => {
if (this.usingBuiltinSigHelpManager) await this.sigHelpManager.showTooltipAt(ed)
else await atom.commands.dispatch(atom.views.getView(ed), "signature-help:show")
}
private hideSigHelpAt = (ed: Atom.TextEditor): boolean => {
if (this.usingBuiltinSigHelpManager) return this.sigHelpManager.hideTooltipAt(ed)
else return false
}
private rotateSigHelp = (ed: Atom.TextEditor, shift: number): boolean => {
if (this.usingBuiltinSigHelpManager) return this.sigHelpManager.rotateSigHelp(ed, shift)
else return false
}
private histGoForward: EditorPositionHistoryManager["goForward"] = (ed, opts) => {
return this.editorPosHist.goForward(ed, opts)
}
private subscribeEditors() {
this.subscriptions.add(
atom.workspace.observeTextEditors((editor: Atom.TextEditor) => {
this.typescriptPaneFactory(editor)
}),
atom.workspace.onDidChangeActiveTextEditor((ed) => {
if (ed && isTypescriptEditorWithPath(ed)) {
handlePromise(this.statusPanel.show())
const tep = TypescriptEditorPane.lookupPane(ed)
if (tep) tep.didActivate()
} else handlePromise(this.statusPanel.hide())
}),
)
}
// tslint:disable-next-line:member-ordering
private drawPending = throttle(
(pending: Array<{title: string}>) => handlePromise(this.statusPanel.update({pending})),
100,
{leading: false},
)
} | the_stack |
import Mongoose = require("mongoose");
import Q = require('q');
import { EntityChange } from '../core/enums/entity-change';
import { getEntity, repoFromModel } from '../core/dynamic/model-entity';
import * as Enumerable from 'linq';
import { winstonLog } from '../logging/winstonLog';
import * as mongooseHelper from './mongoose-model-helper';
import * as CoreUtils from "../core/utils";
import { ConstantKeys } from '../core/constants';
import * as Utils from './utils';
import { QueryOptions } from '../core/interfaces/queryOptions';
import { MetaUtils } from "../core/metadata/utils";
import { Decorators } from '../core/constants/decorators';
import { GetRepositoryForName, DynamicRepository } from '../core/dynamic/dynamic-repository';
import {_arrayPropListSchema} from './dynamic-schema';
import { MetaData } from '../core/metadata/metadata';
import {ShardInfo} from '../core/interfaces/shard-Info';
import {InstanceService} from '../core/services/instance-service';
/**
* Iterate through objArr and check if any child object need to be added. If yes, then add those child objects.
* Bulk create these updated objects.
* Usage - Post multiple objects parallely
* @param model
* @param objArr
*/
export function bulkPost(model: Mongoose.Model<any>, objArr: Array<any>, batchSize?: number): Q.Promise<any> {
if (!objArr) {
return Q.when([]);
}
if (objArr && objArr.length <= 0) {
return Q.when([]);
}
//console.log("bulkPost " + model.modelName);
mongooseHelper.updateWriteCount();
var addChildModel = [];
// create all cloned models
var clonedModels = [];
let transientProps = mongooseHelper.getAllTransientProps(model);
Enumerable.from(objArr).forEach(obj => {
var cloneObj = mongooseHelper.removeGivenTransientProperties(model, obj, transientProps);
cloneObj[ConstantKeys.TempId] = cloneObj._id ? cloneObj._id : Utils.autogenerateIds(model);
clonedModels.push(cloneObj);
});
return mongooseHelper.addChildModelToParent(model, clonedModels)
.then(result => {
// autogenerate ids of all the objects
//Enumerable.from(clonedModels).forEach(clonedObj => {
// try {
// mongooseHelper.autogenerateIdsForAutoFields(model, clonedObj);
// //Object.assign(obj, clonedObj);
// } catch (ex) {
// winstonLog.logError(`Error in bulkPost ${ex}`);
// return Q.reject(ex);
// }
//});
var asyncCalls = [];
if (!batchSize) batchSize = 1000;
for (let curCount = 0; curCount < clonedModels.length; curCount += batchSize) {
asyncCalls.push(executeBulk(model, clonedModels.slice(curCount, curCount + batchSize)))
}
return Q.allSettled(asyncCalls).then(suces => {
let values = [];
values = suces.map(x => x.value).reduce((prev, current) => {
return prev.concat(current);
});
//console.log("bulkPost end" + model.modelName);
return values;
}).catch(er => {
winstonLog.logError(`Error in bulkPost ${model.modelName}: ${er}`);
throw er;
});
});
}
function executeBulk(model, arrayOfDbModels: Array<any>) {
//console.log("start executeBulk post", model.modelName);
let executeBulkPost = {};
arrayOfDbModels.forEach(x => {
if (x[ConstantKeys.TempId]) {
x._id = x[ConstantKeys.TempId]
delete x[ConstantKeys.TempId]
}
mongooseHelper.setUniqueIdFromShard(x);
mongooseHelper.setShardCondition(model, x);
let newModel = mongooseHelper.getNewModelFromObject(model, x);
if (!executeBulkPost[newModel.modelName]) {
executeBulkPost[newModel.modelName] = { objs: [], model: newModel };
}
executeBulkPost[newModel.modelName].objs.push(x);
if (!_arrayPropListSchema[model.modelName]) {
return;
}
// assign empty array for not defined properties
_arrayPropListSchema[model.modelName].forEach(prop => {
if (!x[prop]) {
x[prop] = [];
}
});
});
let asycnCalls = [];
Object.keys(executeBulkPost).forEach(x => {
asycnCalls.push(Q.nbind(executeBulkPost[x].model.collection.insertMany, executeBulkPost[x].model.collection)(executeBulkPost[x].objs));
});
//console.log("empty array executeBulk ", model.modelName);
return Q.allSettled(asycnCalls).then(result => {
//console.log("end executeBulk post", model.modelName);
let values = [];
values = result.map(x => x.value.ops).reduce((prev, current) => {
return prev.concat(current);
});
return values;
}).catch(err => {
throw err;
});
}
/**
* Iterate through objArr and call put for these
* Usage - Update multiple object sequentially
* @param model
* @param objArr
*/
export function bulkPut(model: Mongoose.Model<any>, objArr: Array<any>, batchSize?: number, donotLoadChilds?: boolean): Q.Promise<any> {
if (!objArr || !objArr.length) return Q.when([]);
//console.log("bulkPut " + model.modelName);
mongooseHelper.updateWriteCount();
var asyncCalls = [];
var length = objArr.length;
var ids = objArr.map(x => x._id);
var bulk = model.collection.initializeUnorderedBulkOp();
var asyncCalls = [];
if (!batchSize) {
asyncCalls.push(executeBulkPut(model, objArr, donotLoadChilds));
} else {
for (let curCount = 0; curCount < objArr.length; curCount += batchSize) {
asyncCalls.push(executeBulkPut(model, objArr.slice(curCount, curCount + batchSize), donotLoadChilds))
}
}
return Q.allSettled(asyncCalls).then(suces => {
let values = [];
values = suces.map(x => x.value).reduce((prev, current) => {
return prev.concat(current);
});
//console.log("bulkPut end" + model.modelName);
return values;
}).catch(er => {
winstonLog.logError(`Error in bulkPut ${model.modelName}: ${er}`);
throw er;
});
}
function executeBulkPut(model: Mongoose.Model<any>, objArr: Array<any>, donotLoadChilds?: boolean) {
let length = objArr.length;
var asyncCalls = [];
let fullyLoaded = objArr && objArr.length > 0 && objArr[0][ConstantKeys.FullyLoaded];
let updateParentRequired = [];
var objectIds = [];
//console.log("bulkPut addChildModelToParent child start" + model.modelName);
let allUpdateProps = [];
return mongooseHelper.addChildModelToParent(model, objArr).then(r => {
//console.log("bulkPut addChildModelToParent child end" + model.modelName);
let transientProps = mongooseHelper.getAllTransientProps(model);
var metaArr = CoreUtils.getAllRelationsForTargetInternal(getEntity(model.modelName));
let isRelationsExist = false;
if (metaArr && metaArr.length) {
isRelationsExist = true;
}
//let updatePropsReq = !fullyLoaded || isRelationsExist;
// check if not relationship present in the docs then do not call updateProps
//
let allBulkExecute = {};
for (let i = 0; i < objArr.length; i++) {
let result = objArr[i];
let newModel = mongooseHelper.getNewModelFromObject(model, result);
var objectId = Utils.getCastObjectId(newModel, result._id);
objectIds.push(objectId);
let id = result._id;
let parent = result.parent;
if (!allBulkExecute[newModel.modelName]) {
allBulkExecute[newModel.modelName] = newModel.collection.initializeUnorderedBulkOp();
}
let bulk = allBulkExecute[newModel.modelName];
delete result._id;
delete result[ConstantKeys.FullyLoaded];
for (let prop in transientProps) {
delete result[transientProps[prop].propertyKey];
}
var updatedProps;
updatedProps = Utils.getUpdatedProps(result, EntityChange.put);
// //console.log("update props", updatedProps);
delete result.__dbEntity;
// update only modified objects
if (Object.keys(updatedProps).length === 0) {
continue;
}
updateParentRequired.push(objectId);
//if (updatePropsReq) {
// updatedProps = Utils.getUpdatedProps(result, EntityChange.put);
// // update only modified objects
// if (Object.keys(updatedProps).length === 0) {
// continue;
// }
//}
let isDecoratorPresent = isDecoratorApplied(model, Decorators.OPTIMISTICLOCK, "put");
let query: Object = { _id: objectId };
if (isDecoratorPresent === true) {
updatedProps["$set"] && delete updatedProps["$set"]["__v"];
updatedProps["$inc"] = { '__v': 1 };
query["__v"] = result["__v"];
}
bulk.find(mongooseHelper.setShardCondition(model, { _id: objectId })).update(updatedProps);
}
let asyncCalls = [];
//let promBulkUpdate = Q.when({});
//console.log("bulkPut bulk.execute start" + model.modelName);
if (updateParentRequired.length > 0) {
Object.keys(allBulkExecute).forEach(x => {
let bulk = allBulkExecute[x];
asyncCalls.push(Q.nbind(bulk.execute, bulk)());
});
}
return Q.allSettled(asyncCalls).then(result => {
//return promBulkUpdate.then(result => {
//console.log("bulkPut bulk.execute end" + model.modelName);
// update parent
let repo: DynamicRepository = repoFromModel[model.modelName];
let prom;
if (fullyLoaded) {
// remove eagerloading propeties because it will be used for updating parent
// validate that no one have tampered the new persistent entity
prom = Q.when(objArr);
objectIds.forEach((id, index) => {
objArr[index]['_id'] = id;
});
}
else {
prom = findMany(model, objectIds);
}
return prom.then((objects: Array<any>) => {
let updateParentProm = Q.when([]);
// if (updateParentRequired.length > 0) {
// let updateObject = [];
// updateParentRequired.forEach(x => {
// updateObject.push(objects.find(obj => obj._id.toString() == x));
// });
// updateParentProm = mongooseHelper.updateParent(model, updateObject);
// }
if (updateParentRequired.length > 0) {
let updateObject = [];
let newObjectsMap = {};
objects.forEach(x => {
newObjectsMap[x._id.toString()] = x;
});
updateParentRequired.forEach(x => {
if (newObjectsMap[x]) {
updateObject.push(newObjectsMap[x]);
}
});
updateParentProm = mongooseHelper.updateParent(model, updateObject);
}
return updateParentProm.then(res => {
//console.log("bulkPut updateParent start" + model.modelName);
if (donotLoadChilds === true) {
return Q.when(objects);
}
return mongooseHelper.fetchEagerLoadingProperties(model, objects).then(resultObject => {
return resultObject;
});
});
});
});
}).catch(error => {
winstonLog.logError(`Error in executeBulkPut ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* Iterate through objArr and call put for these
* Usage - Update multiple object sequentially
* @param model
* @param objArr
*/
export function bulkPatch(model: Mongoose.Model<any>, objArr: Array<any>): Q.Promise<any> {
if (!objArr || !objArr.length) return Q.when([]);
//console.log("bulkPatch " + model.modelName);
mongooseHelper.updateWriteCount();
var asyncCalls = [];
var length = objArr.length;
var ids = objArr.map(x => x._id);
var asyncCalls = [];
return mongooseHelper.addChildModelToParent(model, objArr).then(x => {
let transientProps = mongooseHelper.getAllTransientProps(model);
let jsonProps = mongooseHelper.getEmbeddedPropWithFlat(model).map(x => x.propertyKey);
//it has to be group by
let allBulkExecute = {};
objArr.forEach(result => {
var objectId = Utils.getCastObjectId(model, result._id);
let newModel = mongooseHelper.getNewModelFromObject(model, result);
if (!allBulkExecute[newModel.modelName]) {
allBulkExecute[newModel.modelName] = newModel.collection.initializeUnorderedBulkOp();
}
let bulk = allBulkExecute[newModel.modelName];
delete result._id;
for (let prop in transientProps) {
delete result[transientProps[prop].propertyKey];
}
var updatedProps = Utils.getUpdatedProps(result, EntityChange.patch, jsonProps);
let isDecoratorPresent = isDecoratorApplied(model, Decorators.OPTIMISTICLOCK, "patch");
let query: Object = { _id: objectId };
if (isDecoratorPresent === true) {
updatedProps["$set"] && delete updatedProps["$set"]["__v"];
updatedProps["$inc"] = { '__v': 1 };
query["__v"] = result["__v"];
}
bulk.find(mongooseHelper.setShardCondition(model, query)).update(updatedProps);
});
let asyncCalls = [];
Object.keys(allBulkExecute).forEach(x => {
let bulk = allBulkExecute[x];
asyncCalls.push(Q.nbind(bulk.execute, bulk)());
});
return Q.allSettled(asyncCalls).then(result => {
// update parent
return findMany(model, ids).then((objects: Array<any>) => {
return mongooseHelper.updateParent(model, objects).then(res => {
return mongooseHelper.fetchEagerLoadingProperties(model, objects).then(resultObject => {
//console.log("bulkPatch end" + model.modelName);
return resultObject;
});
});
});
}).catch(error => {
winstonLog.logError(`Error in bulkPatch ${model.modelName}: ${error}`);
return Q.reject(error);
});
});
}
/**
* Bulk update objects. Find updated objects, and update the parent docs
* Usage - Update multiple objects parallely with same porperty set
* @param model
* @param objIds
* @param obj
*/
export function bulkPutMany(model: Mongoose.Model<any>, objIds: Array<any>, obj: any): Q.Promise<any> {
if (!objIds || !objIds.length) return Q.when([]);
//console.log("bulkPutMany " + model.modelName);
mongooseHelper.updateWriteCount();
delete obj._id;
let clonedObj = mongooseHelper.removeTransientProperties(model, obj);
// First update the any embedded property and then update the model
var cond = {};
cond['_id'] = {
$in: objIds
};
cond = mongooseHelper.setShardCondition(model, cond);
var updatedProps = Utils.getUpdatedProps(clonedObj, EntityChange.put);
let newModels = mongooseHelper.getAllShardModelsFromIds(model, objIds);
let asyncCalls = [];
Object.keys(newModels).forEach(x => {
asyncCalls.push(Q.nbind(newModels[x].update, newModels[x])(cond, updatedProps, { multi: true }));
});
return Q.allSettled(asyncCalls)
.then(result => {
let allReferencingEntities = CoreUtils.getAllRelationsForTarget(getEntity(model.modelName));
let ref = allReferencingEntities.find((x: MetaData) => x.params && x.params.embedded);
if (ref) {
return findMany(model, objIds).then((objects: Array<any>) => {
return mongooseHelper.updateParent(model, objects).then(res => {
//console.log("bulkPutMany end" + model.modelName);
return objects;
});
});
}
else {
//console.log("bulkPutMany end" + model.modelName);
return result;
}
}).catch(error => {
winstonLog.logError(`Error in bulkPutMany ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* Usage - Find all the objects
* @param model
*/
export function findAll(model: Mongoose.Model<any>): Q.Promise<any> {
//console.log("findAll " + model.modelName);
return <any>model.find(mongooseHelper.setShardCondition(model, {})).lean().then(result => {
//console.log("findAll end" + model.modelName);
return result;
}).catch(error => {
winstonLog.logError(`Error in findAll ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* Query collection and then populate child objects with relationship
* Usage - Search object with given condition
* @param model
* @param query
*/
export function countWhere(model: Mongoose.Model<any>, query: any): Q.Promise<any> {
if (Object.keys(query).length == 0) {
return Q.nbind(model.collection.stats, model.collection)().then((result: any) => {
return Q.resolve(result.count);
})
}
let queryObj = model.find(mongooseHelper.setShardCondition(model, query)).count();
//winstonLog.logInfo(`findWhere query is ${query}`);
return Q.nbind(queryObj.exec, queryObj)()
.then(result => {
// update embedded property, if any
return Q.resolve(result);
}).catch(error => {
winstonLog.logError(`Error in countWhere ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
export function distinctWhere(model: Mongoose.Model<any>, query: any): Q.Promise<any> {
let queryObj = model.find(mongooseHelper.setShardCondition(model, query)).distinct();
//winstonLog.logInfo(`findWhere query is ${query}`);
return Q.nbind(queryObj.exec, queryObj)()
.then(result => {
// update embedded property, if any
return Q.resolve(result);
}).catch(error => {
winstonLog.logError(`Error in distinctWhere ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* Query collection and then populate child objects with relationship
* Usage - Search object with given condition
* @param model
* @param query
* @param select {Array<string> | any} In case it is an array of string, it selects the specified keys mentioned in the array. In case it is an Object, it sets the JS object as the projection key
* @param sort
* @param skip
* @param limit
*/
export function findWhere(model: Mongoose.Model<any>, query: any, select?: Array<string> | any, queryOptions?: QueryOptions, toLoadChilds?: boolean, sort?: any, skip?: number, limit?: number): Q.Promise<any> {
//console.log("findWhere " + model.modelName);
let lt: string, gt: string, lte: string, gte: string, lt_value: number, lte_value: number, gt_value: number, gte_value: number;
var sel = {};
let order = undefined;
if (select instanceof Array) {
select.forEach(x => {
sel[x] = 1;
});
}
else if (select) {
sel = select;
}
if (queryOptions) {
if (queryOptions.limit != null)
limit = Number.parseInt(queryOptions.limit.toString());
if (queryOptions.skip != null)
skip = Number.parseInt(queryOptions.skip.toString());
if (queryOptions.lt != null) {
lt = queryOptions.lt;
}
if (queryOptions.gt != null) {
gt = queryOptions.gt;
}
if (queryOptions.lt_value != null) {
lt_value = Number.parseInt(queryOptions.lt_value);
}
if (queryOptions.gt_value != null) {
gt_value = Number.parseInt(queryOptions.gt_value);
}
if (queryOptions.lt != null) {
lte = queryOptions.lte;
}
if (queryOptions.gt != null) {
gte = queryOptions.gte;
}
if (queryOptions.lt_value != null) {
lte_value = Number.parseInt(queryOptions.lte_value);
}
if (queryOptions.gt_value != null) {
gte_value = Number.parseInt(queryOptions.gte_value);
}
if (queryOptions.sort != null) {
sort = queryOptions.sort;
if (queryOptions.order != null && queryOptions.order === 'desc') {
let descSort = {};
descSort[sort] = -1;
sort = descSort;
}
}
}
let newModels = {};
let obj: ShardInfo = InstanceService.getInstanceFromType(getEntity(model.modelName), true);
if (obj.getShardKey) {
let key = obj.getShardKey();
if (query[key]) {
if (CoreUtils.isJSON(query[key])) {
if (query[key]['$in']) {
query[key]['$in'].forEach(x => {
let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, x);
newModels[newModel.modelName] = newModel;
});
}
}
else {
// get shard collection
let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, query[key]);
newModels[newModel.modelName] = newModel;
}
}
if (Object.keys(newModels).length == 0) {
// find all the collection name and execute the query
mongooseHelper.getAllTheShards(model).forEach(x => {
newModels[x.modelName] = x;
});
}
}
else {
newModels[model.modelName] = model;
}
let asyncCalls = [];
Object.keys(newModels).forEach(x => {
let queryObj = newModels[x].find(mongooseHelper.setShardCondition(model, query), sel).lean();
if (sort) {
queryObj = queryObj.sort(sort);
}
if (skip) {
queryObj = queryObj.skip(skip);
}
if (limit) {
queryObj = queryObj.limit(limit);
}
if (gt && gt_value!=undefined) {
queryObj = queryObj.gt(gt, gt_value);
}
if (lt && lt_value != undefined) {
queryObj = queryObj.lt(lt, lt_value);
}
if (gte && gte_value != undefined) {
queryObj = queryObj.gte(gte, gte_value);
}
if (lte && lte_value != undefined) {
queryObj = queryObj.lte(lte, lte_value);
}
asyncCalls.push(Q.nbind(queryObj.exec, queryObj)());
});
return Q.allSettled(asyncCalls).then(res => {
let result = [];
result = res.map(x => x.value).reduce((prev, current) => {
return prev.concat(current);
});
//winstonLog.logInfo(`findWhere query is ${query}`);
// update embedded property, if any
if (toLoadChilds != undefined && toLoadChilds == false) {
mongooseHelper.transformAllEmbeddedChildern1(model, result);
//console.log("findWhere end" + model.modelName);
return result;
}
var asyncCalls = [];
asyncCalls.push(mongooseHelper.embeddedChildren1(model, result, false));
return Q.allSettled(asyncCalls).then(r => {
//console.log("findWhere end" + model.modelName);
return result;
});
}).catch(error => {
winstonLog.logError(`Error in findWhere ${model.modelName}: ${error}`);
return Q.reject(error);
});
// winstonLog.logInfo(`findWhere query is ${query}`);
// return Q.nbind(model.find, model)(query)
// .then(result => {
// return toObject(result);
// }).catch(error => {
// winstonLog.logError(`Error in findWhere ${error}`);
// return error;
// });
}
/**
* Usage - find object with given object id
* @param model
* @param id
*/
export function findOne(model: Mongoose.Model<any>, id, donotLoadChilds?: boolean): Q.Promise<any> {
//console.log("findOne " + model.modelName);
let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, id);
return <any>newModel.findOne(mongooseHelper.setShardCondition(model, { '_id': id })).lean().then(result => {
return mongooseHelper.embeddedChildren1(model, [result], false, donotLoadChilds)
.then(r => {
//console.log("findOne end" + model.modelName);
return result;
});
}).catch(error => {
winstonLog.logError(`Error in findOne ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* Usage - find the object with given {property : value}
* @param model
* @param fieldName
* @param value
*/
export function findByField(model: Mongoose.Model<any>, fieldName, value): Q.Promise<any> {
//console.log("findByField " + model.modelName);
var param = {};
param[fieldName] = value;
return <any>model.findOne(mongooseHelper.setShardCondition(model, param)).lean().then(result => {
return mongooseHelper.embeddedChildren1(model, [result], false)
.then(r => {
//console.log("findByField end" + model.modelName);
return result;
});
},
err => {
winstonLog.logError(`Error in findByField ${model.modelName}: ${err}`);
return Q.reject(err);
});
}
/**
* Usage - Find all the objects with given ids
* @param model
* @param ids
*/
export function findMany(model: Mongoose.Model<any>, ids: Array<any>, toLoadEmbeddedChilds?: boolean) {
if (!ids || !ids.length) return Q.when([]);
//console.log("findMany " + model.modelName);
if (toLoadEmbeddedChilds == undefined) {
toLoadEmbeddedChilds = false;
}
let newModels = mongooseHelper.getAllShardModelsFromIds(model, ids);
let asyncCalls = [];
Object.keys(newModels).forEach(x => {
asyncCalls.push(<any>newModels[x].find(mongooseHelper.setShardCondition(model, {
'_id': {
$in: ids.map(x => Utils.getCastObjectId(model, x))
}
})).lean());
});
return Q.allSettled(asyncCalls).then(res => {
let result = [];
result = res.map(x => x.value).reduce((prev, current) => {
return prev.concat(current);
});
if (result.length !== ids.length) {
let oneId = "";
if (ids && ids.length) {
oneId = ids[0];
}
var error = 'findmany - numbers of items found:' + result.length + 'number of items searched: ' + ids.length + ' for model: ' + model.modelName + ' one of the id searched is: ' + oneId;
winstonLog.logError(`Error in findMany ${error}`);
return Q.reject(error);
}
if (toLoadEmbeddedChilds) {
let asyncCalls = [];
asyncCalls.push(mongooseHelper.embeddedChildren1(model, result, false));
//console.log("findMany end" + model.modelName);
return Q.allSettled(asyncCalls).then(r => {
return result;
});
} else {
mongooseHelper.transformAllEmbeddedChildern1(model, result);
//console.log("findMany end" + model.modelName);
return result;
}
}).catch(error => {
winstonLog.logError(`Error in findMany ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* find object with the given id.
* Check if property has a relationship. If yes, then find all the child objects and return child
* @param model
* @param id
* @param prop
*/
export function findChild(model: Mongoose.Model<any>, id, prop): Q.Promise<any> {
//console.log("findChild " + model.modelName);
let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, id);
return <any>newModel.findOne(mongooseHelper.setShardCondition(model, { '_id': id })).lean().then(res => {
var metas = CoreUtils.getAllRelationsForTargetInternal(getEntity(model.modelName));
if (Enumerable.from(metas).any(x => x.propertyKey == prop)) {
// create new object and add only that property for which we want to do eagerloading
var result = {};
result[prop] = res;
return mongooseHelper.embeddedChildren1(model, [result], true)
.then(r => {
//console.log("findChild end" + model.modelName);
return result[prop];
});
}
//console.log("findChild end" + model.modelName);
return res;
}).catch(error => {
winstonLog.logError(`Error in findChild ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* case 1: all new - create main item and child separately and embed if true
* case 2: some new, some update - create main item and update/create child accordingly and embed if true
* @param obj
*/
export function post(model: Mongoose.Model<any>, obj: any): Q.Promise<any> {
//console.log("post " + model.modelName);
mongooseHelper.updateWriteCount();
let clonedObj = mongooseHelper.removeTransientProperties(model, obj);
clonedObj[ConstantKeys.TempId] = clonedObj._id ? clonedObj._id : Utils.autogenerateIds(model);
return mongooseHelper.addChildModelToParent(model, [clonedObj])
.then(result => {
//try {
// mongooseHelper.autogenerateIdsForAutoFields(model, clonedObj);
// //Object.assign(obj, clonedObj);
//} catch (ex) {
// //console.log(ex);
// return Q.reject(ex);
//}
if (clonedObj[ConstantKeys.TempId]) {
clonedObj._id = clonedObj[ConstantKeys.TempId];
delete clonedObj[ConstantKeys.TempId];
}
mongooseHelper.setUniqueIdFromShard(clonedObj);
mongooseHelper.setShardCondition(model, clonedObj);
// assign empty array for not defined properties
if (_arrayPropListSchema[model.modelName]) {
_arrayPropListSchema[model.modelName].forEach(prop => {
if (!clonedObj[prop]) {
clonedObj[prop] = [];
}
});
}
let newModel = mongooseHelper.getNewModelFromObject(model, clonedObj);
return Q.nbind(newModel.create, newModel)(clonedObj).then(result => {
let resObj = Utils.toObject(result);
Object.assign(obj, resObj);
return mongooseHelper.embeddedChildren1(model, [obj], false)
.then(r => {
//console.log("post end " + model.modelName);
return obj;
});
});
}).catch(error => {
winstonLog.logError(`Error in post ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* Delete object with given id. Check if, any children have deletecase=true, then delete children from master table
* Update parent document for all the deleted objects
* Usage - Delete object given id
* @param model
* @param id
*/
export function del(model: Mongoose.Model<any>, id: any): Q.Promise<any> {
//console.log("delete " + model.modelName);
let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, id);
return <any>newModel.findByIdAndRemove(mongooseHelper.setShardCondition(model, { '_id': id })).lean().then((response: any) => {
return mongooseHelper.deleteCascade(model, [response]).then(x => {
return mongooseHelper.deleteEmbeddedFromParent(model, EntityChange.delete, [response])
.then(res => {
//console.log("delete end" + model.modelName);
return ({ delete: 'success' });
});
});
})
.catch(err => {
winstonLog.logError(`delete failed ${model.modelName}: ${err}`);
return Q.reject({ delete: 'failed', error: err });
});
}
/**
* Sequetially delete the objects
* @param modelte
* @param ids
*/
export function bulkDel(model: Mongoose.Model<any>, objs: Array<any>): Q.Promise<any> {
//console.log("bulkDel " + model.modelName);
var asyncCalls = [];
var ids = [];
Enumerable.from(objs).forEach(x => {
if (CoreUtils.isJSON(x)) {
ids.push(x._id);
}
else {
ids.push(x);
}
});
if (!ids || !ids.length) return Q.when([]);
let newModels = mongooseHelper.getAllShardModelsFromIds(model, ids);
Object.keys(newModels).forEach(x => {
asyncCalls.push(<any>newModels[x].find(mongooseHelper.setShardCondition(model, {
'_id': {
$in: ids
}
})).lean());
});
return Q.allSettled(asyncCalls).then(res => {
let parents = [];
parents = res.map(x => x.value).reduce((prev, current) => {
return prev.concat(current);
});
asyncCalls = [];
Object.keys(newModels).forEach(x => {
asyncCalls.push(Q.nbind(newModels[x].remove, newModels[x])(mongooseHelper.setShardCondition(model, {
'_id': {
$in: ids
}
})));
});
return Q.allSettled(asyncCalls).then(result => {
return mongooseHelper.deleteCascade(model, parents).then(success => {
let asyncCalls = [];
return mongooseHelper.deleteEmbeddedFromParent(model, EntityChange.delete, parents).then(x => {
//console.log("bulkDel end" + model.modelName);
return ({ delete: 'success' });
});
});
}).catch(err => {
winstonLog.logError(`bulkDel failed ${model.modelName}: ${err}`);
return Q.reject('bulkDel failed');
});
});
}
/**
* Check if any child object need to be added, if yes, then add those child objects.
* update the object with propertie. And then update the parent objects.
* Usage - Update the object with given object id
* @param model
* @param id
* @param obj
*/
export function put(model: Mongoose.Model<any>, id: any, obj: any): Q.Promise<any> {
//console.log("put " + model.modelName);
// Mayank - Check with suresh how to reject the changes in optimistic locking
return bulkPut(model, [obj]).then((res: Array<any>) => {
if (res.length) {
//this merging is wrong, as we cannnot send transient props in API rsult.Inconsistency @Ratnesh sugestion
Object.assign(obj, res[0]);
//console.log("put end" + model.modelName);
return obj;
}
//console.log("put end" + model.modelName);
return [];
}).catch(error => {
winstonLog.logError(`Error in put ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* Check if any child object need to be added, if yes, then add those child objects.
* update the object with propertie. And then update the parent objects.
* Usage - Update the object with given object id
* @param model
* @param id
* @param obj
*/
export function patch(model: Mongoose.Model<any>, id: any, obj): Q.Promise<any> {
//console.log("patch " + model.modelName);
// need to set id in case id is not supplied in patched obj
obj._id = id;
// Mayank - Check with suresh how to reject the changes in optimistic locking
return bulkPatch(model, [obj]).then((res: Array<any>) => {
if (res.length)
return res[0];
return [];
}).catch(error => {
winstonLog.logError(`Error in patch ${model.modelName}: ${error}`);
return Q.reject(error);
});
}
/**
* Check whether decorator is applied or not.
* @param path
* @param decorator
* @param propertyKey
*/
function isDecoratorApplied(model: Mongoose.Model<any>, decorator: string, propertyKey: string) {
var isDecoratorPresent: boolean = false;
let repo = repoFromModel[model.modelName];
var repoEntity = repo && repo.getEntityType();
var optimisticLock = repoEntity && MetaUtils.getMetaData(repoEntity, decorator, propertyKey);
if (optimisticLock) {
isDecoratorPresent = true;
}
return isDecoratorPresent;
} | the_stack |
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { MetronAlertsPage } from '../alerts-list.po';
import {customMatchers} from '../../matchers/custom-matchers';
import {LoginPage} from '../../login/login.po';
import {loadTestData, deleteTestData, createMetaAlertsIndex} from '../../utils/e2e_util';
import {TreeViewPage} from '../tree-view/tree-view.po';
import {MetronAlertDetailsPage} from '../../alert-details/alert-details.po';
import {MetaAlertPage} from './meta-alert.po';
import {AlertFacetsPage} from '../alert-filters/alert-filters.po';
import {browser} from 'protractor';
describe('Test spec for meta alerts workflow', function() {
let detailsPage: MetronAlertDetailsPage;
let tablePage: MetronAlertsPage;
let metaAlertPage: MetaAlertPage;
let treePage: TreeViewPage;
let loginPage: LoginPage;
let alertFacetsPage: AlertFacetsPage;
beforeAll(async function() : Promise<any> {
loginPage = new LoginPage();
tablePage = new MetronAlertsPage();
treePage = new TreeViewPage();
tablePage = new MetronAlertsPage();
metaAlertPage = new MetaAlertPage();
detailsPage = new MetronAlertDetailsPage();
alertFacetsPage = new AlertFacetsPage();
jasmine.addMatchers(customMatchers);
await createMetaAlertsIndex();
await loadTestData();
await loginPage.login();
});
afterAll(async function() : Promise<any> {
await loginPage.logout();
await deleteTestData();
});
it('should have all the steps for meta alerts workflow', async function() : Promise<any> {
let comment1 = 'This is a sample comment';
let userNameAndTimestamp = '- admin - a few seconds ago';
let confirmText = 'Do you wish to create a meta alert with 22 selected alerts?';
let dashRowValues = {
'firstDashRow': ['0', '192.168.138.2', 'ALERTS', '22']
};
await tablePage.navigateTo();
expect(await tablePage.getChangesAlertTableTitle('Alerts (0)')).toEqual('Alerts (169)');
/* Create Meta Alert */
await treePage.selectGroup('ip_dst_addr');
expect(await treePage.getDashGroupValues('192.168.138.2')).toEqualBcoz(dashRowValues.firstDashRow, 'First Dashrow to be present');
await browser.sleep(1000);
await treePage.clickOnMergeAlerts('192.168.138.2');
expect(await treePage.getConfirmationText()).toEqualBcoz(confirmText, 'confirmation text to be present');
await treePage.clickNoForConfirmation();
await treePage.clickOnMergeAlerts('192.168.138.2');
await treePage.clickYesForConfirmation();
await treePage.waitForElementToDisappear('192.168.138.2');
await treePage.unGroup();
/* Table should have all alerts */
await tablePage.waitForMetaAlert(148);
expect(await tablePage.getChangedPaginationText('1 - 25 of 169')).toEqualBcoz('1 - 25 of 148', 'pagination text to be present');
expect(await tablePage.getCellValue(0, 2, '(14)')).toContain('(22)');
expect(await tablePage.getNonHiddenRowCount()).toEqualBcoz(25, '25 rows to be visible');
expect(await tablePage.getAllRowsCount()).toEqualBcoz(47, '47 rows to be available');
expect(await tablePage.getHiddenRowCount()).toEqualBcoz(22, '22 rows to be hidden');
await tablePage.expandMetaAlert(0);
expect(await tablePage.getNonHiddenRowCount()).toEqualBcoz(47, '47 rows to be visible after group expand');
expect(await tablePage.getAllRowsCount()).toEqualBcoz(47, '47 rows to be available after group expand');
expect(await tablePage.getHiddenRowCount()).toEqualBcoz(0, '0 rows to be hidden after group expand');
/* Meta Alert Status Change */
await tablePage.toggleAlertInList(0);
await tablePage.clickActionDropdownOption('Open');
expect(await tablePage.getAlertStatus(0, 'NEW', 2)).toEqual('OPEN');
expect(await tablePage.getAlertStatus(1, 'NEW')).toEqual('OPEN');
expect(await tablePage.getAlertStatus(2, 'NEW')).toEqual('OPEN');
/* Details Edit - add comments - remove comments - multiple alerts */
await tablePage.clickOnMetaAlertRow(0);
expect(await detailsPage.getAlertDetailsCount()).toEqualBcoz(22, '22 alert details should be present');
await detailsPage.clickRenameMetaAlert();
await detailsPage.renameMetaAlert('e2e-meta-alert');
await detailsPage.cancelRename();
expect(await detailsPage.getAlertNameOrId()).not.toEqual('e2e-meta-alert');
await detailsPage.clickRenameMetaAlert();
await detailsPage.renameMetaAlert('e2e-meta-alert');
await detailsPage.saveRename();
expect(await detailsPage.getAlertNameOrId()).toEqual('e2e-meta-alert');
// The below code will fail until this issue is resolved in Protractor: https://github.com/angular/protractor/issues/4693
// This is because the connection resets before deleting the test comment, which causes the assertion to be false
// await detailsPage.clickCommentsInSideNav();
// await detailsPage.addCommentAndSave(comment1, 0);
// expect(await detailsPage.getCommentsText()).toEqual([comment1]);
// expect(await detailsPage.getCommentsUserNameAndTimeStamp()).toEqual([userNameAndTimestamp]);
// expect(await detailsPage.getCommentIconCountInListView()).toEqual(1);
// await detailsPage.deleteComment();
// await detailsPage.clickYesForConfirmation(comment1);
await detailsPage.closeDetailPane();
/* Add to alert */
await tablePage.toggleAlertInList(3);
await tablePage.clickActionDropdownOption('Add to Alert');
await metaAlertPage.waitForDialog();
expect(await metaAlertPage.getPageTitle()).toEqualBcoz('Add to Alert', 'Add Alert Title should be present');
expect(await metaAlertPage.getMetaAlertsTitle()).toEqualBcoz('SELECT OPEN ALERT', 'select open alert title should be present');
expect(await metaAlertPage.getAvailableMetaAlerts()).toEqualBcoz('e2e-meta-alert (22)', 'Meta alert should be present');
await metaAlertPage.selectRadio();
await metaAlertPage.addToMetaAlert();
// FIXME: line below will fail because the following: https://issues.apache.org/jira/browse/METRON-1654
// expect(await tablePage.getCellValue(0, 2, '(22')).toContain('(23)', 'alert count should be incremented');
// /* Remove from alert */
let removAlertConfirmText = 'Do you wish to remove the alert from the meta alert?';
await tablePage.removeAlert(2);
expect(await treePage.getConfirmationText()).toEqualBcoz(removAlertConfirmText, 'confirmation text to remove alert from meta alert');
await treePage.clickYesForConfirmation();
// FIXME: line below will fail because the following: https://issues.apache.org/jira/browse/METRON-1654
// expect(await tablePage.getCellValue(0, 2, '(23')).toContain('(22)', 'alert count should be decremented');
// /* Delete Meta Alert */
let removeMetaAlertConfirmText = 'Do you wish to remove all the alerts from meta alert?';
await tablePage.removeAlert(0);
expect(await treePage.getConfirmationText()).toEqualBcoz(removeMetaAlertConfirmText, 'confirmation text to remove meta alert');
await treePage.clickYesForConfirmation();
});
it('should create a meta alert from nesting of more than one level', async function() : Promise<any> {
let groupByItems = {
'source:type': '1',
'ip_dst_addr': '7',
'enrichm...:country': '3',
'ip_src_addr': '4'
};
let alertsInMetaAlerts = [
'82f8046d-d...03b17480dd',
'5c1825f6-7...da3abe3aec',
'9041285e-9...a04a885b53',
'ed906df7-2...91cc54c2f3',
'c894bbcf-3...74cf0cc1fe',
'e63ff7ae-d...cddbe0c0b3',
'3c346bf9-b...cb04b43210',
'dcc483af-c...7bb802b652',
'b71f085d-6...a4904d8fcf',
'754b4f63-3...b39678207f',
'd9430af3-e...9a18600ab2',
'9a943c94-c...3b9046b782',
'f39dc401-3...1f9cf02cd9',
'd887fe69-c...2fdba06dbc',
'e38be207-b...60a43e3378',
'eba8eccb-b...0005325a90',
'adca96e3-1...979bf0b5f1',
'42f4ce28-8...b3d575b507',
'aed3d10f-b...8b8a139f25',
'a5e95569-a...0e2613b29a'
];
let alertsAfterDeletedInMetaAlerts = [
'3c346bf9-b...cb04b43210',
'42f4ce28-8...b3d575b507',
'5c1825f6-7...da3abe3aec',
'754b4f63-3...b39678207f',
'82f8046d-d...03b17480dd',
'9041285e-9...a04a885b53',
'9a943c94-c...3b9046b782',
'adca96e3-1...979bf0b5f1',
'aed3d10f-b...8b8a139f25',
'b71f085d-6...a4904d8fcf',
'c894bbcf-3...74cf0cc1fe',
'd887fe69-c...2fdba06dbc',
'd9430af3-e...9a18600ab2',
'dcc483af-c...7bb802b652',
'e38be207-b...60a43e3378',
'e63ff7ae-d...cddbe0c0b3',
'eba8eccb-b...0005325a90',
'ed906df7-2...91cc54c2f3',
'f39dc401-3...1f9cf02cd9'
];
// Create a meta alert from a group that is nested by more than 1 level
await treePage.selectGroup('source:type');
await treePage.selectGroup('ip_dst_addr');
await treePage.expandDashGroup('alerts_ui_e2e');
await treePage.clickOnMergeAlertsInTable('alerts_ui_e2e', '224.0.0.251', 0);
await treePage.clickYesForConfirmation();
await treePage.unGroup();
await tablePage.waitForMetaAlert(150);
expect(await tablePage.getChangedPaginationText('1 - 25 of 169')).toEqualBcoz('1 - 25 of 150', 'pagination text to be present');
// Meta Alert should appear in Filters
await alertFacetsPage.toggleFacetState(3);
let facetValues = await alertFacetsPage.getFacetValues(3);
expect(await facetValues['metaalert']).toEqual('1', 'for source:type facet');
// Meta Alert should not appear in Groups
expect(await treePage.getGroupByItemNames()).toEqualBcoz(Object.keys(groupByItems), 'Group By Elements names should be present');
expect(await treePage.getGroupByItemCounts()).toEqualBcoz(Object.keys(groupByItems).map(key => groupByItems[key]),
'5 Group By Elements values should be present');
await tablePage.setSearchText('guid:c894bbcf-3195-0708-aebe-0574cf0cc1fe', '150');
expect(await tablePage.getChangesAlertTableTitle('Alerts (150)')).toEqual('Alerts (1)');
await tablePage.expandMetaAlert(0);
expect(await tablePage.getAllRowsCount()).toEqual(21);
await tablePage.expandMetaAlert(0);
await tablePage.clickClearSearch('150');
expect(await tablePage.getChangesAlertTableTitle('Alerts (1)')).toEqual('Alerts (150)');
// Delete a meta alert from the middle and check the data
await tablePage.expandMetaAlert(0);
let guidValues = await tablePage.getTableCellValues(3, 1, 21);
guidValues = guidValues.slice(1, 21).sort();
expect(guidValues).toEqual(alertsInMetaAlerts.sort());
await tablePage.removeAlert(5);
await treePage.clickYesForConfirmation();
// FIXME: line below will fail because the following: https://issues.apache.org/jira/browse/METRON-1654
// expect(await tablePage.getCellValue(0, 2, '(20')).toContain('(19)', 'alert count should be decremented');
await browser.sleep(1000);
let guidValuesAfterDeleteOp = await tablePage.getTableCellValues(3, 1, 20);
guidValuesAfterDeleteOp = guidValuesAfterDeleteOp.slice(1, 20).sort();
expect(guidValuesAfterDeleteOp).toEqual(alertsAfterDeletedInMetaAlerts.sort());
//Remove the meta alert
await tablePage.removeAlert(0);
await treePage.clickYesForConfirmation();
});
}); | the_stack |
import PathProxy from '../core/PathProxy';
import { cubicSubdivide } from '../core/curve';
import Path from '../graphic/Path';
import Element, { ElementAnimateConfig } from '../Element';
import { defaults, map } from '../core/util';
import { lerp } from '../core/vector';
import Group, { GroupLike } from '../graphic/Group';
import { clonePath } from './path';
import { MatrixArray } from '../core/matrix';
import Transformable from '../core/Transformable';
import { ZRenderType } from '../zrender';
import { split } from './dividePath';
import { pathToBezierCurves } from './convertPath';
function alignSubpath(subpath1: number[], subpath2: number[]): [number[], number[]] {
const len1 = subpath1.length;
const len2 = subpath2.length;
if (len1 === len2) {
return [subpath1, subpath2];
}
const tmpSegX: number[] = [];
const tmpSegY: number[] = [];
const shorterPath = len1 < len2 ? subpath1 : subpath2;
const shorterLen = Math.min(len1, len2);
// Should divide excatly
const diff = Math.abs(len2 - len1) / 6;
const shorterBezierCount = (shorterLen - 2) / 6;
// Add `diff` number of beziers
const eachCurveSubDivCount = Math.ceil(diff / shorterBezierCount) + 1;
const newSubpath = [shorterPath[0], shorterPath[1]];
let remained = diff;
for (let i = 2; i < shorterLen;) {
let x0 = shorterPath[i - 2];
let y0 = shorterPath[i - 1];
let x1 = shorterPath[i++];
let y1 = shorterPath[i++];
let x2 = shorterPath[i++];
let y2 = shorterPath[i++];
let x3 = shorterPath[i++];
let y3 = shorterPath[i++];
if (remained <= 0) {
newSubpath.push(x1, y1, x2, y2, x3, y3);
continue;
}
let actualSubDivCount = Math.min(remained, eachCurveSubDivCount - 1) + 1;
for (let k = 1; k <= actualSubDivCount; k++) {
const p = k / actualSubDivCount;
cubicSubdivide(x0, x1, x2, x3, p, tmpSegX);
cubicSubdivide(y0, y1, y2, y3, p, tmpSegY);
// tmpSegX[3] === tmpSegX[4]
x0 = tmpSegX[3];
y0 = tmpSegY[3];
newSubpath.push(tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], x0, y0);
x1 = tmpSegX[5];
y1 = tmpSegY[5];
x2 = tmpSegX[6];
y2 = tmpSegY[6];
// The last point (x3, y3) is still the same.
}
remained -= actualSubDivCount - 1;
}
return shorterPath === subpath1 ? [newSubpath, subpath2] : [subpath1, newSubpath];
}
function createSubpath(lastSubpathSubpath: number[], otherSubpath: number[]) {
const len = lastSubpathSubpath.length;
const lastX = lastSubpathSubpath[len - 2];
const lastY = lastSubpathSubpath[len - 1];
const newSubpath: number[] = [];
for (let i = 0; i < otherSubpath.length;) {
newSubpath[i++] = lastX;
newSubpath[i++] = lastY;
}
return newSubpath;
}
/**
* Make two bezier arrays aligns on structure. To have better animation.
*
* It will:
* Make two bezier arrays have same number of subpaths.
* Make each subpath has equal number of bezier curves.
*
* array is the convert result of pathToBezierCurves.
*/
export function alignBezierCurves(array1: number[][], array2: number[][]) {
let lastSubpath1;
let lastSubpath2;
let newArray1 = [];
let newArray2 = [];
for (let i = 0; i < Math.max(array1.length, array2.length); i++) {
const subpath1 = array1[i];
const subpath2 = array2[i];
let newSubpath1;
let newSubpath2;
if (!subpath1) {
newSubpath1 = createSubpath(lastSubpath1 || subpath2, subpath2);
newSubpath2 = subpath2;
}
else if (!subpath2) {
newSubpath2 = createSubpath(lastSubpath2 || subpath1, subpath1);
newSubpath1 = subpath1;
}
else {
[newSubpath1, newSubpath2] = alignSubpath(subpath1, subpath2);
lastSubpath1 = newSubpath1;
lastSubpath2 = newSubpath2;
}
newArray1.push(newSubpath1);
newArray2.push(newSubpath2);
}
return [newArray1, newArray2];
}
interface MorphingPath extends Path {
__morphT: number;
}
export interface CombineMorphingPath extends Path {
childrenRef(): (CombineMorphingPath | Path)[]
__isCombineMorphing: boolean;
}
export function centroid(array: number[]) {
// https://en.wikipedia.org/wiki/Centroid#Of_a_polygon
let signedArea = 0;
let cx = 0;
let cy = 0;
const len = array.length;
// Polygon should been closed.
for (let i = 0, j = len - 2; i < len; j = i, i += 2) {
const x0 = array[j];
const y0 = array[j + 1];
const x1 = array[i];
const y1 = array[i + 1];
const a = x0 * y1 - x1 * y0;
signedArea += a;
cx += (x0 + x1) * a;
cy += (y0 + y1) * a;
}
if (signedArea === 0) {
return [array[0] || 0, array[1] || 0];
}
return [cx / signedArea / 3, cy / signedArea / 3, signedArea];
}
/**
* Offset the points to find the nearest morphing distance.
* Return beziers count needs to be offset.
*/
function findBestRingOffset(
fromSubBeziers: number[],
toSubBeziers: number[],
fromCp: number[],
toCp: number[]
) {
const bezierCount = (fromSubBeziers.length - 2) / 6;
let bestScore = Infinity;
let bestOffset = 0;
const len = fromSubBeziers.length;
const len2 = len - 2;
for (let offset = 0; offset < bezierCount; offset++) {
const cursorOffset = offset * 6;
let score = 0;
for (let k = 0; k < len; k += 2) {
let idx = k === 0 ? cursorOffset : ((cursorOffset + k - 2) % len2 + 2);
const x0 = fromSubBeziers[idx] - fromCp[0];
const y0 = fromSubBeziers[idx + 1] - fromCp[1];
const x1 = toSubBeziers[k] - toCp[0];
const y1 = toSubBeziers[k + 1] - toCp[1];
const dx = x1 - x0;
const dy = y1 - y0;
score += dx * dx + dy * dy;
}
if (score < bestScore) {
bestScore = score;
bestOffset = offset;
}
}
return bestOffset;
}
function reverse(array: number[]) {
const newArr: number[] = [];
const len = array.length;
for (let i = 0; i < len; i += 2) {
newArr[i] = array[len - i - 2];
newArr[i + 1] = array[len - i - 1];
}
return newArr;
}
type MorphingData = {
from: number[];
to: number[];
fromCp: number[];
toCp: number[];
rotation: number;
}[];
/**
* If we interpolating between two bezier curve arrays.
* It will have many broken effects during the transition.
* So we try to apply an extra rotation which can make each bezier curve morph as small as possible.
*/
function findBestMorphingRotation(
fromArr: number[][],
toArr: number[][],
searchAngleIteration: number,
searchAngleRange: number
): MorphingData {
const result = [];
let fromNeedsReverse: boolean;
for (let i = 0; i < fromArr.length; i++) {
let fromSubpathBezier = fromArr[i];
const toSubpathBezier = toArr[i];
const fromCp = centroid(fromSubpathBezier);
const toCp = centroid(toSubpathBezier);
if (fromNeedsReverse == null) {
// Reverse from array if two have different directions.
// Determine the clockwise based on the first subpath.
// Reverse all subpaths or not. Avoid winding rule changed.
fromNeedsReverse = fromCp[2] < 0 !== toCp[2] < 0;
}
const newFromSubpathBezier: number[] = [];
const newToSubpathBezier: number[] = [];
let bestAngle = 0;
let bestScore = Infinity;
let tmpArr: number[] = [];
const len = fromSubpathBezier.length;
if (fromNeedsReverse) {
// Make sure clockwise
fromSubpathBezier = reverse(fromSubpathBezier);
}
const offset = findBestRingOffset(fromSubpathBezier, toSubpathBezier, fromCp, toCp) * 6;
const len2 = len - 2;
for (let k = 0; k < len2; k += 2) {
// Not include the start point.
const idx = (offset + k) % len2 + 2;
newFromSubpathBezier[k + 2] = fromSubpathBezier[idx] - fromCp[0];
newFromSubpathBezier[k + 3] = fromSubpathBezier[idx + 1] - fromCp[1];
}
newFromSubpathBezier[0] = fromSubpathBezier[offset] - fromCp[0];
newFromSubpathBezier[1] = fromSubpathBezier[offset + 1] - fromCp[1];
if (searchAngleIteration > 0) {
const step = searchAngleRange / searchAngleIteration;
for (let angle = -searchAngleRange / 2; angle <= searchAngleRange / 2; angle += step) {
const sa = Math.sin(angle);
const ca = Math.cos(angle);
let score = 0;
for (let k = 0; k < fromSubpathBezier.length; k += 2) {
const x0 = newFromSubpathBezier[k];
const y0 = newFromSubpathBezier[k + 1];
const x1 = toSubpathBezier[k] - toCp[0];
const y1 = toSubpathBezier[k + 1] - toCp[1];
// Apply rotation on the target point.
const newX1 = x1 * ca - y1 * sa;
const newY1 = x1 * sa + y1 * ca;
tmpArr[k] = newX1;
tmpArr[k + 1] = newY1;
const dx = newX1 - x0;
const dy = newY1 - y0;
// Use dot product to have min direction change.
// const d = Math.sqrt(x0 * x0 + y0 * y0);
// score += x0 * dx / d + y0 * dy / d;
score += dx * dx + dy * dy;
}
if (score < bestScore) {
bestScore = score;
bestAngle = angle;
// Copy.
for (let m = 0; m < tmpArr.length; m++) {
newToSubpathBezier[m] = tmpArr[m];
}
}
}
}
else {
for (let i = 0; i < len; i += 2) {
newToSubpathBezier[i] = toSubpathBezier[i] - toCp[0];
newToSubpathBezier[i + 1] = toSubpathBezier[i + 1] - toCp[1];
}
}
result.push({
from: newFromSubpathBezier,
to: newToSubpathBezier,
fromCp,
toCp,
rotation: -bestAngle
});
}
return result;
}
export function isCombineMorphing(path: Element): path is CombineMorphingPath {
return (path as CombineMorphingPath).__isCombineMorphing;
}
export function isMorphing(el: Element) {
return (el as MorphingPath).__morphT >= 0;
}
const SAVED_METHOD_PREFIX = '__mOriginal_';
function saveAndModifyMethod<T extends object, M extends keyof T>(
obj: T,
methodName: M,
modifiers: { replace?: T[M], after?: T[M], before?: T[M] }
) {
const savedMethodName = SAVED_METHOD_PREFIX + methodName;
const originalMethod = (obj as any)[savedMethodName] || obj[methodName];
if (!(obj as any)[savedMethodName]) {
(obj as any)[savedMethodName] = obj[methodName];
}
const replace = modifiers.replace;
const after = modifiers.after;
const before = modifiers.before;
(obj as any)[methodName] = function () {
const args = arguments;
let res;
before && (before as unknown as Function).apply(this, args);
// Still call the original method if not replacement.
if (replace) {
res = (replace as unknown as Function).apply(this, args);
}
else {
res = originalMethod.apply(this, args);
}
after && (after as unknown as Function).apply(this, args);
return res;
};
}
function restoreMethod<T extends object>(
obj: T,
methodName: keyof T
) {
const savedMethodName = SAVED_METHOD_PREFIX + methodName;
if ((obj as any)[savedMethodName]) {
obj[methodName] = (obj as any)[savedMethodName];
(obj as any)[savedMethodName] = null;
}
}
function applyTransformOnBeziers(bezierCurves: number[][], mm: MatrixArray) {
for (let i = 0; i < bezierCurves.length; i++) {
const subBeziers = bezierCurves[i];
for (let k = 0; k < subBeziers.length;) {
const x = subBeziers[k];
const y = subBeziers[k + 1];
subBeziers[k++] = mm[0] * x + mm[2] * y + mm[4];
subBeziers[k++] = mm[1] * x + mm[3] * y + mm[5];
}
}
}
function prepareMorphPath(
fromPath: Path,
toPath: Path
) {
const fromPathProxy = fromPath.getUpdatedPathProxy();
const toPathProxy = toPath.getUpdatedPathProxy();
const [fromBezierCurves, toBezierCurves] =
alignBezierCurves(pathToBezierCurves(fromPathProxy), pathToBezierCurves(toPathProxy));
const fromPathTransform = fromPath.getComputedTransform();
const toPathTransform = toPath.getComputedTransform();
function updateIdentityTransform(this: Transformable) {
this.transform = null;
}
fromPathTransform && applyTransformOnBeziers(fromBezierCurves, fromPathTransform);
toPathTransform && applyTransformOnBeziers(toBezierCurves, toPathTransform);
// Just ignore transform
saveAndModifyMethod(toPath, 'updateTransform', { replace: updateIdentityTransform });
toPath.transform = null;
const morphingData = findBestMorphingRotation(fromBezierCurves, toBezierCurves, 10, Math.PI);
const tmpArr: number[] = [];
saveAndModifyMethod(toPath, 'buildPath', { replace(path: PathProxy) {
const t = (toPath as MorphingPath).__morphT;
const onet = 1 - t;
const newCp: number[] = [];
for (let i = 0; i < morphingData.length; i++) {
const item = morphingData[i];
const from = item.from;
const to = item.to;
const angle = item.rotation * t;
const fromCp = item.fromCp;
const toCp = item.toCp;
const sa = Math.sin(angle);
const ca = Math.cos(angle);
lerp(newCp, fromCp, toCp, t);
for (let m = 0; m < from.length; m += 2) {
const x0 = from[m];
const y0 = from[m + 1];
const x1 = to[m];
const y1 = to[m + 1];
const x = x0 * onet + x1 * t;
const y = y0 * onet + y1 * t;
tmpArr[m] = (x * ca - y * sa) + newCp[0];
tmpArr[m + 1] = (x * sa + y * ca) + newCp[1];
}
let x0 = tmpArr[0];
let y0 = tmpArr[1];
path.moveTo(x0, y0);
for (let m = 2; m < from.length;) {
const x1 = tmpArr[m++];
const y1 = tmpArr[m++];
const x2 = tmpArr[m++];
const y2 = tmpArr[m++];
const x3 = tmpArr[m++];
const y3 = tmpArr[m++];
// Is a line.
if (x0 === x1 && y0 === y1 && x2 === x3 && y2 === y3) {
path.lineTo(x3, y3);
}
else {
path.bezierCurveTo(x1, y1, x2, y2, x3, y3);
}
x0 = x3;
y0 = y3;
}
}
} });
}
/**
* Morphing from old path to new path.
*/
export function morphPath(
fromPath: Path,
toPath: Path,
animationOpts: ElementAnimateConfig
): Path {
if (!fromPath || !toPath) {
return toPath;
}
const oldDone = animationOpts.done;
// const oldAborted = animationOpts.aborted;
const oldDuring = animationOpts.during;
prepareMorphPath(fromPath, toPath);
(toPath as MorphingPath).__morphT = 0;
function restoreToPath() {
restoreMethod(toPath, 'buildPath');
restoreMethod(toPath, 'updateTransform');
// Mark as not in morphing
(toPath as MorphingPath).__morphT = -1;
// Cleanup.
toPath.createPathProxy();
toPath.dirtyShape();
}
toPath.animateTo({
__morphT: 1
} as any, defaults({
during(p) {
toPath.dirtyShape();
oldDuring && oldDuring(p);
},
done() {
restoreToPath();
oldDone && oldDone();
}
// NOTE: Don't do restore if aborted.
// Because all status was just set when animation started.
// aborted() {
// oldAborted && oldAborted();
// }
} as ElementAnimateConfig, animationOpts));
return toPath;
}
// https://github.com/mapbox/earcut/blob/master/src/earcut.js#L437
// https://jsfiddle.net/pissang/2jk7x145/
// function zOrder(x: number, y: number, minX: number, minY: number, maxX: number, maxY: number) {
// // Normalize coords to 0 - 1
// // The transformed into non-negative 15-bit integer range
// x = (maxX === minX) ? 0 : Math.round(32767 * (x - minX) / (maxX - minX));
// y = (maxY === minY) ? 0 : Math.round(32767 * (y - minY) / (maxY - minY));
// x = (x | (x << 8)) & 0x00FF00FF;
// x = (x | (x << 4)) & 0x0F0F0F0F;
// x = (x | (x << 2)) & 0x33333333;
// x = (x | (x << 1)) & 0x55555555;
// y = (y | (y << 8)) & 0x00FF00FF;
// y = (y | (y << 4)) & 0x0F0F0F0F;
// y = (y | (y << 2)) & 0x33333333;
// y = (y | (y << 1)) & 0x55555555;
// return x | (y << 1);
// }
// https://github.com/w8r/hilbert/blob/master/hilbert.js#L30
// https://jsfiddle.net/pissang/xdnbzg6v/
function hilbert(x: number, y: number, minX: number, minY: number, maxX: number, maxY: number) {
const bits = 16;
x = (maxX === minX) ? 0 : Math.round(32767 * (x - minX) / (maxX - minX));
y = (maxY === minY) ? 0 : Math.round(32767 * (y - minY) / (maxY - minY));
let d = 0;
let tmp: number;
for (let s = (1 << bits) / 2; s > 0; s /= 2) {
let rx = 0;
let ry = 0;
if ((x & s) > 0) {
rx = 1;
}
if ((y & s) > 0) {
ry = 1;
}
d += s * s * ((3 * rx) ^ ry);
if (ry === 0) {
if (rx === 1) {
x = s - 1 - x;
y = s - 1 - y;
}
tmp = x;
x = y;
y = tmp;
}
}
return d;
}
// Sort paths on hilbert. Not using z-order because it may still have large cross.
// So the left most source can animate to the left most target, not right most target.
// Hope in this way. We can make sure each element is animated to the proper target. Not the farthest.
function sortPaths(pathList: Path[]): Path[] {
let xMin = Infinity;
let yMin = Infinity;
let xMax = -Infinity;
let yMax = -Infinity;
const cps = map(pathList, path => {
const rect = path.getBoundingRect();
const m = path.getComputedTransform();
const x = rect.x + rect.width / 2 + (m ? m[4] : 0);
const y = rect.y + rect.height / 2 + (m ? m[5] : 0);
xMin = Math.min(x, xMin);
yMin = Math.min(y, yMin);
xMax = Math.max(x, xMax);
yMax = Math.max(y, yMax);
return [x, y];
});
const items = map(cps, (cp, idx) => {
return {
cp,
z: hilbert(cp[0], cp[1], xMin, yMin, xMax, yMax),
path: pathList[idx]
};
});
return items.sort((a, b) => a.z - b.z).map(item => item.path);
}
export interface DividePathParams {
path: Path,
count: number
};
export interface DividePath {
(params: DividePathParams): Path[]
}
export interface IndividualDelay {
(index: number, count: number, fromPath: Path, toPath: Path): number
}
function defaultDividePath(param: DividePathParams) {
return split(param.path, param.count);
}
export interface CombineConfig extends ElementAnimateConfig {
/**
* Transform of returned will be ignored.
*/
dividePath?: DividePath
/**
* delay of each individual.
* Because individual are sorted on z-order. The index is also sorted top-left / right-down.
*/
individualDelay?: IndividualDelay
/**
* If sort splitted paths so the movement between them can be more natural
*/
// sort?: boolean
}
function createEmptyReturn() {
return {
fromIndividuals: [] as Path[],
toIndividuals: [] as Path[],
count: 0
};
}
/**
* Make combine morphing from many paths to one.
* Will return a group to replace the original path.
*/
export function combineMorph(
fromList: (CombineMorphingPath | Path)[],
toPath: Path,
animationOpts: CombineConfig
) {
let fromPathList: Path[] = [];
function addFromPath(fromList: Element[]) {
for (let i = 0; i < fromList.length; i++) {
const from = fromList[i];
if (isCombineMorphing(from)) {
addFromPath((from as GroupLike).childrenRef());
}
else if (from instanceof Path) {
fromPathList.push(from);
}
}
}
addFromPath(fromList);
const separateCount = fromPathList.length;
// fromPathList.length is 0.
if (!separateCount) {
return createEmptyReturn();
}
const dividePath = animationOpts.dividePath || defaultDividePath;
let toSubPathList = dividePath({
path: toPath, count: separateCount
});
if (toSubPathList.length !== separateCount) {
console.error('Invalid morphing: unmatched splitted path');
return createEmptyReturn();
}
fromPathList = sortPaths(fromPathList);
toSubPathList = sortPaths(toSubPathList);
const oldDone = animationOpts.done;
// const oldAborted = animationOpts.aborted;
const oldDuring = animationOpts.during;
const individualDelay = animationOpts.individualDelay;
const identityTransform = new Transformable();
for (let i = 0; i < separateCount; i++) {
const from = fromPathList[i];
const to = toSubPathList[i];
to.parent = toPath as unknown as Group;
// Ignore transform in each subpath.
to.copyTransform(identityTransform);
// Will do morphPath for each individual if individualDelay is set.
if (!individualDelay) {
prepareMorphPath(from, to);
}
}
(toPath as CombineMorphingPath).__isCombineMorphing = true;
(toPath as CombineMorphingPath).childrenRef = function () {
return toSubPathList;
};
function addToSubPathListToZr(zr: ZRenderType) {
for (let i = 0; i < toSubPathList.length; i++) {
toSubPathList[i].addSelfToZr(zr);
}
}
saveAndModifyMethod(toPath, 'addSelfToZr', {
after(zr) {
addToSubPathListToZr(zr);
}
});
saveAndModifyMethod(toPath, 'removeSelfFromZr', {
after(zr) {
for (let i = 0; i < toSubPathList.length; i++) {
toSubPathList[i].removeSelfFromZr(zr);
}
}
});
function restoreToPath() {
(toPath as CombineMorphingPath).__isCombineMorphing = false;
// Mark as not in morphing
(toPath as MorphingPath).__morphT = -1;
(toPath as CombineMorphingPath).childrenRef = null;
restoreMethod(toPath, 'addSelfToZr');
restoreMethod(toPath, 'removeSelfFromZr');
}
const toLen = toSubPathList.length;
if (individualDelay) {
let animating = toLen;
const eachDone = () => {
animating--;
if (animating === 0) {
restoreToPath();
oldDone && oldDone();
}
};
// Animate each element individually.
for (let i = 0; i < toLen; i++) {
// TODO only call during once?
const indivdualAnimationOpts = individualDelay ? defaults({
delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toSubPathList[i]),
done: eachDone
} as ElementAnimateConfig, animationOpts) : animationOpts;
morphPath(fromPathList[i], toSubPathList[i], indivdualAnimationOpts);
}
}
else {
(toPath as MorphingPath).__morphT = 0;
toPath.animateTo({
__morphT: 1
} as any, defaults({
during(p) {
for (let i = 0; i < toLen; i++) {
const child = toSubPathList[i] as MorphingPath;
child.__morphT = (toPath as MorphingPath).__morphT;
child.dirtyShape();
}
oldDuring && oldDuring(p);
},
done() {
restoreToPath();
for (let i = 0; i < fromList.length; i++) {
restoreMethod(fromList[i], 'updateTransform');
}
oldDone && oldDone();
}
} as ElementAnimateConfig, animationOpts));
}
if (toPath.__zr) {
addToSubPathListToZr(toPath.__zr);
}
return {
fromIndividuals: fromPathList,
toIndividuals: toSubPathList,
count: toLen
};
}
export interface SeparateConfig extends ElementAnimateConfig {
dividePath?: DividePath
individualDelay?: IndividualDelay
/**
* If sort splitted paths so the movement between them can be more natural
*/
// sort?: boolean
// // If the from path of separate animation is doing combine animation.
// // And the paths number is not same with toPathList. We need to do enter/leave animation
// // on the missing/spare paths.
// enter?: (el: Path) => void
// leave?: (el: Path) => void
}
/**
* Make separate morphing from one path to many paths.
* Make the MorphingKind of `toPath` become `'ONE_ONE'`.
*/
export function separateMorph(
fromPath: Path,
toPathList: Path[],
animationOpts: SeparateConfig
) {
const toLen = toPathList.length;
let fromPathList: Path[] = [];
const dividePath = animationOpts.dividePath || defaultDividePath;
function addFromPath(fromList: Element[]) {
for (let i = 0; i < fromList.length; i++) {
const from = fromList[i];
if (isCombineMorphing(from)) {
addFromPath((from as GroupLike).childrenRef());
}
else if (from instanceof Path) {
fromPathList.push(from);
}
}
}
// This case most happen when a combining path is called to reverse the animation
// to its original separated state.
if (isCombineMorphing(fromPath)) {
addFromPath(fromPath.childrenRef());
const fromLen = fromPathList.length;
if (fromLen < toLen) {
let k = 0;
for (let i = fromLen; i < toLen; i++) {
// Create a clone
fromPathList.push(clonePath(fromPathList[k++ % fromLen]));
}
}
// Else simply remove if fromLen > toLen
fromPathList.length = toLen;
}
else {
fromPathList = dividePath({ path: fromPath, count: toLen });
const fromPathTransform = fromPath.getComputedTransform();
for (let i = 0; i < fromPathList.length; i++) {
// Force use transform of source path.
fromPathList[i].setLocalTransform(fromPathTransform);
}
if (fromPathList.length !== toLen) {
console.error('Invalid morphing: unmatched splitted path');
return createEmptyReturn();
}
}
fromPathList = sortPaths(fromPathList);
toPathList = sortPaths(toPathList);
const individualDelay = animationOpts.individualDelay;
for (let i = 0; i < toLen; i++) {
const indivdualAnimationOpts = individualDelay ? defaults({
delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toPathList[i])
} as ElementAnimateConfig, animationOpts) : animationOpts;
morphPath(fromPathList[i], toPathList[i], indivdualAnimationOpts);
}
return {
fromIndividuals: fromPathList,
toIndividuals: toPathList,
count: toPathList.length
};
}
export { split as defaultDividePath }; | the_stack |
import fs from "fs-extra";
import path from "path";
import * as ts from "typescript";
import { convert } from "../../commands/samples/tsToJs";
import { createPrinter } from "../printer";
import { createAccumulator } from "../typescript/accumulator";
import { createDiagnosticEmitter } from "../typescript/diagnostic";
import { AzSdkMetaTags, AZSDK_META_TAG_PREFIX, ModuleInfo, VALID_AZSDK_META_TAGS } from "./info";
import { testSyntax } from "./syntax";
import { isDependency, isRelativePath, toCommonJs } from "./transforms";
const log = createPrinter("samples:processor");
export async function processSources(
sourceDirectory: string,
sources: string[],
fail: (...values: unknown[]) => never
): Promise<ModuleInfo[]> {
// Project-scoped information (shared between all source files)
let hadUnsupportedSyntax = false;
const importedRelativeModules = new Set<string>();
const jobs = sources.map(async (source) => {
const sourceText = (await fs.readFile(source)).toString("utf8");
// File-scoped information
let summary: string | undefined = undefined;
const azSdkTags: AzSdkMetaTags = {};
const relativeSourcePath = path.relative(sourceDirectory, source);
// This object is used to gather information about the nodes.
// See: util/typescript/accumulator.ts
const accumulator = createAccumulator({
importedModules: {
predicate: isImportOrStaticRequire,
select: (node: ts.ImportDeclaration | ts.CallExpression) => {
if (ts.isImportDeclaration(node)) {
return (node.moduleSpecifier as ts.StringLiteral).text;
} else {
return (node.arguments[0] as ts.StringLiteralLike).text;
}
},
},
usedEnvironmentVariables: {
predicate: isProcessEnvAccess,
select: (node: ts.PropertyAccessExpression | ts.ElementAccessExpression) => {
if (ts.isPropertyAccessExpression(node)) {
return node.name.text;
} else {
return (node.argumentExpression as ts.StringLiteralLike).text;
}
},
},
exports: {
predicate: ({ modifiers }) =>
(modifiers?.some(({ kind }) => kind === ts.SyntaxKind.ExportKeyword) &&
!modifiers.some(({ kind }) => kind === ts.SyntaxKind.DefaultKeyword)) ??
false,
select: (node: ts.FunctionDeclaration | ts.ClassDeclaration | ts.VariableStatement) => {
if (ts.isVariableStatement(node)) {
return node.declarationList.declarations
.filter((decl) => ts.isIdentifier(decl.name))
.map((decl) => (decl.name as ts.Identifier).text);
} else {
return node.name?.text;
}
},
},
});
const sourceProcessor: ts.TransformerFactory<ts.SourceFile> =
(context) => (sourceFile: ts.SourceFile) => {
const emitError = createDiagnosticEmitter(sourceFile);
const visitor: ts.Visitor = (node: ts.Node) => {
const syntaxSupportError = testSyntax(node);
if (syntaxSupportError) {
hadUnsupportedSyntax = true;
emitError(syntaxSupportError.message, node, syntaxSupportError.suggest);
// We won't check the children of erroneous nodes. It can get confusing quickly to do so.
return undefined;
}
accumulator.addNode(node);
const tags = ts.getJSDocTags(node);
// Process azsdk tags. This function returns the summary tag if it was found and also inserts @azsdk-<name>
// tags into the azSdkTags object.
summary ??= extractAzSdkTags(tags, relativeSourcePath, node, sourceFile, azSdkTags);
return ts.visitEachChild(node, visitor, context);
};
return addCommonJsExports(context, ts.visitNode(sourceFile, visitor), accumulator.exports);
};
// Where the work happens. This runs the conversion step from the ts-to-js command with the visitor we've defined
// above and the CommonJS transforms (see transforms.ts).
const jsModuleText = convert(sourceText, {
fileName: source,
transformers: {
before: [sourceProcessor],
after: [toCommonJs],
},
});
// Check the imports for any relative module imports (these could be util files), and compute a relative path to the
// module from the source directory
for (const relativeModule of accumulator.importedModules
.filter(isRelativePath)
.map((modulePath) =>
path.normalize(path.join(path.dirname(relativeSourcePath), modulePath))
)) {
importedRelativeModules.add(relativeModule);
}
return {
filePath: source,
relativeSourcePath,
text: sourceText,
jsModuleText,
summary,
importedModules: accumulator.importedModules.filter(isDependency),
usedEnvironmentVariables: accumulator.usedEnvironmentVariables,
azSdkTags,
};
});
return Promise.all(jobs).then((results) => {
// Only fail once at the end, so that we don't drown you with tons of red messages.
// Think of this whole *then* continuation as a validation pass.
if (hadUnsupportedSyntax) {
fail(
"Samples must support the latest Node LTS well. See the errors above for more information."
);
}
for (const result of results) {
if (
result.summary === undefined &&
!importedRelativeModules.has(result.relativeSourcePath.replace(/\.ts$/, "")) &&
!result.azSdkTags.util
) {
fail(
`${result.relativeSourcePath} does not include an @summary tag, is not imported by any other module, and is not marked as a util (using @azsdk-util true).`
);
}
}
return results;
});
}
function isImportOrStaticRequire(node: ts.Node): node is ts.ImportDeclaration | ts.CallExpression {
return (
ts.isImportDeclaration(node) ||
(ts.isCallExpression(node) &&
((ts.isIdentifier(node.expression) && node.expression.text === "require") ||
node.expression.kind === ts.SyntaxKind.ImportKeyword) &&
ts.isStringLiteralLike(node.arguments[0]))
);
}
/**
* Detects usage of environment variables.
*
* This can _only_ work with property access expressions where the left hand side is a node that has the exact text
*
* "process.env"
*
* For example, it won't work with process["env"], and it won't work if process is bound to another name. It will _only_
* work with:
*
* - `process.env.NAME`
* - `process.env["NAME"]`
*
* @param node - the node to test
* @param sourceFile - the source file where the node appears
* @returns true if the node appears to be a process.env access.
*/
function isProcessEnvAccess(
node: ts.Node,
sourceFile?: ts.SourceFile
): node is ts.PropertyAccessExpression | ts.ElementAccessExpression {
return (
(ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) &&
// This is cheating a bit, but it will work and doesn't require us to test the node any deeper
node.expression.getText(sourceFile) === "process.env"
);
}
/**
* Look for Azure SDK JSDoc tags and add them to an object, and extract the value of the `summary` tag.
*
* @param tags - JSDoc tags of a node
* @param relativeSourcePath - the relative source path of the file
* @param node - the node where the tags come from (used for debug output)
* @param sourceFile - the source file
* @param azSdkTags - an object to enter azsdk tags into
* @returns the summary tag's value or undefined if none was found
*/
function extractAzSdkTags(
tags: readonly ts.JSDocTag[],
relativeSourcePath: string,
node: ts.Node,
sourceFile: ts.SourceFile,
azSdkTags: AzSdkMetaTags
): string | undefined {
let summary: string | undefined;
for (const tag of tags) {
log.debug(`File ${relativeSourcePath} has tag ${tag.tagName.text}`);
// New TS introduced comment: NodeArray, so we join the text if it is made of many nodes.
const comment = Array.isArray(tag.comment)
? tag.comment.map((node: ts.JSDocText) => node.text ?? " ").join(" ")
: (tag.comment as string | undefined);
if (tag.tagName.text === "summary") {
log.debug("Found summary tag on node:", node.getText(sourceFile));
// Replace is required due to multi-line splitting messing with table formatting
summary = comment?.replace(/\s*\r?\n\s*/g, " ");
} else if (tag.tagName.text.startsWith(`${AZSDK_META_TAG_PREFIX}`)) {
// We ran into an `azsdk` directive in the metadata
const metaTag = tag.tagName.text.replace(
new RegExp(`^${AZSDK_META_TAG_PREFIX}`),
""
) as keyof AzSdkMetaTags;
log.debug(`File ${relativeSourcePath} has azsdk tag ${tag.tagName.text}`);
if (VALID_AZSDK_META_TAGS.includes(metaTag)) {
const trimmedComment = comment?.trim();
// If there was _no_ comment, then we can assume it is a boolean tag
// and so being specified at all is an indication that we should use
// `true`
azSdkTags[metaTag as keyof AzSdkMetaTags] = trimmedComment
? JSON.parse(trimmedComment)
: true;
} else {
log.warn(`Invalid azsdk tag ${metaTag}. Valid tags include ${VALID_AZSDK_META_TAGS}`);
}
}
}
return summary;
}
/**
* Adds a node to the end of a source file containing a CommonJS module.exports = block.
*
* @param context - transformation context from the compiler API
* @param sourceFile - the source file to process
* @param exports - a list of exported symbols in the file
* @returns the updated SourceFile node
*/
function addCommonJsExports(
context: ts.TransformationContext,
sourceFile: ts.SourceFile,
exports: string[]
): ts.SourceFile {
log.debug("Adding exports:", exports);
const factory = context.factory;
const exportEntries: ts.ObjectLiteralElementLike[] = exports.map((name) =>
factory.createShorthandPropertyAssignment(name)
);
const transformedOriginalStatements = processExportDefault(sourceFile, factory, exportEntries);
if (exportEntries.length > 0) {
transformedOriginalStatements.push(
factory.createEmptyStatement(),
// module.exports = { ... }
factory.createExpressionStatement(
factory.createAssignment(
factory.createPropertyAccessExpression(
factory.createIdentifier("module"),
factory.createIdentifier("exports")
),
factory.createObjectLiteralExpression(exportEntries)
)
)
);
}
return factory.updateSourceFile(sourceFile, transformedOriginalStatements);
}
/**
* Handles `export default` modifiers.
*
* Default exports in the TypeScript compiler are actually handled very strangely. As a consequence, we can only handle
* `export default function` and `export default class` (as these are just ordinary function/class declarations with an
* `export` modifier and a `default` modifier at the surface level). Something like `export default {}` is actually a
* different kind of syntax node: ExportAssignment (the same kind as an `export =` statement). ExportAssignment
* statements are rejected outright by the sample tool, so we only need to consider `export default function` and
* `export default class`
*
* @param sourceFile - the source file to process
* @param factory - a context-bound NodeFactory
* @param exportEntries - a list to add the new default property assignments to
* @returns a new list of statements for the source file
*/
function processExportDefault(
sourceFile: ts.SourceFile,
factory: ts.NodeFactory,
exportEntries: ts.ObjectLiteralElementLike[]
): ts.Statement[] {
return sourceFile.statements.map((statement) => {
const isDefault =
statement.modifiers?.some(({ kind }) => kind === ts.SyntaxKind.DefaultKeyword) &&
statement.modifiers.some(({ kind }) => kind === ts.SyntaxKind.ExportKeyword);
if (!isDefault) {
return statement;
}
// The only forms that can have `export default` modifiers are the following.
const decl = statement as ts.FunctionDeclaration | ts.ClassDeclaration;
const updatedModifiers = decl.modifiers?.filter(
({ kind }) => kind !== ts.SyntaxKind.DefaultKeyword && kind !== ts.SyntaxKind.ExportKeyword
);
if (!decl.name) {
// If there is no name, the declaration is anonymous, and we will bind it as an expression in module.exports
const initializer = ts.isClassDeclaration(decl)
? factory.createClassExpression(
decl.decorators,
updatedModifiers,
undefined,
decl.typeParameters,
decl.heritageClauses,
decl.members
)
: decl.body === undefined // This is a strange case that I assume has to do with overload declarations.
? undefined
: factory.createFunctionExpression(
updatedModifiers,
decl.asteriskToken,
undefined,
decl.typeParameters,
decl.parameters,
decl.type,
decl.body
);
if (initializer) {
exportEntries.push(factory.createPropertyAssignment("default", initializer));
}
return factory.createEmptyStatement();
}
exportEntries.push(factory.createPropertyAssignment("default", decl.name));
return ts.isClassDeclaration(decl)
? factory.updateClassDeclaration(
decl,
decl.decorators,
updatedModifiers,
decl.name,
decl.typeParameters,
decl.heritageClauses,
decl.members
)
: factory.updateFunctionDeclaration(
decl,
decl.decorators,
updatedModifiers,
decl.asteriskToken,
decl.name,
decl.typeParameters,
decl.parameters,
decl.type,
decl.body
);
});
} | the_stack |
import * as assert from 'assert';
import * as fs from 'fs';
import * as sinon from 'sinon';
import { PassThrough } from 'stream';
import appInsights from '../../../../appInsights';
import auth from '../../../../Auth';
import { Logger } from '../../../../cli';
import Command, { CommandError } from '../../../../Command';
import request from '../../../../request';
import commands from '../../commands';
import { sinonUtil } from '../../../../utils/sinonUtil';
const command: Command = require('./app-teamspackage-download');
describe(commands.APP_TEAMSPACKAGE_DOWNLOAD, () => {
let log: string[];
let logger: Logger;
before(() => {
sinon.stub(auth, 'restoreAuth').callsFake(() => Promise.resolve());
sinon.stub(appInsights, 'trackEvent').callsFake(() => { });
auth.service.connected = true;
auth.service.spoUrl = 'https://contoso.sharepoint.com';
});
beforeEach(() => {
log = [];
logger = {
log: (msg: string) => {
log.push(msg);
},
logRaw: (msg: string) => {
log.push(msg);
},
logToStderr: (msg: string) => {
log.push(msg);
}
};
});
afterEach(() => {
sinonUtil.restore([
request.get,
request.post,
fs.existsSync,
fs.createWriteStream
]);
});
after(() => {
sinonUtil.restore([
auth.restoreAuth,
appInsights.trackEvent
]);
auth.service.connected = false;
auth.service.spoUrl = undefined;
});
it('has correct name', () => {
assert.strictEqual(command.name.startsWith(commands.APP_TEAMSPACKAGE_DOWNLOAD), true);
});
it('has a description', () => {
assert.notStrictEqual(command.description, null);
});
it('downloads Teams app package when appItemUniqueId specified', (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemByUniqueId('335a5612-3e85-462d-9d5b-c014b5abeac4')?$expand=File&$select=Id,File/Name`) {
return Promise.resolve({
"File": {
"Name": "m365-spfx-wellbeing.sppkg"
},
"Id": 2,
"ID": 2
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemUniqueId: '335a5612-3e85-462d-9d5b-c014b5abeac4' } }, (err) => {
try {
assert(fsStub.calledOnce);
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it('downloads Teams app package when appItemId specified', (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemById(2)?$expand=File&$select=File/Name`) {
return Promise.resolve({
"File": {
"Name": "m365-spfx-wellbeing.sppkg"
}
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemId: 2 } }, (err) => {
try {
assert(fsStub.calledOnce);
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it('downloads Teams app package when appItemId specified (debug)', (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemById(2)?$expand=File&$select=File/Name`) {
return Promise.resolve({
"File": {
"Name": "m365-spfx-wellbeing.sppkg"
}
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemId: 2, debug: true } }, (err) => {
try {
assert(fsStub.calledOnce);
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it('downloads Teams app package when appName specified', (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/getfolderbyserverrelativeurl('AppCatalog')/files('m365-spfx-wellbeing.sppkg')/ListItemAllFields?$select=Id`) {
return Promise.resolve({
"Id": 2,
"ID": 2
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appName: 'm365-spfx-wellbeing.sppkg' } }, (err) => {
try {
assert(fsStub.calledOnce);
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it('saves the downloaded Teams package to file with name following the .sppkg file', (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/getfolderbyserverrelativeurl('AppCatalog')/files('m365-spfx-wellbeing.sppkg')/ListItemAllFields?$select=Id`) {
return Promise.resolve({
"Id": 2,
"ID": 2
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appName: 'm365-spfx-wellbeing.sppkg' } }, (err) => {
try {
assert(fsStub.calledWith('m365-spfx-wellbeing.zip'));
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it('saves the app package downloaded using appItemUniqueId to the specified file', (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemByUniqueId('335a5612-3e85-462d-9d5b-c014b5abeac4')?$expand=File&$select=Id,File/Name`) {
return Promise.resolve({
"File": {
"Name": "m365-spfx-wellbeing.sppkg"
},
"Id": 2,
"ID": 2
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemUniqueId: '335a5612-3e85-462d-9d5b-c014b5abeac4', fileName: 'package.zip' } }, (err) => {
try {
assert(fsStub.calledWith('package.zip'));
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it('saves the app package downloaded using appItemId to the specified file', (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemById(2)?$expand=File&$select=File/Name`) {
return Promise.resolve({
"File": {
"Name": "m365-spfx-wellbeing.sppkg"
}
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemId: 2, fileName: 'package.zip' } }, (err) => {
try {
assert(fsStub.calledWith('package.zip'));
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it('saves the app package downloaded using appName to the specified file', (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/getfolderbyserverrelativeurl('AppCatalog')/files('m365-spfx-wellbeing.sppkg')/ListItemAllFields?$select=Id`) {
return Promise.resolve({
"Id": 2,
"ID": 2
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appName: 'm365-spfx-wellbeing.sppkg', fileName: 'package.zip' } }, (err) => {
try {
assert(fsStub.calledWith('package.zip'));
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it(`doesn't detect app catalog URL when specified`, (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
const fsStub = sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('close');
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemById(2)?$expand=File&$select=File/Name`) {
return Promise.resolve({
"File": {
"Name": "m365-spfx-wellbeing.sppkg"
}
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemId: 2, appCatalogUrl: 'https://contoso.sharepoint.com/sites/appcatalog' } }, (err) => {
try {
assert(fsStub.calledOnce);
assert.strictEqual(err, undefined);
done();
}
catch (e) {
done(e);
}
});
});
it(`handles error when the specified app catalog doesn't exist`, (done) => {
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/getfolderbyserverrelativeurl('AppCatalog')/files('m365-spfx-wellbeing.sppkg')/ListItemAllFields?$select=Id`) {
return Promise.reject('404 FILE NOT FOUND');
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appName: 'm365-spfx-wellbeing.sppkg', appCatalogUrl: 'https://contoso.sharepoint.com/sites/appcatalog' } }, (err) => {
try {
assert.strictEqual(JSON.stringify(err), JSON.stringify(new CommandError(`404 FILE NOT FOUND`)));
done();
}
catch (e) {
done(e);
}
});
});
it(`handles error when the specified appItemUniqueId doesn't exist`, (done) => {
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemByUniqueId('335a5612-3e85-462d-9d5b-c014b5abeac4')?$expand=File&$select=Id,File/Name`) {
return Promise.reject({
error: {
"odata.error": {
"code": "-2147024809, System.ArgumentException",
"message": {
"lang": "en-US",
"value": "Value does not fall within the expected range."
}
}
}
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemUniqueId: '335a5612-3e85-462d-9d5b-c014b5abeac4' } }, (err) => {
try {
assert.strictEqual(JSON.stringify(err), JSON.stringify(new CommandError(`Value does not fall within the expected range.`)));
done();
}
catch (e) {
done(e);
}
});
});
it(`handles error when the specified appItemId doesn't exist`, (done) => {
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemById(2)?$expand=File&$select=File/Name`) {
return Promise.reject({
error: {
"odata.error": {
"code": "-2147024809, System.ArgumentException",
"message": {
"lang": "en-US",
"value": "Item does not exist. It may have been deleted by another user."
}
}
}
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemId: 2 } }, (err) => {
try {
assert.strictEqual(JSON.stringify(err), JSON.stringify(new CommandError('Item does not exist. It may have been deleted by another user.')));
done();
}
catch (e) {
done(e);
}
});
});
it(`handles error when the specified appName doesn't exist`, (done) => {
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/getfolderbyserverrelativeurl('AppCatalog')/files('m365-spfx-wellbeing.sppkg')/ListItemAllFields?$select=Id`) {
return Promise.reject({
error: {
"odata.error": {
"code": "-2147024894, System.IO.FileNotFoundException",
"message": {
"lang": "en-US",
"value": "File Not Found."
}
}
}
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appName: 'm365-spfx-wellbeing.sppkg' } }, (err) => {
try {
assert.strictEqual(JSON.stringify(err), JSON.stringify(new CommandError('File Not Found.')));
done();
}
catch (e) {
done(e);
}
});
});
it(`handles error when the package doesn't support syncing to Teams`, (done) => {
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemById(2)?$expand=File&$select=File/Name`) {
return Promise.resolve({
"File": {
"Name": "m365-spfx-wellbeing.sppkg"
}
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.reject('Request failed with status code 404');
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemId: 2 } }, (err) => {
try {
assert.strictEqual(JSON.stringify(err), JSON.stringify(new CommandError('Request failed with status code 404')));
done();
}
catch (e) {
done(e);
}
});
});
it(`handles error when saving the package to file fails`, (done) => {
const mockResponse = `{"data": 123}`;
const responseStream = new PassThrough();
responseStream.write(mockResponse);
responseStream.end(); //Mark that we pushed all the data.
const writeStream = new PassThrough();
sinon.stub(fs, 'createWriteStream').returns(writeStream as any);
setTimeout(() => {
writeStream.emit('error', "An error has occurred");
}, 5);
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://contoso.sharepoint.com/_api/SP_TenantSettings_Current`) {
return Promise.resolve({ "CorporateCatalogUrl": "https://contoso.sharepoint.com/sites/appcatalog" });
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/GetList('/sites/appcatalog/AppCatalog')/GetItemById(2)?$expand=File&$select=File/Name`) {
return Promise.resolve({
"File": {
"Name": "m365-spfx-wellbeing.sppkg"
}
});
}
if (opts.url === `https://contoso.sharepoint.com/sites/appcatalog/_api/web/tenantappcatalog/downloadteamssolution(2)/$value`) {
return Promise.resolve({
data: responseStream
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { appItemId: 2 } }, (err) => {
try {
assert.strictEqual(JSON.stringify(err), JSON.stringify(new CommandError('An error has occurred')));
done();
}
catch (e) {
done(e);
}
});
});
it('fails validation if the appCatalogUrl option is not a valid SharePoint site URL', () => {
const actual = command.validate({ options: { appItemId: 1, appCatalogUrl: 'foo' } });
assert.notStrictEqual(actual, true);
});
it('passes validation when the appCatalogUrl is a valid SharePoint URL', () => {
const actual = command.validate({ options: { appItemId: 1, appCatalogUrl: 'https://contoso.sharepoint.com/sites/appcatalog' } });
assert.strictEqual(actual, true);
});
it('passes validation when the appCatalogUrl is not specified', () => {
const actual = command.validate({ options: { appItemId: 1 } });
assert.strictEqual(actual, true);
});
it('fails validation when the appItemId is not a number', () => {
const actual = command.validate({ options: { appItemId: 'a' } });
assert.notStrictEqual(actual, true);
});
it('passes validation when the appItemId is a number', () => {
const actual = command.validate({ options: { appItemId: 1 } });
assert.strictEqual(actual, true);
});
it('fails validation when the appItemUniqueId is not a GUID', () => {
const actual = command.validate({ options: { appItemUniqueId: 'a' } });
assert.notStrictEqual(actual, true);
});
it('passes validation when the appItemUniqueId is a GUID', () => {
const actual = command.validate({ options: { appItemUniqueId: '335a5612-3e85-462d-9d5b-c014b5abeac4' } });
assert.strictEqual(actual, true);
});
it('fails validation when the specified file already exists', () => {
sinon.stub(fs, 'existsSync').callsFake(() => true);
const actual = command.validate({ options: { appItemId: 1, fileName: 'file.zip' } });
assert.notStrictEqual(actual, true);
});
it('passes validation when the specified file does not exist', () => {
sinon.stub(fs, 'existsSync').callsFake(() => false);
const actual = command.validate({ options: { appItemId: 1, fileName: 'file.zip' } });
assert.strictEqual(actual, true);
});
it('fails validation when the appItemUniqueId and appItemId specified', () => {
const actual = command.validate({ options: { appItemUniqueId: '335a5612-3e85-462d-9d5b-c014b5abeac4', appItemId: 1 } });
assert.notStrictEqual(actual, true);
});
it('fails validation when the appItemUniqueId and appName specified', () => {
const actual = command.validate({ options: { appItemUniqueId: '335a5612-3e85-462d-9d5b-c014b5abeac4', appName: 'app.sppkg' } });
assert.notStrictEqual(actual, true);
});
it('fails validation when the appItemId and appName specified', () => {
const actual = command.validate({ options: { appItemId: 1, appName: 'app.sppkg' } });
assert.notStrictEqual(actual, true);
});
it('fails validation when no app identifier specified', () => {
const actual = command.validate({ options: {} });
assert.notStrictEqual(actual, true);
});
it('supports debug mode', () => {
const options = command.options();
let containsDebugOption = false;
options.forEach(o => {
if (o.option === '--debug') {
containsDebugOption = true;
}
});
assert(containsDebugOption);
});
}); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [storagegateway](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonstoragegateway.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Storagegateway extends PolicyStatement {
public servicePrefix = 'storagegateway';
/**
* Statement provider for service [storagegateway](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonstoragegateway.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to activate the gateway you previously deployed on your host
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ActivateGateway.html
*/
public toActivateGateway() {
return this.to('ActivateGateway');
}
/**
* Grants permission to configure one or more gateway local disks as cache for a cached-volume gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AddCache.html
*/
public toAddCache() {
return this.to('AddCache');
}
/**
* Grants permission to add one or more tags to the specified resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AddTagsToResource.html
*/
public toAddTagsToResource() {
return this.to('AddTagsToResource');
}
/**
* Grants permission to configure one or more gateway local disks as upload buffer for a specified gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AddUploadBuffer.html
*/
public toAddUploadBuffer() {
return this.to('AddUploadBuffer');
}
/**
* Grants permission to configure one or more gateway local disks as working storage for a gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AddWorkingStorage.html
*/
public toAddWorkingStorage() {
return this.to('AddWorkingStorage');
}
/**
* Grants permission to move a tape to the target pool specified
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AssignTapePool.html
*/
public toAssignTapePool() {
return this.to('AssignTapePool');
}
/**
* Grants permission to associate an Amazon FSx file system with the Amazon FSx file gateway
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AssociateFileSystem.html
*/
public toAssociateFileSystem() {
return this.to('AssociateFileSystem');
}
/**
* Grants permission to connect a volume to an iSCSI connection and then attaches the volume to the specified gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AttachVolume.html
*/
public toAttachVolume() {
return this.to('AttachVolume');
}
/**
* Grants permission to allow the governance retention lock on a pool to be bypassed
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/CreatingCustomTapePool.html#TapeRetentionLock
*/
public toBypassGovernanceRetention() {
return this.to('BypassGovernanceRetention');
}
/**
* Grants permission to cancel archiving of a virtual tape to the virtual tape shelf (VTS) after the archiving process is initiated
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CancelArchival.html
*/
public toCancelArchival() {
return this.to('CancelArchival');
}
/**
* Grants permission to cancel retrieval of a virtual tape from the virtual tape shelf (VTS) to a gateway after the retrieval process is initiated
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CancelRetrieval.html
*/
public toCancelRetrieval() {
return this.to('CancelRetrieval');
}
/**
* Grants permission to create a cached volume on a specified cached gateway. This operation is supported only for the gateway-cached volume architecture
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateCachediSCSIVolume.html
*/
public toCreateCachediSCSIVolume() {
return this.to('CreateCachediSCSIVolume');
}
/**
* Grants permission to create a NFS file share on an existing file gateway
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateNFSFileShare.html
*/
public toCreateNFSFileShare() {
return this.to('CreateNFSFileShare');
}
/**
* Grants permission to create a SMB file share on an existing file gateway
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateSMBFileShare.html
*/
public toCreateSMBFileShare() {
return this.to('CreateSMBFileShare');
}
/**
* Grants permission to initiate a snapshot of a volume
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateSnapshot.html
*/
public toCreateSnapshot() {
return this.to('CreateSnapshot');
}
/**
* Grants permission to initiate a snapshot of a gateway from a volume recovery point
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateSnapshotFromVolumeRecoveryPoint.html
*/
public toCreateSnapshotFromVolumeRecoveryPoint() {
return this.to('CreateSnapshotFromVolumeRecoveryPoint');
}
/**
* Grants permission to create a volume on a specified gateway
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateStorediSCSIVolume.html
*/
public toCreateStorediSCSIVolume() {
return this.to('CreateStorediSCSIVolume');
}
/**
* Grants permission to create a tape pool
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateTapePool.html
*/
public toCreateTapePool() {
return this.to('CreateTapePool');
}
/**
* Grants permission to create a virtual tape by using your own barcode
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateTapeWithBarcode.html
*/
public toCreateTapeWithBarcode() {
return this.to('CreateTapeWithBarcode');
}
/**
* Grants permission to create one or more virtual tapes. You write data to the virtual tapes and then archive the tapes
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateTapes.html
*/
public toCreateTapes() {
return this.to('CreateTapes');
}
/**
* Grants permission to delete the automatic tape creation policy configured on a gateway-VTL
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteAutomaticTapeCreationPolicy.html
*/
public toDeleteAutomaticTapeCreationPolicy() {
return this.to('DeleteAutomaticTapeCreationPolicy');
}
/**
* Grants permission to delete the bandwidth rate limits of a gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteBandwidthRateLimit.html
*/
public toDeleteBandwidthRateLimit() {
return this.to('DeleteBandwidthRateLimit');
}
/**
* Grants permission to delete Challenge-Handshake Authentication Protocol (CHAP) credentials for a specified iSCSI target and initiator pair
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteChapCredentials.html
*/
public toDeleteChapCredentials() {
return this.to('DeleteChapCredentials');
}
/**
* Grants permission to delete a file share from a file gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteFileShare.html
*/
public toDeleteFileShare() {
return this.to('DeleteFileShare');
}
/**
* Grants permission to delete a gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteGateway.html
*/
public toDeleteGateway() {
return this.to('DeleteGateway');
}
/**
* Grants permission to delete a snapshot of a volume
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteSnapshotSchedule.html
*/
public toDeleteSnapshotSchedule() {
return this.to('DeleteSnapshotSchedule');
}
/**
* Grants permission to delete the specified virtual tape
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteTape.html
*/
public toDeleteTape() {
return this.to('DeleteTape');
}
/**
* Grants permission to delete the specified virtual tape from the virtual tape shelf (VTS)
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteTapeArchive.html
*/
public toDeleteTapeArchive() {
return this.to('DeleteTapeArchive');
}
/**
* Grants permission to delete the specified tape pool
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteTapePool.html
*/
public toDeleteTapePool() {
return this.to('DeleteTapePool');
}
/**
* Grants permission to delete the specified gateway volume that you previously created using the CreateCachediSCSIVolume or CreateStorediSCSIVolume API
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteVolume.html
*/
public toDeleteVolume() {
return this.to('DeleteVolume');
}
/**
* Grants permission to get the information about the most recent high availability monitoring test that was performed on the gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeAvailabilityMonitorTest.html
*/
public toDescribeAvailabilityMonitorTest() {
return this.to('DescribeAvailabilityMonitorTest');
}
/**
* Grants permission to get the bandwidth rate limits of a gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeBandwidthRateLimit.html
*/
public toDescribeBandwidthRateLimit() {
return this.to('DescribeBandwidthRateLimit');
}
/**
* Grants permission to get the bandwidth rate limit schedule of a gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeBandwidthRateLimitSchedule.html
*/
public toDescribeBandwidthRateLimitSchedule() {
return this.to('DescribeBandwidthRateLimitSchedule');
}
/**
* Grants permission to get information about the cache of a gateway. This operation is supported only for the gateway-cached volume architecture
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeCache.html
*/
public toDescribeCache() {
return this.to('DescribeCache');
}
/**
* Grants permission to get a description of the gateway volumes specified in the request. This operation is supported only for the gateway-cached volume architecture
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeCachediSCSIVolumes.html
*/
public toDescribeCachediSCSIVolumes() {
return this.to('DescribeCachediSCSIVolumes');
}
/**
* Grants permission to get an array of Challenge-Handshake Authentication Protocol (CHAP) credentials information for a specified iSCSI target, one for each target-initiator pair
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeChapCredentials.html
*/
public toDescribeChapCredentials() {
return this.to('DescribeChapCredentials');
}
/**
* Grants permission to get a description for one or more file system associations
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeFileSystemAssociations.html
*/
public toDescribeFileSystemAssociations() {
return this.to('DescribeFileSystemAssociations');
}
/**
* Grants permission to get metadata about a gateway such as its name, network interfaces, configured time zone, and the state (whether the gateway is running or not)
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeGatewayInformation.html
*/
public toDescribeGatewayInformation() {
return this.to('DescribeGatewayInformation');
}
/**
* Grants permission to get your gateway's weekly maintenance start time including the day and time of the week
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeMaintenanceStartTime.html
*/
public toDescribeMaintenanceStartTime() {
return this.to('DescribeMaintenanceStartTime');
}
/**
* Grants permission to get a description for one or more file shares from a file gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeNFSFileShares.html
*/
public toDescribeNFSFileShares() {
return this.to('DescribeNFSFileShares');
}
/**
* Grants permission to get a description for one or more file shares from a file gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeSMBFileShares.html
*/
public toDescribeSMBFileShares() {
return this.to('DescribeSMBFileShares');
}
/**
* Grants permission to get a description of a Server Message Block (SMB) file share settings from a file gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeSMBSettings.html
*/
public toDescribeSMBSettings() {
return this.to('DescribeSMBSettings');
}
/**
* Grants permission to describe the snapshot schedule for the specified gateway volume
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeSnapshotSchedule.html
*/
public toDescribeSnapshotSchedule() {
return this.to('DescribeSnapshotSchedule');
}
/**
* Grants permission to get the description of the gateway volumes specified in the request
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeStorediSCSIVolumes.html
*/
public toDescribeStorediSCSIVolumes() {
return this.to('DescribeStorediSCSIVolumes');
}
/**
* Grants permission to get a description of specified virtual tapes in the virtual tape shelf (VTS)
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeTapeArchives.html
*/
public toDescribeTapeArchives() {
return this.to('DescribeTapeArchives');
}
/**
* Grants permission to get a list of virtual tape recovery points that are available for the specified gateway-VTL
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeTapeRecoveryPoints.html
*/
public toDescribeTapeRecoveryPoints() {
return this.to('DescribeTapeRecoveryPoints');
}
/**
* Grants permission to get a description of the specified Amazon Resource Name (ARN) of virtual tapes
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeTapes.html
*/
public toDescribeTapes() {
return this.to('DescribeTapes');
}
/**
* Grants permission to get information about the upload buffer of a gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeUploadBuffer.html
*/
public toDescribeUploadBuffer() {
return this.to('DescribeUploadBuffer');
}
/**
* Grants permission to get a description of virtual tape library (VTL) devices for the specified gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeVTLDevices.html
*/
public toDescribeVTLDevices() {
return this.to('DescribeVTLDevices');
}
/**
* Grants permission to get information about the working storage of a gateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeWorkingStorage.html
*/
public toDescribeWorkingStorage() {
return this.to('DescribeWorkingStorage');
}
/**
* Grants permission to disconnect a volume from an iSCSI connection and then detaches the volume from the specified gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DetachVolume.html
*/
public toDetachVolume() {
return this.to('DetachVolume');
}
/**
* Grants permission to disable a gateway when the gateway is no longer functioning
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DisableGateway.html
*/
public toDisableGateway() {
return this.to('DisableGateway');
}
/**
* Grants permission to disassociate an Amazon FSx file system from an Amazon FSx file gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DisassociateFileSystem.html
*/
public toDisassociateFileSystem() {
return this.to('DisassociateFileSystem');
}
/**
* Grants permission to enable you to join an Active Directory Domain
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_JoinDomain.html
*/
public toJoinDomain() {
return this.to('JoinDomain');
}
/**
* Grants permission to list the automatic tape creation policies configured on the specified gateway-VTL or all gateway-VTLs owned by your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListAutomaticTapeCreationPolicies.html
*/
public toListAutomaticTapeCreationPolicies() {
return this.to('ListAutomaticTapeCreationPolicies');
}
/**
* Grants permission to get a list of the file shares for a specific file gateway, or the list of file shares that belong to the calling user account
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListFileShares.html
*/
public toListFileShares() {
return this.to('ListFileShares');
}
/**
* Grants permission to get a list of the file system associations for the specified gateway
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListFileSystemAssociations.html
*/
public toListFileSystemAssociations() {
return this.to('ListFileSystemAssociations');
}
/**
* Grants permission to list gateways owned by an AWS account in a region specified in the request. The returned list is ordered by gateway Amazon Resource Name (ARN)
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListGateways.html
*/
public toListGateways() {
return this.to('ListGateways');
}
/**
* Grants permission to get a list of the gateway's local disks
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListLocalDisks.html
*/
public toListLocalDisks() {
return this.to('ListLocalDisks');
}
/**
* Grants permission to get the tags that have been added to the specified resource
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to list tape pools owned by your AWS account
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListTapePools.html
*/
public toListTapePools() {
return this.to('ListTapePools');
}
/**
* Grants permission to list virtual tapes in your virtual tape library (VTL) and your virtual tape shelf (VTS)
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListTapes.html
*/
public toListTapes() {
return this.to('ListTapes');
}
/**
* Grants permission to list iSCSI initiators that are connected to a volume
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListVolumeInitiators.html
*/
public toListVolumeInitiators() {
return this.to('ListVolumeInitiators');
}
/**
* Grants permission to list the recovery points for a specified gateway
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListVolumeRecoveryPoints.html
*/
public toListVolumeRecoveryPoints() {
return this.to('ListVolumeRecoveryPoints');
}
/**
* Grants permission to list the iSCSI stored volumes of a gateway
*
* Access Level: List
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListVolumes.html
*/
public toListVolumes() {
return this.to('ListVolumes');
}
/**
* Grants permission to send you a notification through CloudWatch Events when all files written to your NFS file share have been uploaded to Amazon S3
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_NotifyWhenUploaded.html
*/
public toNotifyWhenUploaded() {
return this.to('NotifyWhenUploaded');
}
/**
* Grants permission to refresh the cache for the specified file share
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_RefreshCache.html
*/
public toRefreshCache() {
return this.to('RefreshCache');
}
/**
* Grants permission to remove one or more tags from the specified resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_RemoveTagsFromResource.html
*/
public toRemoveTagsFromResource() {
return this.to('RemoveTagsFromResource');
}
/**
* Grants permission to reset all cache disks that have encountered a error and makes the disks available for reconfiguration as cache storage
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ResetCache.html
*/
public toResetCache() {
return this.to('ResetCache');
}
/**
* Grants permission to retrieve an archived virtual tape from the virtual tape shelf (VTS) to a gateway-VTL
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_RetrieveTapeArchive.html
*/
public toRetrieveTapeArchive() {
return this.to('RetrieveTapeArchive');
}
/**
* Grants permission to retrieve the recovery point for the specified virtual tape
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_RetrieveTapeRecoveryPoint.html
*/
public toRetrieveTapeRecoveryPoint() {
return this.to('RetrieveTapeRecoveryPoint');
}
/**
* Grants permission to set the password for your VM local console
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_SetLocalConsolePassword.html
*/
public toSetLocalConsolePassword() {
return this.to('SetLocalConsolePassword');
}
/**
* Grants permission to set the password for SMB Guest user
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_SetSMBGuestPassword.html
*/
public toSetSMBGuestPassword() {
return this.to('SetSMBGuestPassword');
}
/**
* Grants permission to shut down a gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ShutdownGateway.html
*/
public toShutdownGateway() {
return this.to('ShutdownGateway');
}
/**
* Grants permission to start a test that verifies that the specified gateway is configured for High Availability monitoring in your host environment
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_StartAvailabilityMonitorTest.html
*/
public toStartAvailabilityMonitorTest() {
return this.to('StartAvailabilityMonitorTest');
}
/**
* Grants permission to start a gateway that you previously shut down
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_StartGateway.html
*/
public toStartGateway() {
return this.to('StartGateway');
}
/**
* Grants permission to update the automatic tape creation policy configured on a gateway-VTL
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateAutomaticTapeCreationPolicy.html
*/
public toUpdateAutomaticTapeCreationPolicy() {
return this.to('UpdateAutomaticTapeCreationPolicy');
}
/**
* Grants permission to update the bandwidth rate limits of a gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateBandwidthRateLimit.html
*/
public toUpdateBandwidthRateLimit() {
return this.to('UpdateBandwidthRateLimit');
}
/**
* Grants permission to update the bandwidth rate limit schedule of a gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateBandwidthRateLimitSchedule.html
*/
public toUpdateBandwidthRateLimitSchedule() {
return this.to('UpdateBandwidthRateLimitSchedule');
}
/**
* Grants permission to update the Challenge-Handshake Authentication Protocol (CHAP) credentials for a specified iSCSI target
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateChapCredentials.html
*/
public toUpdateChapCredentials() {
return this.to('UpdateChapCredentials');
}
/**
* Grants permission to update a file system association
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateFileSystemAssociation.html
*/
public toUpdateFileSystemAssociation() {
return this.to('UpdateFileSystemAssociation');
}
/**
* Grants permission to update a gateway's metadata, which includes the gateway's name and time zone
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateGatewayInformation.html
*/
public toUpdateGatewayInformation() {
return this.to('UpdateGatewayInformation');
}
/**
* Grants permission to update the gateway virtual machine (VM) software
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateGatewaySoftwareNow.html
*/
public toUpdateGatewaySoftwareNow() {
return this.to('UpdateGatewaySoftwareNow');
}
/**
* Grants permission to update a gateway's weekly maintenance start time information, including day and time of the week. The maintenance time is the time in your gateway's time zone
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateMaintenanceStartTime.html
*/
public toUpdateMaintenanceStartTime() {
return this.to('UpdateMaintenanceStartTime');
}
/**
* Grants permission to update a NFS file share
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateNFSFileShare.html
*/
public toUpdateNFSFileShare() {
return this.to('UpdateNFSFileShare');
}
/**
* Grants permission to update a SMB file share
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateSMBFileShare.html
*/
public toUpdateSMBFileShare() {
return this.to('UpdateSMBFileShare');
}
/**
* Grants permission to update whether the shares on a gateway are visible in a net view or browse list
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateSMBFileShareVisibility.html
*/
public toUpdateSMBFileShareVisibility() {
return this.to('UpdateSMBFileShareVisibility');
}
/**
* Grants permission to update the SMB security strategy on a file gateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateSMBSecurityStrategy.html
*/
public toUpdateSMBSecurityStrategy() {
return this.to('UpdateSMBSecurityStrategy');
}
/**
* Grants permission to update a snapshot schedule configured for a gateway volume
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateSnapshotSchedule.html
*/
public toUpdateSnapshotSchedule() {
return this.to('UpdateSnapshotSchedule');
}
/**
* Grants permission to update the type of medium changer in a gateway-VTL
*
* Access Level: Write
*
* https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateVTLDeviceType.html
*/
public toUpdateVTLDeviceType() {
return this.to('UpdateVTLDeviceType');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"ActivateGateway",
"AddCache",
"AddUploadBuffer",
"AddWorkingStorage",
"AssignTapePool",
"AssociateFileSystem",
"AttachVolume",
"BypassGovernanceRetention",
"CancelArchival",
"CancelRetrieval",
"CreateCachediSCSIVolume",
"CreateNFSFileShare",
"CreateSMBFileShare",
"CreateSnapshot",
"CreateSnapshotFromVolumeRecoveryPoint",
"CreateStorediSCSIVolume",
"CreateTapePool",
"CreateTapeWithBarcode",
"CreateTapes",
"DeleteAutomaticTapeCreationPolicy",
"DeleteBandwidthRateLimit",
"DeleteChapCredentials",
"DeleteFileShare",
"DeleteGateway",
"DeleteSnapshotSchedule",
"DeleteTape",
"DeleteTapeArchive",
"DeleteTapePool",
"DeleteVolume",
"DetachVolume",
"DisableGateway",
"DisassociateFileSystem",
"JoinDomain",
"NotifyWhenUploaded",
"RefreshCache",
"ResetCache",
"RetrieveTapeArchive",
"RetrieveTapeRecoveryPoint",
"SetLocalConsolePassword",
"SetSMBGuestPassword",
"ShutdownGateway",
"StartAvailabilityMonitorTest",
"StartGateway",
"UpdateAutomaticTapeCreationPolicy",
"UpdateBandwidthRateLimit",
"UpdateBandwidthRateLimitSchedule",
"UpdateChapCredentials",
"UpdateFileSystemAssociation",
"UpdateGatewayInformation",
"UpdateGatewaySoftwareNow",
"UpdateMaintenanceStartTime",
"UpdateNFSFileShare",
"UpdateSMBFileShare",
"UpdateSMBFileShareVisibility",
"UpdateSMBSecurityStrategy",
"UpdateSnapshotSchedule",
"UpdateVTLDeviceType"
],
"Tagging": [
"AddTagsToResource",
"RemoveTagsFromResource"
],
"Read": [
"DescribeAvailabilityMonitorTest",
"DescribeBandwidthRateLimit",
"DescribeBandwidthRateLimitSchedule",
"DescribeCache",
"DescribeCachediSCSIVolumes",
"DescribeChapCredentials",
"DescribeFileSystemAssociations",
"DescribeGatewayInformation",
"DescribeMaintenanceStartTime",
"DescribeNFSFileShares",
"DescribeSMBFileShares",
"DescribeSMBSettings",
"DescribeSnapshotSchedule",
"DescribeStorediSCSIVolumes",
"DescribeTapeArchives",
"DescribeTapeRecoveryPoints",
"DescribeTapes",
"DescribeUploadBuffer",
"DescribeVTLDevices",
"DescribeWorkingStorage"
],
"List": [
"ListAutomaticTapeCreationPolicies",
"ListFileShares",
"ListFileSystemAssociations",
"ListGateways",
"ListLocalDisks",
"ListTagsForResource",
"ListTapePools",
"ListTapes",
"ListVolumeInitiators",
"ListVolumeRecoveryPoints",
"ListVolumes"
]
};
/**
* Adds a resource of type device to the statement
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/resource_vtl-devices.html
*
* @param gatewayId - Identifier for the gatewayId.
* @param vtldevice - Identifier for the vtldevice.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onDevice(gatewayId: string, vtldevice: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:storagegateway:${Region}:${Account}:gateway/${GatewayId}/device/${Vtldevice}';
arn = arn.replace('${GatewayId}', gatewayId);
arn = arn.replace('${Vtldevice}', vtldevice);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type fs-association to the statement
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/API_AssociateFileSystem.html
*
* @param fsaId - Identifier for the fsaId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onFsAssociation(fsaId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:storagegateway:${Region}:${Account}:fs-association/${FsaId}';
arn = arn.replace('${FsaId}', fsaId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type gateway to the statement
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/StorageGatewayConcepts.html
*
* @param gatewayId - Identifier for the gatewayId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onGateway(gatewayId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:storagegateway:${Region}:${Account}:gateway/${GatewayId}';
arn = arn.replace('${GatewayId}', gatewayId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type share to the statement
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/GettingStartedCreateFileShare.html
*
* @param shareId - Identifier for the shareId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onShare(shareId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:storagegateway:${Region}:${Account}:share/${ShareId}';
arn = arn.replace('${ShareId}', shareId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type tape to the statement
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/StorageGatewayConcepts.html#storage-gateway-vtl-concepts
*
* @param tapeBarcode - Identifier for the tapeBarcode.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onTape(tapeBarcode: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:storagegateway:${Region}:${Account}:tape/${TapeBarcode}';
arn = arn.replace('${TapeBarcode}', tapeBarcode);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type tapepool to the statement
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/CreatingCustomTapePool.html
*
* @param poolId - Identifier for the poolId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onTapepool(poolId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:storagegateway:${Region}:${Account}:tapepool/${PoolId}';
arn = arn.replace('${PoolId}', poolId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type target to the statement
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/GettingStartedCreateVolumes.html
*
* @param gatewayId - Identifier for the gatewayId.
* @param iscsiTarget - Identifier for the iscsiTarget.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onTarget(gatewayId: string, iscsiTarget: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:storagegateway:${Region}:${Account}:gateway/${GatewayId}/target/${IscsiTarget}';
arn = arn.replace('${GatewayId}', gatewayId);
arn = arn.replace('${IscsiTarget}', iscsiTarget);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type volume to the statement
*
* https://docs.aws.amazon.com/storagegateway/latest/userguide/StorageGatewayConcepts.html#volume-gateway-concepts
*
* @param gatewayId - Identifier for the gatewayId.
* @param volumeId - Identifier for the volumeId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onVolume(gatewayId: string, volumeId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:storagegateway:${Region}:${Account}:gateway/${GatewayId}/volume/${VolumeId}';
arn = arn.replace('${GatewayId}', gatewayId);
arn = arn.replace('${VolumeId}', volumeId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import "./release-details.scss";
import React, { Component } from "react";
import groupBy from "lodash/groupBy";
import type { IComputedValue } from "mobx";
import { computed, makeObservable, observable } from "mobx";
import { Link } from "react-router-dom";
import kebabCase from "lodash/kebabCase";
import type { HelmRelease, HelmReleaseDetails, HelmReleaseUpdateDetails, HelmReleaseUpdatePayload } from "../../../../common/k8s-api/endpoints/helm-releases.api";
import { HelmReleaseMenu } from "../release-menu";
import { Drawer, DrawerItem, DrawerTitle } from "../../drawer";
import { Badge } from "../../badge";
import { cssNames, stopPropagation } from "../../../utils";
import { Observer, observer } from "mobx-react";
import { Spinner } from "../../spinner";
import { Table, TableCell, TableHead, TableRow } from "../../table";
import { Button } from "../../button";
import { Notifications } from "../../notifications";
import type { ThemeStore } from "../../../themes/store";
import type { ApiManager } from "../../../../common/k8s-api/api-manager";
import { SubTitle } from "../../layout/sub-title";
import { Checkbox } from "../../checkbox";
import { MonacoEditor } from "../../monaco-editor";
import type { IAsyncComputed } from "@ogre-tools/injectable-react";
import { withInjectables } from "@ogre-tools/injectable-react";
import createUpgradeChartTabInjectable from "../../dock/upgrade-chart/create-upgrade-chart-tab.injectable";
import updateReleaseInjectable from "../update-release/update-release.injectable";
import releaseInjectable from "./release.injectable";
import releaseDetailsInjectable from "./release-details.injectable";
import releaseValuesInjectable from "./release-values.injectable";
import userSuppliedValuesAreShownInjectable from "./user-supplied-values-are-shown.injectable";
import { KubeObjectAge } from "../../kube-object/age";
import type { KubeJsonApiData } from "../../../../common/k8s-api/kube-json-api";
import { entries } from "../../../../common/utils/objects";
import themeStoreInjectable from "../../../themes/store.injectable";
import type { GetDetailsUrl } from "../../kube-detail-params/get-details-url.injectable";
import apiManagerInjectable from "../../../../common/k8s-api/api-manager/manager.injectable";
import getDetailsUrlInjectable from "../../kube-detail-params/get-details-url.injectable";
export interface ReleaseDetailsProps {
hideDetails(): void;
}
interface Dependencies {
release: IComputedValue<HelmRelease | null | undefined>;
releaseDetails: IAsyncComputed<HelmReleaseDetails>;
releaseValues: IAsyncComputed<string>;
updateRelease: (name: string, namespace: string, payload: HelmReleaseUpdatePayload) => Promise<HelmReleaseUpdateDetails>;
createUpgradeChartTab: (release: HelmRelease) => void;
userSuppliedValuesAreShown: { toggle: () => void; value: boolean };
themeStore: ThemeStore;
apiManager: ApiManager;
getDetailsUrl: GetDetailsUrl;
}
@observer
class NonInjectedReleaseDetails extends Component<ReleaseDetailsProps & Dependencies> {
@observable saving = false;
private nonSavedValues = "";
constructor(props: ReleaseDetailsProps & Dependencies) {
super(props);
makeObservable(this);
}
@computed get details() {
return this.props.releaseDetails.value.get();
}
updateValues = async (release: HelmRelease) => {
const name = release.getName();
const namespace = release.getNs();
const data = {
chart: release.getChart(),
repo: await release.getRepo(),
version: release.getVersion(),
values: this.nonSavedValues,
};
this.saving = true;
try {
await this.props.updateRelease(name, namespace, data);
Notifications.ok(
<p>
Release
<b>{name}</b>
{" successfully updated!"}
</p>,
);
this.props.releaseValues.invalidate();
} catch (err) {
Notifications.checkedError(err, "Unknown error occured while updating release");
}
this.saving = false;
};
upgradeVersion = (release: HelmRelease) => {
const { hideDetails, createUpgradeChartTab } = this.props;
createUpgradeChartTab(release);
hideDetails();
};
renderValues(release: HelmRelease) {
return (
<Observer>
{() => {
const { saving } = this;
const releaseValuesArePending =
this.props.releaseValues.pending.get();
this.nonSavedValues = this.props.releaseValues.value.get();
return (
<div className="values">
<DrawerTitle>Values</DrawerTitle>
<div className="flex column gaps">
<Checkbox
label="User-supplied values only"
value={this.props.userSuppliedValuesAreShown.value}
onChange={this.props.userSuppliedValuesAreShown.toggle}
disabled={releaseValuesArePending}
/>
<MonacoEditor
style={{ minHeight: 300 }}
value={this.nonSavedValues}
onChange={(text) => (this.nonSavedValues = text)}
/>
<Button
primary
label="Save"
waiting={saving}
disabled={releaseValuesArePending}
onClick={() => this.updateValues(release)}
/>
</div>
</div>
);
}}
</Observer>
);
}
renderNotes() {
if (!this.details.info?.notes) return null;
const { notes } = this.details.info;
return (
<div className="notes">
{notes}
</div>
);
}
renderResources(resources: KubeJsonApiData[]) {
const { apiManager, getDetailsUrl } = this.props;
return (
<div className="resources">
{
entries(groupBy(resources, item => item.kind))
.map(([kind, items]) => (
<React.Fragment key={kind}>
<SubTitle title={kind} />
<Table scrollable={false}>
<TableHead sticky={false}>
<TableCell className="name">Name</TableCell>
{items[0].metadata.namespace && <TableCell className="namespace">Namespace</TableCell>}
<TableCell className="age">Age</TableCell>
</TableHead>
{items.map(item => {
const { name, namespace, uid } = item.metadata;
const api = apiManager.getApi(api => api.kind === kind && api.apiVersionWithGroup == item.apiVersion);
const detailsUrl = api ? getDetailsUrl(api.getUrl({ name, namespace })) : "";
return (
<TableRow key={uid}>
<TableCell className="name">
{detailsUrl ? <Link to={detailsUrl}>{name}</Link> : name}
</TableCell>
{namespace && (
<TableCell className="namespace">
{namespace}
</TableCell>
)}
<TableCell className="age">
<KubeObjectAge key="age" object={item} />
</TableCell>
</TableRow>
);
})}
</Table>
</React.Fragment>
))
}
</div>
);
}
renderContent(release: HelmRelease) {
if (!this.details) {
return <Spinner center/>;
}
const { resources } = this.details;
return (
<div>
<DrawerItem name="Chart" className="chart">
<div className="flex gaps align-center">
<span>{release.getChart()}</span>
<Button
primary
label="Upgrade"
className="box right upgrade"
onClick={() => this.upgradeVersion(release)}
/>
</div>
</DrawerItem>
<DrawerItem name="Updated">
{release.getUpdated()}
{` ago (${release.updated})`}
</DrawerItem>
<DrawerItem name="Namespace">
{release.getNs()}
</DrawerItem>
<DrawerItem name="Version" onClick={stopPropagation}>
<div className="version flex gaps align-center">
<span>
{release.getVersion()}
</span>
</div>
</DrawerItem>
<DrawerItem
name="Status"
className="status"
labelsOnly
>
<Badge
label={release.getStatus()}
className={kebabCase(release.getStatus())}
/>
</DrawerItem>
{this.renderValues(release)}
<DrawerTitle>Notes</DrawerTitle>
{this.renderNotes()}
<DrawerTitle>Resources</DrawerTitle>
{resources && this.renderResources(resources)}
</div>
);
}
render() {
const { hideDetails, themeStore } = this.props;
const release = this.props.release.get();
return (
<Drawer
className={cssNames("ReleaseDetails", themeStore.activeTheme.type)}
usePortal={true}
open={Boolean(release)}
title={release ? `Release: ${release.getName()}` : ""}
onClose={hideDetails}
toolbar={release && (
<HelmReleaseMenu
release={release}
toolbar
hideDetails={hideDetails}
/>
)}
>
{release && this.renderContent(release)}
</Drawer>
);
}
}
export const ReleaseDetails = withInjectables<Dependencies, ReleaseDetailsProps>(NonInjectedReleaseDetails, {
getProps: (di, props) => ({
...props,
release: di.inject(releaseInjectable),
releaseDetails: di.inject(releaseDetailsInjectable),
releaseValues: di.inject(releaseValuesInjectable),
userSuppliedValuesAreShown: di.inject(userSuppliedValuesAreShownInjectable),
updateRelease: di.inject(updateReleaseInjectable),
createUpgradeChartTab: di.inject(createUpgradeChartTabInjectable),
themeStore: di.inject(themeStoreInjectable),
apiManager: di.inject(apiManagerInjectable),
getDetailsUrl: di.inject(getDetailsUrlInjectable),
}),
}); | the_stack |
import { mXparserConstants } from '../mXparserConstants';
/**
* Binary functions (2 arguments) - mXparserConstants tokens definition.
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
*
* @version 4.2.0
* @class
*/
export class Function2Arg {
public static TYPE_ID: number = 5;
public static TYPE_DESC: string = "Binary Function";
public static LOG_ID: number = 1;
public static MOD_ID: number = 2;
public static BINOM_COEFF_ID: number = 3;
public static BERNOULLI_NUMBER_ID: number = 4;
public static STIRLING1_NUMBER_ID: number = 5;
public static STIRLING2_NUMBER_ID: number = 6;
public static WORPITZKY_NUMBER_ID: number = 7;
public static EULER_NUMBER_ID: number = 8;
public static KRONECKER_DELTA_ID: number = 9;
public static EULER_POLYNOMIAL_ID: number = 10;
public static HARMONIC_NUMBER_ID: number = 11;
public static RND_UNIFORM_CONT_ID: number = 12;
public static RND_UNIFORM_DISCR_ID: number = 13;
public static ROUND_ID: number = 14;
public static RND_NORMAL_ID: number = 15;
public static NDIG_ID: number = 16;
public static DIGIT10_ID: number = 17;
public static FACTVAL_ID: number = 18;
public static FACTEXP_ID: number = 19;
public static ROOT_ID: number = 20;
public static INC_GAMMA_LOWER_ID: number = 21;
public static INC_GAMMA_UPPER_ID: number = 22;
public static REG_GAMMA_LOWER_ID: number = 23;
public static REG_GAMMA_UPPER_ID: number = 24;
public static PERMUTATIONS_ID: number = 25;
public static BETA_ID: number = 26;
public static LOG_BETA_ID: number = 27;
public static LOG_STR: string = "log";
public static MOD_STR: string = "mod";
public static BINOM_COEFF_STR: string = "C";
public static BINOM_COEFF_NCK_STR: string = "nCk";
public static BERNOULLI_NUMBER_STR: string = "Bern";
public static STIRLING1_NUMBER_STR: string = "Stirl1";
public static STIRLING2_NUMBER_STR: string = "Stirl2";
public static WORPITZKY_NUMBER_STR: string = "Worp";
public static EULER_NUMBER_STR: string = "Euler";
public static KRONECKER_DELTA_STR: string = "KDelta";
public static EULER_POLYNOMIAL_STR: string = "EulerPol";
public static HARMONIC_NUMBER_STR: string = "Harm";
public static RND_UNIFORM_CONT_STR: string = "rUni";
public static RND_UNIFORM_DISCR_STR: string = "rUnid";
public static ROUND_STR: string = "round";
public static RND_NORMAL_STR: string = "rNor";
public static NDIG_STR: string = "ndig";
public static DIGIT10_STR: string = "dig10";
public static FACTVAL_STR: string = "factval";
public static FACTEXP_STR: string = "factexp";
public static ROOT_STR: string = "root";
public static INC_GAMMA_LOWER_STR: string = "GammaL";
public static INC_GAMMA_UPPER_STR: string = "GammaU";
public static REG_GAMMA_LOWER_STR: string = "GammaRegL";
public static REG_GAMMA_UPPER_STR: string = "GammaRegU";
public static REG_GAMMA_LOWER_P_STR: string = "GammaP";
public static REG_GAMMA_UPPER_Q_STR: string = "GammaQ";
public static PERMUTATIONS_STR: string = "nPk";
public static BETA_STR: string = "Beta";
public static LOG_BETA_STR: string = "logBeta";
public static LOG_SYN: string = "log(a, b)";
public static MOD_SYN: string = "mod(a, b)";
public static BINOM_COEFF_SYN: string = "C(n, k)";
public static BERNOULLI_NUMBER_SYN: string = "Bern(m, n)";
public static STIRLING1_NUMBER_SYN: string = "Stirl1(n, k)";
public static STIRLING2_NUMBER_SYN: string = "Stirl2(n, k)";
public static WORPITZKY_NUMBER_SYN: string = "Worp(n, k)";
public static EULER_NUMBER_SYN: string = "Euler(n, k)";
public static KRONECKER_DELTA_SYN: string = "KDelta(i, j)";
public static EULER_POLYNOMIAL_SYN: string = "EulerPol";
public static HARMONIC_NUMBER_SYN: string = "Harm(x, n)";
public static RND_UNIFORM_CONT_SYN: string = "rUni(a, b)";
public static RND_UNIFORM_DISCR_SYN: string = "rUnid(a, b)";
public static ROUND_SYN: string = "round(x, n)";
public static RND_NORMAL_SYN: string = "rNor(mean, stdv)";
public static NDIG_SYN: string = "ndig(number, base)";
public static DIGIT10_SYN: string = "dig10(num, pos)";
public static FACTVAL_SYN: string = "factval(number, factorid)";
public static FACTEXP_SYN: string = "factexp(number, factorid)";
public static ROOT_SYN: string = "root(rootorder, number)";
public static INC_GAMMA_LOWER_SYN: string; public static INC_GAMMA_LOWER_SYN_$LI$(): string { if (Function2Arg.INC_GAMMA_LOWER_SYN == null) { Function2Arg.INC_GAMMA_LOWER_SYN = Function2Arg.INC_GAMMA_LOWER_STR + "(s,x)"; } return Function2Arg.INC_GAMMA_LOWER_SYN; }
public static INC_GAMMA_UPPER_SYN: string; public static INC_GAMMA_UPPER_SYN_$LI$(): string { if (Function2Arg.INC_GAMMA_UPPER_SYN == null) { Function2Arg.INC_GAMMA_UPPER_SYN = Function2Arg.INC_GAMMA_UPPER_STR + "(s,x)"; } return Function2Arg.INC_GAMMA_UPPER_SYN; }
public static REG_GAMMA_LOWER_SYN: string; public static REG_GAMMA_LOWER_SYN_$LI$(): string { if (Function2Arg.REG_GAMMA_LOWER_SYN == null) { Function2Arg.REG_GAMMA_LOWER_SYN = Function2Arg.REG_GAMMA_LOWER_STR + "(s,x)"; } return Function2Arg.REG_GAMMA_LOWER_SYN; }
public static REG_GAMMA_UPPER_SYN: string; public static REG_GAMMA_UPPER_SYN_$LI$(): string { if (Function2Arg.REG_GAMMA_UPPER_SYN == null) { Function2Arg.REG_GAMMA_UPPER_SYN = Function2Arg.REG_GAMMA_UPPER_STR + "(s,x)"; } return Function2Arg.REG_GAMMA_UPPER_SYN; }
public static REG_GAMMA_LOWER_P_SYN: string; public static REG_GAMMA_LOWER_P_SYN_$LI$(): string { if (Function2Arg.REG_GAMMA_LOWER_P_SYN == null) { Function2Arg.REG_GAMMA_LOWER_P_SYN = Function2Arg.REG_GAMMA_LOWER_P_STR + "(s,x)"; } return Function2Arg.REG_GAMMA_LOWER_P_SYN; }
public static REG_GAMMA_UPPER_Q_SYN: string; public static REG_GAMMA_UPPER_Q_SYN_$LI$(): string { if (Function2Arg.REG_GAMMA_UPPER_Q_SYN == null) { Function2Arg.REG_GAMMA_UPPER_Q_SYN = Function2Arg.REG_GAMMA_UPPER_Q_STR + "(s,x)"; } return Function2Arg.REG_GAMMA_UPPER_Q_SYN; }
public static BINOM_COEFF_NCK_SYN: string; public static BINOM_COEFF_NCK_SYN_$LI$(): string { if (Function2Arg.BINOM_COEFF_NCK_SYN == null) { Function2Arg.BINOM_COEFF_NCK_SYN = Function2Arg.BINOM_COEFF_NCK_STR + "(n,k)"; } return Function2Arg.BINOM_COEFF_NCK_SYN; }
public static PERMUTATIONS_SYN: string; public static PERMUTATIONS_SYN_$LI$(): string { if (Function2Arg.PERMUTATIONS_SYN == null) { Function2Arg.PERMUTATIONS_SYN = Function2Arg.PERMUTATIONS_STR + "(n,k)"; } return Function2Arg.PERMUTATIONS_SYN; }
public static BETA_SYN: string; public static BETA_SYN_$LI$(): string { if (Function2Arg.BETA_SYN == null) { Function2Arg.BETA_SYN = Function2Arg.BETA_STR + "(x,y)"; } return Function2Arg.BETA_SYN; }
public static LOG_BETA_SYN: string; public static LOG_BETA_SYN_$LI$(): string { if (Function2Arg.LOG_BETA_SYN == null) { Function2Arg.LOG_BETA_SYN = Function2Arg.LOG_BETA_STR + "(x,y)"; } return Function2Arg.LOG_BETA_SYN; }
public static LOG_DESC: string = "Logarithm function";
public static MOD_DESC: string = "Modulo function";
public static BINOM_COEFF_DESC: string = "Binomial coefficient function, number of k-combinations that can be drawn from n-elements set";
public static BERNOULLI_NUMBER_DESC: string = "Bernoulli numbers";
public static STIRLING1_NUMBER_DESC: string = "Stirling numbers of the first kind";
public static STIRLING2_NUMBER_DESC: string = "Stirling numbers of the second kind";
public static WORPITZKY_NUMBER_DESC: string = "Worpitzky number";
public static EULER_NUMBER_DESC: string = "Euler number";
public static KRONECKER_DELTA_DESC: string = "Kronecker delta";
public static EULER_POLYNOMIAL_DESC: string = "EulerPol";
public static HARMONIC_NUMBER_DESC: string = "Harmonic number";
public static RND_UNIFORM_CONT_DESC: string = "Random variable - Uniform continuous distribution U(a,b), usage example: 2*rUni(2,10)";
public static RND_UNIFORM_DISCR_DESC: string = "Random variable - Uniform discrete distribution U{a,b}, usage example: 2*rUnid(2,100)";
public static ROUND_DESC: string = "Half-up rounding, usage examples: round(2.2, 0) = 2, round(2.6, 0) = 3, round(2.66,1) = 2.7";
public static RND_NORMAL_DESC: string = "Random variable - Normal distribution N(m,s) m - mean, s - stddev, usage example: 3*rNor(0,1)";
public static NDIG_DESC: string = "Number of digits representing the number in numeral system with given base";
public static DIGIT10_DESC: string = "Digit at position 1 ... n (left -> right) or 0 ... -(n-1) (right -> left) - base 10 numeral system";
public static FACTVAL_DESC: string = "Prime decomposition - factor value at position between 1 ... nfact(n) - ascending order by factor value";
public static FACTEXP_DESC: string = "Prime decomposition - factor exponent / multiplicity at position between 1 ... nfact(n) - ascending order by factor value";
public static ROOT_DESC: string = "N-th order root of a number";
public static INC_GAMMA_LOWER_DESC: string = "Lower incomplete gamma special function, \u03b3(s,x)";
public static INC_GAMMA_UPPER_DESC: string = "Upper incomplete Gamma special function, \u0393(s,x)";
public static REG_GAMMA_LOWER_DESC: string = "Lower regularized P gamma special function, P(s,x)";
public static REG_GAMMA_UPPER_DESC: string = "Upper regularized Q Gamma special function, Q(s,x)";
public static PERMUTATIONS_DESC: string = "Number of k-permutations that can be drawn from n-elements set";
public static BETA_DESC: string = "The Beta special function B(x,y), also called the Euler integral of the first kind";
public static LOG_BETA_DESC: string = "The Log Beta special function ln B(x,y), also called the Log Euler integral of the first kind, ln B(x,y)";
public static LOG_SINCE: string; public static LOG_SINCE_$LI$(): string { if (Function2Arg.LOG_SINCE == null) { Function2Arg.LOG_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.LOG_SINCE; }
public static MOD_SINCE: string; public static MOD_SINCE_$LI$(): string { if (Function2Arg.MOD_SINCE == null) { Function2Arg.MOD_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.MOD_SINCE; }
public static BINOM_COEFF_SINCE: string; public static BINOM_COEFF_SINCE_$LI$(): string { if (Function2Arg.BINOM_COEFF_SINCE == null) { Function2Arg.BINOM_COEFF_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.BINOM_COEFF_SINCE; }
public static BINOM_COEFF_NCK_SINCE: string; public static BINOM_COEFF_NCK_SINCE_$LI$(): string { if (Function2Arg.BINOM_COEFF_NCK_SINCE == null) { Function2Arg.BINOM_COEFF_NCK_SINCE = mXparserConstants.NAMEv42; } return Function2Arg.BINOM_COEFF_NCK_SINCE; }
public static BERNOULLI_NUMBER_SINCE: string; public static BERNOULLI_NUMBER_SINCE_$LI$(): string { if (Function2Arg.BERNOULLI_NUMBER_SINCE == null) { Function2Arg.BERNOULLI_NUMBER_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.BERNOULLI_NUMBER_SINCE; }
public static STIRLING1_NUMBER_SINCE: string; public static STIRLING1_NUMBER_SINCE_$LI$(): string { if (Function2Arg.STIRLING1_NUMBER_SINCE == null) { Function2Arg.STIRLING1_NUMBER_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.STIRLING1_NUMBER_SINCE; }
public static STIRLING2_NUMBER_SINCE: string; public static STIRLING2_NUMBER_SINCE_$LI$(): string { if (Function2Arg.STIRLING2_NUMBER_SINCE == null) { Function2Arg.STIRLING2_NUMBER_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.STIRLING2_NUMBER_SINCE; }
public static WORPITZKY_NUMBER_SINCE: string; public static WORPITZKY_NUMBER_SINCE_$LI$(): string { if (Function2Arg.WORPITZKY_NUMBER_SINCE == null) { Function2Arg.WORPITZKY_NUMBER_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.WORPITZKY_NUMBER_SINCE; }
public static EULER_NUMBER_SINCE: string; public static EULER_NUMBER_SINCE_$LI$(): string { if (Function2Arg.EULER_NUMBER_SINCE == null) { Function2Arg.EULER_NUMBER_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.EULER_NUMBER_SINCE; }
public static KRONECKER_DELTA_SINCE: string; public static KRONECKER_DELTA_SINCE_$LI$(): string { if (Function2Arg.KRONECKER_DELTA_SINCE == null) { Function2Arg.KRONECKER_DELTA_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.KRONECKER_DELTA_SINCE; }
public static EULER_POLYNOMIAL_SINCE: string; public static EULER_POLYNOMIAL_SINCE_$LI$(): string { if (Function2Arg.EULER_POLYNOMIAL_SINCE == null) { Function2Arg.EULER_POLYNOMIAL_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.EULER_POLYNOMIAL_SINCE; }
public static HARMONIC_NUMBER_SINCE: string; public static HARMONIC_NUMBER_SINCE_$LI$(): string { if (Function2Arg.HARMONIC_NUMBER_SINCE == null) { Function2Arg.HARMONIC_NUMBER_SINCE = mXparserConstants.NAMEv10; } return Function2Arg.HARMONIC_NUMBER_SINCE; }
public static RND_UNIFORM_CONT_SINCE: string; public static RND_UNIFORM_CONT_SINCE_$LI$(): string { if (Function2Arg.RND_UNIFORM_CONT_SINCE == null) { Function2Arg.RND_UNIFORM_CONT_SINCE = mXparserConstants.NAMEv30; } return Function2Arg.RND_UNIFORM_CONT_SINCE; }
public static RND_UNIFORM_DISCR_SINCE: string; public static RND_UNIFORM_DISCR_SINCE_$LI$(): string { if (Function2Arg.RND_UNIFORM_DISCR_SINCE == null) { Function2Arg.RND_UNIFORM_DISCR_SINCE = mXparserConstants.NAMEv30; } return Function2Arg.RND_UNIFORM_DISCR_SINCE; }
public static ROUND_SINCE: string; public static ROUND_SINCE_$LI$(): string { if (Function2Arg.ROUND_SINCE == null) { Function2Arg.ROUND_SINCE = mXparserConstants.NAMEv30; } return Function2Arg.ROUND_SINCE; }
public static RND_NORMAL_SINCE: string; public static RND_NORMAL_SINCE_$LI$(): string { if (Function2Arg.RND_NORMAL_SINCE == null) { Function2Arg.RND_NORMAL_SINCE = mXparserConstants.NAMEv30; } return Function2Arg.RND_NORMAL_SINCE; }
public static NDIG_SINCE: string; public static NDIG_SINCE_$LI$(): string { if (Function2Arg.NDIG_SINCE == null) { Function2Arg.NDIG_SINCE = mXparserConstants.NAMEv41; } return Function2Arg.NDIG_SINCE; }
public static DIGIT10_SINCE: string; public static DIGIT10_SINCE_$LI$(): string { if (Function2Arg.DIGIT10_SINCE == null) { Function2Arg.DIGIT10_SINCE = mXparserConstants.NAMEv41; } return Function2Arg.DIGIT10_SINCE; }
public static FACTVAL_SINCE: string; public static FACTVAL_SINCE_$LI$(): string { if (Function2Arg.FACTVAL_SINCE == null) { Function2Arg.FACTVAL_SINCE = mXparserConstants.NAMEv41; } return Function2Arg.FACTVAL_SINCE; }
public static FACTEXP_SINCE: string; public static FACTEXP_SINCE_$LI$(): string { if (Function2Arg.FACTEXP_SINCE == null) { Function2Arg.FACTEXP_SINCE = mXparserConstants.NAMEv41; } return Function2Arg.FACTEXP_SINCE; }
public static ROOT_SINCE: string; public static ROOT_SINCE_$LI$(): string { if (Function2Arg.ROOT_SINCE == null) { Function2Arg.ROOT_SINCE = mXparserConstants.NAMEv41; } return Function2Arg.ROOT_SINCE; }
public static INC_GAMMA_LOWER_SINCE: string; public static INC_GAMMA_LOWER_SINCE_$LI$(): string { if (Function2Arg.INC_GAMMA_LOWER_SINCE == null) { Function2Arg.INC_GAMMA_LOWER_SINCE = mXparserConstants.NAMEv42; } return Function2Arg.INC_GAMMA_LOWER_SINCE; }
public static INC_GAMMA_UPPER_SINCE: string; public static INC_GAMMA_UPPER_SINCE_$LI$(): string { if (Function2Arg.INC_GAMMA_UPPER_SINCE == null) { Function2Arg.INC_GAMMA_UPPER_SINCE = mXparserConstants.NAMEv42; } return Function2Arg.INC_GAMMA_UPPER_SINCE; }
public static REG_GAMMA_LOWER_SINCE: string; public static REG_GAMMA_LOWER_SINCE_$LI$(): string { if (Function2Arg.REG_GAMMA_LOWER_SINCE == null) { Function2Arg.REG_GAMMA_LOWER_SINCE = mXparserConstants.NAMEv42; } return Function2Arg.REG_GAMMA_LOWER_SINCE; }
public static REG_GAMMA_UPPER_SINCE: string; public static REG_GAMMA_UPPER_SINCE_$LI$(): string { if (Function2Arg.REG_GAMMA_UPPER_SINCE == null) { Function2Arg.REG_GAMMA_UPPER_SINCE = mXparserConstants.NAMEv42; } return Function2Arg.REG_GAMMA_UPPER_SINCE; }
public static PERMUTATIONS_SINCE: string; public static PERMUTATIONS_SINCE_$LI$(): string { if (Function2Arg.PERMUTATIONS_SINCE == null) { Function2Arg.PERMUTATIONS_SINCE = mXparserConstants.NAMEv42; } return Function2Arg.PERMUTATIONS_SINCE; }
public static BETA_SINCE: string; public static BETA_SINCE_$LI$(): string { if (Function2Arg.BETA_SINCE == null) { Function2Arg.BETA_SINCE = mXparserConstants.NAMEv42; } return Function2Arg.BETA_SINCE; }
public static LOG_BETA_SINCE: string; public static LOG_BETA_SINCE_$LI$(): string { if (Function2Arg.LOG_BETA_SINCE == null) { Function2Arg.LOG_BETA_SINCE = mXparserConstants.NAMEv42; } return Function2Arg.LOG_BETA_SINCE; }
}
Function2Arg["__class"] = "org.mariuszgromada.math.mxparser.parsertokens.Function2Arg"; | the_stack |
declare enum DOTA_GameState {
DOTA_GAMERULES_STATE_INIT = 0,
DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD = 1,
DOTA_GAMERULES_STATE_HERO_SELECTION = 3,
DOTA_GAMERULES_STATE_STRATEGY_TIME = 4,
DOTA_GAMERULES_STATE_PRE_GAME = 7,
DOTA_GAMERULES_STATE_GAME_IN_PROGRESS = 8,
DOTA_GAMERULES_STATE_POST_GAME = 9,
DOTA_GAMERULES_STATE_DISCONNECT = 10,
DOTA_GAMERULES_STATE_TEAM_SHOWCASE = 5,
DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP = 2,
DOTA_GAMERULES_STATE_WAIT_FOR_MAP_TO_LOAD = 6,
DOTA_GAMERULES_STATE_LAST = 0
}
declare enum DOTA_GC_TEAM {
DOTA_GC_TEAM_GOOD_GUYS = 0,
DOTA_GC_TEAM_BAD_GUYS = 1,
DOTA_GC_TEAM_BROADCASTER = 2,
DOTA_GC_TEAM_SPECTATOR = 3,
DOTA_GC_TEAM_PLAYER_POOL = 4,
DOTA_GC_TEAM_NOTEAM = 5
}
declare enum DOTAConnectionState_t {
DOTA_CONNECTION_STATE_UNKNOWN = 0,
DOTA_CONNECTION_STATE_NOT_YET_CONNECTED = 1,
DOTA_CONNECTION_STATE_CONNECTED = 2,
DOTA_CONNECTION_STATE_DISCONNECTED = 3,
DOTA_CONNECTION_STATE_ABANDONED = 4,
DOTA_CONNECTION_STATE_LOADING = 5,
DOTA_CONNECTION_STATE_FAILED = 6
}
declare enum dotaunitorder_t {
DOTA_UNIT_ORDER_NONE = 0,
DOTA_UNIT_ORDER_MOVE_TO_POSITION = 1,
DOTA_UNIT_ORDER_MOVE_TO_TARGET = 2,
DOTA_UNIT_ORDER_ATTACK_MOVE = 3,
DOTA_UNIT_ORDER_ATTACK_TARGET = 4,
DOTA_UNIT_ORDER_CAST_POSITION = 5,
DOTA_UNIT_ORDER_CAST_TARGET = 6,
DOTA_UNIT_ORDER_CAST_TARGET_TREE = 7,
DOTA_UNIT_ORDER_CAST_NO_TARGET = 8,
DOTA_UNIT_ORDER_CAST_TOGGLE = 9,
DOTA_UNIT_ORDER_HOLD_POSITION = 10,
DOTA_UNIT_ORDER_TRAIN_ABILITY = 11,
DOTA_UNIT_ORDER_DROP_ITEM = 12,
DOTA_UNIT_ORDER_GIVE_ITEM = 13,
DOTA_UNIT_ORDER_PICKUP_ITEM = 14,
DOTA_UNIT_ORDER_PICKUP_RUNE = 15,
DOTA_UNIT_ORDER_PURCHASE_ITEM = 16,
DOTA_UNIT_ORDER_SELL_ITEM = 17,
DOTA_UNIT_ORDER_DISASSEMBLE_ITEM = 18,
DOTA_UNIT_ORDER_MOVE_ITEM = 19,
DOTA_UNIT_ORDER_CAST_TOGGLE_AUTO = 20,
DOTA_UNIT_ORDER_STOP = 21,
DOTA_UNIT_ORDER_TAUNT = 22,
DOTA_UNIT_ORDER_BUYBACK = 23,
DOTA_UNIT_ORDER_GLYPH = 24,
DOTA_UNIT_ORDER_EJECT_ITEM_FROM_STASH = 25,
DOTA_UNIT_ORDER_CAST_RUNE = 26,
DOTA_UNIT_ORDER_PING_ABILITY = 27,
DOTA_UNIT_ORDER_MOVE_TO_DIRECTION = 28,
DOTA_UNIT_ORDER_PATROL = 29,
DOTA_UNIT_ORDER_VECTOR_TARGET_POSITION = 30,
DOTA_UNIT_ORDER_RADAR = 31,
DOTA_UNIT_ORDER_SET_ITEM_COMBINE_LOCK = 32,
DOTA_UNIT_ORDER_CONTINUE = 33
}
declare enum DOTA_OVERHEAD_ALERT {
OVERHEAD_ALERT_GOLD = 0,
OVERHEAD_ALERT_DENY = 1,
OVERHEAD_ALERT_CRITICAL = 2,
OVERHEAD_ALERT_XP = 3,
OVERHEAD_ALERT_BONUS_SPELL_DAMAGE = 4,
OVERHEAD_ALERT_MISS = 5,
OVERHEAD_ALERT_DAMAGE = 6,
OVERHEAD_ALERT_EVADE = 7,
OVERHEAD_ALERT_BLOCK = 8,
OVERHEAD_ALERT_BONUS_POISON_DAMAGE = 9,
OVERHEAD_ALERT_HEAL = 10,
OVERHEAD_ALERT_MANA_ADD = 11,
OVERHEAD_ALERT_MANA_LOSS = 12,
OVERHEAD_ALERT_LAST_HIT_EARLY = 13,
OVERHEAD_ALERT_LAST_HIT_CLOSE = 14,
OVERHEAD_ALERT_LAST_HIT_MISS = 15,
OVERHEAD_ALERT_MAGICAL_BLOCK = 16,
OVERHEAD_ALERT_INCOMING_DAMAGE = 17,
OVERHEAD_ALERT_OUTGOING_DAMAGE = 18
}
declare enum DOTA_HeroPickState {
DOTA_HEROPICK_STATE_NONE = 0,
DOTA_HEROPICK_STATE_AP_SELECT = 1,
DOTA_HEROPICK_STATE_SD_SELECT = 2,
DOTA_HEROPICK_STATE_INTRO_SELECT_UNUSED = 3,
DOTA_HEROPICK_STATE_RD_SELECT_UNUSED = 4,
DOTA_HEROPICK_STATE_CM_INTRO = 5,
DOTA_HEROPICK_STATE_CM_CAPTAINPICK = 6,
DOTA_HEROPICK_STATE_CM_BAN1 = 7,
DOTA_HEROPICK_STATE_CM_BAN2 = 8,
DOTA_HEROPICK_STATE_CM_BAN3 = 9,
DOTA_HEROPICK_STATE_CM_BAN4 = 10,
DOTA_HEROPICK_STATE_CM_BAN5 = 11,
DOTA_HEROPICK_STATE_CM_BAN6 = 12,
DOTA_HEROPICK_STATE_CM_BAN7 = 13,
DOTA_HEROPICK_STATE_CM_BAN8 = 14,
DOTA_HEROPICK_STATE_CM_BAN9 = 15,
DOTA_HEROPICK_STATE_CM_BAN10 = 16,
DOTA_HEROPICK_STATE_CM_SELECT1 = 17,
DOTA_HEROPICK_STATE_CM_SELECT2 = 18,
DOTA_HEROPICK_STATE_CM_SELECT3 = 19,
DOTA_HEROPICK_STATE_CM_SELECT4 = 20,
DOTA_HEROPICK_STATE_CM_SELECT5 = 21,
DOTA_HEROPICK_STATE_CM_SELECT6 = 22,
DOTA_HEROPICK_STATE_CM_SELECT7 = 23,
DOTA_HEROPICK_STATE_CM_SELECT8 = 24,
DOTA_HEROPICK_STATE_CM_SELECT9 = 25,
DOTA_HEROPICK_STATE_CM_SELECT10 = 26,
DOTA_HEROPICK_STATE_CM_PICK = 27,
DOTA_HEROPICK_STATE_AR_SELECT = 28,
DOTA_HEROPICK_STATE_MO_SELECT = 29,
DOTA_HEROPICK_STATE_FH_SELECT = 30,
DOTA_HEROPICK_STATE_CD_INTRO = 31,
DOTA_HEROPICK_STATE_CD_CAPTAINPICK = 32,
DOTA_HEROPICK_STATE_CD_BAN1 = 33,
DOTA_HEROPICK_STATE_CD_BAN2 = 34,
DOTA_HEROPICK_STATE_CD_BAN3 = 35,
DOTA_HEROPICK_STATE_CD_BAN4 = 36,
DOTA_HEROPICK_STATE_CD_BAN5 = 37,
DOTA_HEROPICK_STATE_CD_BAN6 = 38,
DOTA_HEROPICK_STATE_CD_SELECT1 = 39,
DOTA_HEROPICK_STATE_CD_SELECT2 = 40,
DOTA_HEROPICK_STATE_CD_SELECT3 = 41,
DOTA_HEROPICK_STATE_CD_SELECT4 = 42,
DOTA_HEROPICK_STATE_CD_SELECT5 = 43,
DOTA_HEROPICK_STATE_CD_SELECT6 = 44,
DOTA_HEROPICK_STATE_CD_SELECT7 = 45,
DOTA_HEROPICK_STATE_CD_SELECT8 = 46,
DOTA_HEROPICK_STATE_CD_SELECT9 = 47,
DOTA_HEROPICK_STATE_CD_SELECT10 = 48,
DOTA_HEROPICK_STATE_CD_PICK = 49,
DOTA_HEROPICK_STATE_BD_SELECT = 50,
DOTA_HERO_PICK_STATE_ABILITY_DRAFT_SELECT = 51,
DOTA_HERO_PICK_STATE_ARDM_SELECT = 52,
DOTA_HEROPICK_STATE_ALL_DRAFT_SELECT = 53,
DOTA_HERO_PICK_STATE_CUSTOMGAME_SELECT = 54,
DOTA_HEROPICK_STATE_SELECT_PENALTY = 55,
DOTA_HEROPICK_STATE_COUNT = 56
}
declare enum DOTATeam_t {
DOTA_TEAM_FIRST = 2,
DOTA_TEAM_GOODGUYS = 2,
DOTA_TEAM_BADGUYS = 3,
DOTA_TEAM_NEUTRALS = 4,
DOTA_TEAM_NOTEAM = 5,
DOTA_TEAM_CUSTOM_1 = 6,
DOTA_TEAM_CUSTOM_2 = 7,
DOTA_TEAM_CUSTOM_3 = 8,
DOTA_TEAM_CUSTOM_4 = 9,
DOTA_TEAM_CUSTOM_5 = 10,
DOTA_TEAM_CUSTOM_6 = 11,
DOTA_TEAM_CUSTOM_7 = 12,
DOTA_TEAM_CUSTOM_8 = 13,
DOTA_TEAM_COUNT = 14,
DOTA_TEAM_CUSTOM_MIN = 6,
DOTA_TEAM_CUSTOM_MAX = 13,
DOTA_TEAM_CUSTOM_COUNT = 8
}
declare enum DOTA_RUNES {
DOTA_RUNE_INVALID = -1,
DOTA_RUNE_DOUBLEDAMAGE = 0,
DOTA_RUNE_HASTE = 1,
DOTA_RUNE_ILLUSION = 2,
DOTA_RUNE_INVISIBILITY = 3,
DOTA_RUNE_REGENERATION = 4,
DOTA_RUNE_BOUNTY = 5,
DOTA_RUNE_ARCANE = 6,
DOTA_RUNE_COUNT = 7
}
declare enum DOTA_UNIT_TARGET_TEAM {
DOTA_UNIT_TARGET_TEAM_NONE = 0,
DOTA_UNIT_TARGET_TEAM_FRIENDLY = 1,
DOTA_UNIT_TARGET_TEAM_ENEMY = 2,
DOTA_UNIT_TARGET_TEAM_CUSTOM = 4,
DOTA_UNIT_TARGET_TEAM_BOTH = 3
}
declare enum DOTA_UNIT_TARGET_TYPE {
DOTA_UNIT_TARGET_NONE = 0,
DOTA_UNIT_TARGET_HERO = 1,
DOTA_UNIT_TARGET_CREEP = 2,
DOTA_UNIT_TARGET_BUILDING = 4,
DOTA_UNIT_TARGET_COURIER = 16,
DOTA_UNIT_TARGET_OTHER = 32,
DOTA_UNIT_TARGET_TREE = 64,
DOTA_UNIT_TARGET_CUSTOM = 128,
DOTA_UNIT_TARGET_BASIC = 18,
DOTA_UNIT_TARGET_ALL = 55
}
declare enum DOTA_UNIT_TARGET_FLAGS {
DOTA_UNIT_TARGET_FLAG_NONE = 0,
DOTA_UNIT_TARGET_FLAG_RANGED_ONLY = 2,
DOTA_UNIT_TARGET_FLAG_MELEE_ONLY = 4,
DOTA_UNIT_TARGET_FLAG_DEAD = 8,
DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES = 16,
DOTA_UNIT_TARGET_FLAG_NOT_MAGIC_IMMUNE_ALLIES = 32,
DOTA_UNIT_TARGET_FLAG_INVULNERABLE = 64,
DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE = 128,
DOTA_UNIT_TARGET_FLAG_NO_INVIS = 256,
DOTA_UNIT_TARGET_FLAG_NOT_ANCIENTS = 512,
DOTA_UNIT_TARGET_FLAG_PLAYER_CONTROLLED = 1024,
DOTA_UNIT_TARGET_FLAG_NOT_DOMINATED = 2048,
DOTA_UNIT_TARGET_FLAG_NOT_SUMMONED = 4096,
DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS = 8192,
DOTA_UNIT_TARGET_FLAG_NOT_ATTACK_IMMUNE = 16384,
DOTA_UNIT_TARGET_FLAG_MANA_ONLY = 32768,
DOTA_UNIT_TARGET_FLAG_CHECK_DISABLE_HELP = 65536,
DOTA_UNIT_TARGET_FLAG_NOT_CREEP_HERO = 131072,
DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD = 262144,
DOTA_UNIT_TARGET_FLAG_NOT_NIGHTMARED = 524288,
DOTA_UNIT_TARGET_FLAG_PREFER_ENEMIES = 1048576
}
declare enum DOTALimits_t {
DOTA_MAX_PLAYERS = 64,
DOTA_MAX_TEAM = 24,
DOTA_MAX_PLAYER_TEAMS = 10,
DOTA_MAX_TEAM_PLAYERS = 24,
DOTA_MAX_SPECTATOR_TEAM_SIZE = 40,
DOTA_MAX_SPECTATOR_LOBBY_SIZE = 15,
DOTA_DEFAULT_MAX_TEAM = 5,
DOTA_DEFAULT_MAX_TEAM_PLAYERS = 10
}
declare enum DOTAInventoryFlags_t {
DOTA_INVENTORY_ALLOW_NONE = 0,
DOTA_INVENTORY_ALLOW_MAIN = 1,
DOTA_INVENTORY_ALLOW_STASH = 2,
DOTA_INVENTORY_ALLOW_DROP_ON_GROUND = 4,
DOTA_INVENTORY_ALLOW_DROP_AT_FOUNTAIN = 8,
DOTA_INVENTORY_LIMIT_DROP_ON_GROUND = 16,
DOTA_INVENTORY_ALL_ACCESS = 3
}
declare enum EDOTA_ModifyGold_Reason {
DOTA_ModifyGold_Unspecified = 0,
DOTA_ModifyGold_Death = 1,
DOTA_ModifyGold_Buyback = 2,
DOTA_ModifyGold_PurchaseConsumable = 3,
DOTA_ModifyGold_PurchaseItem = 4,
DOTA_ModifyGold_AbandonedRedistribute = 5,
DOTA_ModifyGold_SellItem = 6,
DOTA_ModifyGold_AbilityCost = 7,
DOTA_ModifyGold_CheatCommand = 8,
DOTA_ModifyGold_SelectionPenalty = 9,
DOTA_ModifyGold_GameTick = 10,
DOTA_ModifyGold_Building = 11,
DOTA_ModifyGold_HeroKill = 12,
DOTA_ModifyGold_CreepKill = 13,
DOTA_ModifyGold_RoshanKill = 14,
DOTA_ModifyGold_CourierKill = 15,
DOTA_ModifyGold_SharedGold = 16
}
declare enum DOTAUnitAttackCapability_t {
DOTA_UNIT_CAP_NO_ATTACK = 0,
DOTA_UNIT_CAP_MELEE_ATTACK = 1,
DOTA_UNIT_CAP_RANGED_ATTACK = 2
}
declare enum DOTAUnitMoveCapability_t {
DOTA_UNIT_CAP_MOVE_NONE = 0,
DOTA_UNIT_CAP_MOVE_GROUND = 1,
DOTA_UNIT_CAP_MOVE_FLY = 2
}
declare enum EShareAbility {
ITEM_FULLY_SHAREABLE = 0,
ITEM_PARTIALLY_SHAREABLE = 1,
ITEM_NOT_SHAREABLE = 2
}
declare enum DOTAMusicStatus_t {
DOTA_MUSIC_STATUS_NONE = 0,
DOTA_MUSIC_STATUS_EXPLORATION = 1,
DOTA_MUSIC_STATUS_BATTLE = 2,
DOTA_MUSIC_STATUS_PRE_GAME_EXPLORATION = 3,
DOTA_MUSIC_STATUS_DEAD = 4,
DOTA_MUSIC_STATUS_LAST = 5
}
declare enum DOTA_ABILITY_BEHAVIOR {
DOTA_ABILITY_BEHAVIOR_NONE = 0,
DOTA_ABILITY_BEHAVIOR_HIDDEN = 1,
DOTA_ABILITY_BEHAVIOR_PASSIVE = 2,
DOTA_ABILITY_BEHAVIOR_NO_TARGET = 4,
DOTA_ABILITY_BEHAVIOR_UNIT_TARGET = 8,
DOTA_ABILITY_BEHAVIOR_POINT = 16,
DOTA_ABILITY_BEHAVIOR_AOE = 32,
DOTA_ABILITY_BEHAVIOR_NOT_LEARNABLE = 64,
DOTA_ABILITY_BEHAVIOR_CHANNELLED = 128,
DOTA_ABILITY_BEHAVIOR_ITEM = 256,
DOTA_ABILITY_BEHAVIOR_TOGGLE = 512,
DOTA_ABILITY_BEHAVIOR_DIRECTIONAL = 1024,
DOTA_ABILITY_BEHAVIOR_IMMEDIATE = 2048,
DOTA_ABILITY_BEHAVIOR_AUTOCAST = 4096,
DOTA_ABILITY_BEHAVIOR_OPTIONAL_UNIT_TARGET = 8192,
DOTA_ABILITY_BEHAVIOR_OPTIONAL_POINT = 16384,
DOTA_ABILITY_BEHAVIOR_OPTIONAL_NO_TARGET = 32768,
DOTA_ABILITY_BEHAVIOR_AURA = 65536,
DOTA_ABILITY_BEHAVIOR_ATTACK = 131072,
DOTA_ABILITY_BEHAVIOR_DONT_RESUME_MOVEMENT = 262144,
DOTA_ABILITY_BEHAVIOR_ROOT_DISABLES = 524288,
DOTA_ABILITY_BEHAVIOR_UNRESTRICTED = 1048576,
DOTA_ABILITY_BEHAVIOR_IGNORE_PSEUDO_QUEUE = 2097152,
DOTA_ABILITY_BEHAVIOR_IGNORE_CHANNEL = 4194304,
DOTA_ABILITY_BEHAVIOR_DONT_CANCEL_MOVEMENT = 8388608,
DOTA_ABILITY_BEHAVIOR_DONT_ALERT_TARGET = 16777216,
DOTA_ABILITY_BEHAVIOR_DONT_RESUME_ATTACK = 33554432,
DOTA_ABILITY_BEHAVIOR_NORMAL_WHEN_STOLEN = 67108864,
DOTA_ABILITY_BEHAVIOR_IGNORE_BACKSWING = 134217728,
DOTA_ABILITY_BEHAVIOR_RUNE_TARGET = 268435456,
DOTA_ABILITY_BEHAVIOR_DONT_CANCEL_CHANNEL = 536870912,
DOTA_ABILITY_BEHAVIOR_VECTOR_TARGETING = 1073741824,
DOTA_ABILITY_BEHAVIOR_LAST_RESORT_POINT = -2147483648,
DOTA_ABILITY_LAST_BEHAVIOR = -2147483648
}
declare enum DAMAGE_TYPES {
DAMAGE_TYPE_NONE = 0,
DAMAGE_TYPE_PHYSICAL = 1,
DAMAGE_TYPE_MAGICAL = 2,
DAMAGE_TYPE_PURE = 4,
DAMAGE_TYPE_HP_REMOVAL = 8,
DAMAGE_TYPE_ALL = 7
}
declare enum ABILITY_TYPES {
ABILITY_TYPE_BASIC = 0,
ABILITY_TYPE_ULTIMATE = 1,
ABILITY_TYPE_ATTRIBUTES = 2,
ABILITY_TYPE_HIDDEN = 3
}
declare enum SPELL_IMMUNITY_TYPES {
SPELL_IMMUNITY_NONE = 0,
SPELL_IMMUNITY_ALLIES_YES = 1,
SPELL_IMMUNITY_ALLIES_NO = 2,
SPELL_IMMUNITY_ENEMIES_YES = 3,
SPELL_IMMUNITY_ENEMIES_NO = 4
}
declare enum DOTADamageFlag_t {
DOTA_DAMAGE_FLAG_NONE = 0,
DOTA_DAMAGE_FLAG_IGNORES_MAGIC_ARMOR = 1,
DOTA_DAMAGE_FLAG_IGNORES_PHYSICAL_ARMOR = 2,
DOTA_DAMAGE_FLAG_BYPASSES_INVULNERABILITY = 4,
DOTA_DAMAGE_FLAG_BYPASSES_BLOCK = 8,
DOTA_DAMAGE_FLAG_REFLECTION = 16,
DOTA_DAMAGE_FLAG_HPLOSS = 32,
DOTA_DAMAGE_FLAG_NO_DIRECTOR_EVENT = 64,
DOTA_DAMAGE_FLAG_NON_LETHAL = 128,
DOTA_DAMAGE_FLAG_USE_COMBAT_PROFICIENCY = 256,
DOTA_DAMAGE_FLAG_NO_DAMAGE_MULTIPLIERS = 512,
DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION = 1024,
DOTA_DAMAGE_FLAG_DONT_DISPLAY_DAMAGE_IF_SOURCE_HIDDEN = 2048
}
declare enum EDOTA_ModifyXP_Reason {
DOTA_ModifyXP_Unspecified = 0,
DOTA_ModifyXP_HeroKill = 1,
DOTA_ModifyXP_CreepKill = 2,
DOTA_ModifyXP_RoshanKill = 3
}
declare enum GameActivity_t {
ACT_DOTA_IDLE = 1500,
ACT_DOTA_IDLE_RARE = 1501,
ACT_DOTA_RUN = 1502,
ACT_DOTA_ATTACK = 1503,
ACT_DOTA_ATTACK2 = 1504,
ACT_DOTA_ATTACK_EVENT = 1505,
ACT_DOTA_DIE = 1506,
ACT_DOTA_FLINCH = 1507,
ACT_DOTA_FLAIL = 1508,
ACT_DOTA_DISABLED = 1509,
ACT_DOTA_CAST_ABILITY_1 = 1510,
ACT_DOTA_CAST_ABILITY_2 = 1511,
ACT_DOTA_CAST_ABILITY_3 = 1512,
ACT_DOTA_CAST_ABILITY_4 = 1513,
ACT_DOTA_CAST_ABILITY_5 = 1514,
ACT_DOTA_CAST_ABILITY_6 = 1515,
ACT_DOTA_OVERRIDE_ABILITY_1 = 1516,
ACT_DOTA_OVERRIDE_ABILITY_2 = 1517,
ACT_DOTA_OVERRIDE_ABILITY_3 = 1518,
ACT_DOTA_OVERRIDE_ABILITY_4 = 1519,
ACT_DOTA_CHANNEL_ABILITY_1 = 1520,
ACT_DOTA_CHANNEL_ABILITY_2 = 1521,
ACT_DOTA_CHANNEL_ABILITY_3 = 1522,
ACT_DOTA_CHANNEL_ABILITY_4 = 1523,
ACT_DOTA_CHANNEL_ABILITY_5 = 1524,
ACT_DOTA_CHANNEL_ABILITY_6 = 1525,
ACT_DOTA_CHANNEL_END_ABILITY_1 = 1526,
ACT_DOTA_CHANNEL_END_ABILITY_2 = 1527,
ACT_DOTA_CHANNEL_END_ABILITY_3 = 1528,
ACT_DOTA_CHANNEL_END_ABILITY_4 = 1529,
ACT_DOTA_CHANNEL_END_ABILITY_5 = 1530,
ACT_DOTA_CHANNEL_END_ABILITY_6 = 1531,
ACT_DOTA_CONSTANT_LAYER = 1532,
ACT_DOTA_CAPTURE = 1533,
ACT_DOTA_SPAWN = 1534,
ACT_DOTA_KILLTAUNT = 1535,
ACT_DOTA_TAUNT = 1536,
ACT_DOTA_THIRST = 1537,
ACT_DOTA_CAST_DRAGONBREATH = 1538,
ACT_DOTA_ECHO_SLAM = 1539,
ACT_DOTA_CAST_ABILITY_1_END = 1540,
ACT_DOTA_CAST_ABILITY_2_END = 1541,
ACT_DOTA_CAST_ABILITY_3_END = 1542,
ACT_DOTA_CAST_ABILITY_4_END = 1543,
ACT_MIRANA_LEAP_END = 1544,
ACT_WAVEFORM_START = 1545,
ACT_WAVEFORM_END = 1546,
ACT_DOTA_CAST_ABILITY_ROT = 1547,
ACT_DOTA_DIE_SPECIAL = 1548,
ACT_DOTA_RATTLETRAP_BATTERYASSAULT = 1549,
ACT_DOTA_RATTLETRAP_POWERCOGS = 1550,
ACT_DOTA_RATTLETRAP_HOOKSHOT_START = 1551,
ACT_DOTA_RATTLETRAP_HOOKSHOT_LOOP = 1552,
ACT_DOTA_RATTLETRAP_HOOKSHOT_END = 1553,
ACT_STORM_SPIRIT_OVERLOAD_RUN_OVERRIDE = 1554,
ACT_DOTA_TINKER_REARM1 = 1555,
ACT_DOTA_TINKER_REARM2 = 1556,
ACT_DOTA_TINKER_REARM3 = 1557,
ACT_TINY_AVALANCHE = 1558,
ACT_TINY_TOSS = 1559,
ACT_TINY_GROWL = 1560,
ACT_DOTA_WEAVERBUG_ATTACH = 1561,
ACT_DOTA_CAST_WILD_AXES_END = 1562,
ACT_DOTA_CAST_LIFE_BREAK_START = 1563,
ACT_DOTA_CAST_LIFE_BREAK_END = 1564,
ACT_DOTA_NIGHTSTALKER_TRANSITION = 1565,
ACT_DOTA_LIFESTEALER_RAGE = 1566,
ACT_DOTA_LIFESTEALER_OPEN_WOUNDS = 1567,
ACT_DOTA_SAND_KING_BURROW_IN = 1568,
ACT_DOTA_SAND_KING_BURROW_OUT = 1569,
ACT_DOTA_EARTHSHAKER_TOTEM_ATTACK = 1570,
ACT_DOTA_WHEEL_LAYER = 1571,
ACT_DOTA_ALCHEMIST_CHEMICAL_RAGE_START = 1572,
ACT_DOTA_ALCHEMIST_CONCOCTION = 1573,
ACT_DOTA_JAKIRO_LIQUIDFIRE_START = 1574,
ACT_DOTA_JAKIRO_LIQUIDFIRE_LOOP = 1575,
ACT_DOTA_LIFESTEALER_INFEST = 1576,
ACT_DOTA_LIFESTEALER_INFEST_END = 1577,
ACT_DOTA_LASSO_LOOP = 1578,
ACT_DOTA_ALCHEMIST_CONCOCTION_THROW = 1579,
ACT_DOTA_ALCHEMIST_CHEMICAL_RAGE_END = 1580,
ACT_DOTA_CAST_COLD_SNAP = 1581,
ACT_DOTA_CAST_GHOST_WALK = 1582,
ACT_DOTA_CAST_TORNADO = 1583,
ACT_DOTA_CAST_EMP = 1584,
ACT_DOTA_CAST_ALACRITY = 1585,
ACT_DOTA_CAST_CHAOS_METEOR = 1586,
ACT_DOTA_CAST_SUN_STRIKE = 1587,
ACT_DOTA_CAST_FORGE_SPIRIT = 1588,
ACT_DOTA_CAST_ICE_WALL = 1589,
ACT_DOTA_CAST_DEAFENING_BLAST = 1590,
ACT_DOTA_VICTORY = 1591,
ACT_DOTA_DEFEAT = 1592,
ACT_DOTA_SPIRIT_BREAKER_CHARGE_POSE = 1593,
ACT_DOTA_SPIRIT_BREAKER_CHARGE_END = 1594,
ACT_DOTA_TELEPORT = 1595,
ACT_DOTA_TELEPORT_END = 1596,
ACT_DOTA_CAST_REFRACTION = 1597,
ACT_DOTA_CAST_ABILITY_7 = 1598,
ACT_DOTA_CANCEL_SIREN_SONG = 1599,
ACT_DOTA_CHANNEL_ABILITY_7 = 1600,
ACT_DOTA_LOADOUT = 1601,
ACT_DOTA_FORCESTAFF_END = 1602,
ACT_DOTA_POOF_END = 1603,
ACT_DOTA_SLARK_POUNCE = 1604,
ACT_DOTA_MAGNUS_SKEWER_START = 1605,
ACT_DOTA_MAGNUS_SKEWER_END = 1606,
ACT_DOTA_MEDUSA_STONE_GAZE = 1607,
ACT_DOTA_RELAX_START = 1608,
ACT_DOTA_RELAX_LOOP = 1609,
ACT_DOTA_RELAX_END = 1610,
ACT_DOTA_CENTAUR_STAMPEDE = 1611,
ACT_DOTA_BELLYACHE_START = 1612,
ACT_DOTA_BELLYACHE_LOOP = 1613,
ACT_DOTA_BELLYACHE_END = 1614,
ACT_DOTA_ROQUELAIRE_LAND = 1615,
ACT_DOTA_ROQUELAIRE_LAND_IDLE = 1616,
ACT_DOTA_GREEVIL_CAST = 1617,
ACT_DOTA_GREEVIL_OVERRIDE_ABILITY = 1618,
ACT_DOTA_GREEVIL_HOOK_START = 1619,
ACT_DOTA_GREEVIL_HOOK_END = 1620,
ACT_DOTA_GREEVIL_BLINK_BONE = 1621,
ACT_DOTA_IDLE_SLEEPING = 1622,
ACT_DOTA_INTRO = 1623,
ACT_DOTA_GESTURE_POINT = 1624,
ACT_DOTA_GESTURE_ACCENT = 1625,
ACT_DOTA_SLEEPING_END = 1626,
ACT_DOTA_AMBUSH = 1627,
ACT_DOTA_ITEM_LOOK = 1628,
ACT_DOTA_STARTLE = 1629,
ACT_DOTA_FRUSTRATION = 1630,
ACT_DOTA_TELEPORT_REACT = 1631,
ACT_DOTA_TELEPORT_END_REACT = 1632,
ACT_DOTA_SHRUG = 1633,
ACT_DOTA_RELAX_LOOP_END = 1634,
ACT_DOTA_PRESENT_ITEM = 1635,
ACT_DOTA_IDLE_IMPATIENT = 1636,
ACT_DOTA_SHARPEN_WEAPON = 1637,
ACT_DOTA_SHARPEN_WEAPON_OUT = 1638,
ACT_DOTA_IDLE_SLEEPING_END = 1639,
ACT_DOTA_BRIDGE_DESTROY = 1640,
ACT_DOTA_TAUNT_SNIPER = 1641,
ACT_DOTA_DEATH_BY_SNIPER = 1642,
ACT_DOTA_LOOK_AROUND = 1643,
ACT_DOTA_CAGED_CREEP_RAGE = 1644,
ACT_DOTA_CAGED_CREEP_RAGE_OUT = 1645,
ACT_DOTA_CAGED_CREEP_SMASH = 1646,
ACT_DOTA_CAGED_CREEP_SMASH_OUT = 1647,
ACT_DOTA_IDLE_IMPATIENT_SWORD_TAP = 1648,
ACT_DOTA_INTRO_LOOP = 1649,
ACT_DOTA_BRIDGE_THREAT = 1650,
ACT_DOTA_DAGON = 1651,
ACT_DOTA_CAST_ABILITY_2_ES_ROLL_START = 1652,
ACT_DOTA_CAST_ABILITY_2_ES_ROLL = 1653,
ACT_DOTA_CAST_ABILITY_2_ES_ROLL_END = 1654,
ACT_DOTA_NIAN_PIN_START = 1655,
ACT_DOTA_NIAN_PIN_LOOP = 1656,
ACT_DOTA_NIAN_PIN_END = 1657,
ACT_DOTA_LEAP_STUN = 1658,
ACT_DOTA_LEAP_SWIPE = 1659,
ACT_DOTA_NIAN_INTRO_LEAP = 1660,
ACT_DOTA_AREA_DENY = 1661,
ACT_DOTA_NIAN_PIN_TO_STUN = 1662,
ACT_DOTA_RAZE_1 = 1663,
ACT_DOTA_RAZE_2 = 1664,
ACT_DOTA_RAZE_3 = 1665,
ACT_DOTA_UNDYING_DECAY = 1666,
ACT_DOTA_UNDYING_SOUL_RIP = 1667,
ACT_DOTA_UNDYING_TOMBSTONE = 1668,
ACT_DOTA_WHIRLING_AXES_RANGED = 1669,
ACT_DOTA_SHALLOW_GRAVE = 1670,
ACT_DOTA_COLD_FEET = 1671,
ACT_DOTA_ICE_VORTEX = 1672,
ACT_DOTA_CHILLING_TOUCH = 1673,
ACT_DOTA_ENFEEBLE = 1674,
ACT_DOTA_FATAL_BONDS = 1675,
ACT_DOTA_MIDNIGHT_PULSE = 1676,
ACT_DOTA_ANCESTRAL_SPIRIT = 1677,
ACT_DOTA_THUNDER_STRIKE = 1678,
ACT_DOTA_KINETIC_FIELD = 1679,
ACT_DOTA_STATIC_STORM = 1680,
ACT_DOTA_MINI_TAUNT = 1681,
ACT_DOTA_ARCTIC_BURN_END = 1682,
ACT_DOTA_LOADOUT_RARE = 1683,
ACT_DOTA_SWIM = 1684,
ACT_DOTA_FLEE = 1685,
ACT_DOTA_TROT = 1686,
ACT_DOTA_SHAKE = 1687,
ACT_DOTA_SWIM_IDLE = 1688,
ACT_DOTA_WAIT_IDLE = 1689,
ACT_DOTA_GREET = 1690,
ACT_DOTA_TELEPORT_COOP_START = 1691,
ACT_DOTA_TELEPORT_COOP_WAIT = 1692,
ACT_DOTA_TELEPORT_COOP_END = 1693,
ACT_DOTA_TELEPORT_COOP_EXIT = 1694,
ACT_DOTA_SHOPKEEPER_PET_INTERACT = 1695,
ACT_DOTA_ITEM_PICKUP = 1696,
ACT_DOTA_ITEM_DROP = 1697,
ACT_DOTA_CAPTURE_PET = 1698,
ACT_DOTA_PET_WARD_OBSERVER = 1699,
ACT_DOTA_PET_WARD_SENTRY = 1700,
ACT_DOTA_PET_LEVEL = 1701,
ACT_DOTA_CAST_BURROW_END = 1702,
ACT_DOTA_LIFESTEALER_ASSIMILATE = 1703,
ACT_DOTA_LIFESTEALER_EJECT = 1704,
ACT_DOTA_ATTACK_EVENT_BASH = 1705,
ACT_DOTA_CAPTURE_RARE = 1706,
ACT_DOTA_AW_MAGNETIC_FIELD = 1707,
ACT_DOTA_CAST_GHOST_SHIP = 1708,
ACT_DOTA_FXANIM = 1709,
ACT_DOTA_VICTORY_START = 1710,
ACT_DOTA_DEFEAT_START = 1711,
ACT_DOTA_DP_SPIRIT_SIPHON = 1712,
ACT_DOTA_TRICKS_END = 1713,
ACT_DOTA_ES_STONE_CALLER = 1714,
ACT_DOTA_MK_STRIKE = 1715,
ACT_DOTA_VERSUS = 1716,
ACT_DOTA_CAPTURE_CARD = 1717,
ACT_DOTA_MK_SPRING_SOAR = 1718,
ACT_DOTA_MK_SPRING_END = 1719,
ACT_DOTA_MK_TREE_SOAR = 1720,
ACT_DOTA_MK_TREE_END = 1721,
ACT_DOTA_MK_FUR_ARMY = 1722,
ACT_DOTA_MK_SPRING_CAST = 1723
}
declare enum DOTAMinimapEvent_t {
DOTA_MINIMAP_EVENT_ANCIENT_UNDER_ATTACK = 2,
DOTA_MINIMAP_EVENT_BASE_UNDER_ATTACK = 4,
DOTA_MINIMAP_EVENT_BASE_GLYPHED = 8,
DOTA_MINIMAP_EVENT_TEAMMATE_UNDER_ATTACK = 16,
DOTA_MINIMAP_EVENT_TEAMMATE_TELEPORTING = 32,
DOTA_MINIMAP_EVENT_TEAMMATE_DIED = 64,
DOTA_MINIMAP_EVENT_TUTORIAL_TASK_ACTIVE = 128,
DOTA_MINIMAP_EVENT_TUTORIAL_TASK_FINISHED = 256,
DOTA_MINIMAP_EVENT_HINT_LOCATION = 512,
DOTA_MINIMAP_EVENT_ENEMY_TELEPORTING = 1024,
DOTA_MINIMAP_EVENT_CANCEL_TELEPORTING = 2048,
DOTA_MINIMAP_EVENT_RADAR = 4096,
DOTA_MINIMAP_EVENT_RADAR_TARGET = 8192
}
declare enum DOTASlotType_t {
DOTA_LOADOUT_TYPE_INVALID = -1,
DOTA_LOADOUT_TYPE_WEAPON = 0,
DOTA_LOADOUT_TYPE_OFFHAND_WEAPON = 1,
DOTA_LOADOUT_TYPE_WEAPON2 = 2,
DOTA_LOADOUT_TYPE_OFFHAND_WEAPON2 = 3,
DOTA_LOADOUT_TYPE_HEAD = 4,
DOTA_LOADOUT_TYPE_SHOULDER = 5,
DOTA_LOADOUT_TYPE_ARMS = 6,
DOTA_LOADOUT_TYPE_ARMOR = 7,
DOTA_LOADOUT_TYPE_BELT = 8,
DOTA_LOADOUT_TYPE_NECK = 9,
DOTA_LOADOUT_TYPE_BACK = 10,
DOTA_LOADOUT_TYPE_LEGS = 11,
DOTA_LOADOUT_TYPE_GLOVES = 12,
DOTA_LOADOUT_TYPE_TAIL = 13,
DOTA_LOADOUT_TYPE_MISC = 14,
DOTA_LOADOUT_TYPE_BODY_HEAD = 15,
DOTA_LOADOUT_TYPE_MOUNT = 16,
DOTA_LOADOUT_TYPE_SUMMON = 17,
DOTA_LOADOUT_TYPE_SHAPESHIFT = 18,
DOTA_LOADOUT_TYPE_TAUNT = 19,
DOTA_LOADOUT_TYPE_AMBIENT_EFFECTS = 20,
DOTA_LOADOUT_TYPE_ABILITY_ATTACK = 21,
DOTA_LOADOUT_TYPE_ABILITY1 = 22,
DOTA_LOADOUT_TYPE_ABILITY2 = 23,
DOTA_LOADOUT_TYPE_ABILITY3 = 24,
DOTA_LOADOUT_TYPE_ABILITY4 = 25,
DOTA_LOADOUT_TYPE_ABILITY_ULTIMATE = 26,
DOTA_LOADOUT_TYPE_VOICE = 27,
DOTA_LOADOUT_TYPE_ACTION_ITEM = 28,
DOTA_LOADOUT_TYPE_COURIER = 29,
DOTA_LOADOUT_TYPE_ANNOUNCER = 30,
DOTA_LOADOUT_TYPE_MEGA_KILLS = 31,
DOTA_LOADOUT_TYPE_MUSIC = 32,
DOTA_LOADOUT_TYPE_WARD = 33,
DOTA_LOADOUT_TYPE_HUD_SKIN = 34,
DOTA_LOADOUT_TYPE_LOADING_SCREEN = 35,
DOTA_LOADOUT_TYPE_WEATHER = 36,
DOTA_LOADOUT_TYPE_HEROIC_STATUE = 37,
DOTA_LOADOUT_TYPE_MULTIKILL_BANNER = 38,
DOTA_LOADOUT_TYPE_CURSOR_PACK = 39,
DOTA_LOADOUT_TYPE_TELEPORT_EFFECT = 40,
DOTA_LOADOUT_TYPE_BLINK_EFFECT = 41,
DOTA_LOADOUT_TYPE_TEAM_SHOWCASE = 42,
DOTA_LOADOUT_TYPE_TERRAIN = 43,
DOTA_PLAYER_LOADOUT_START = 28,
DOTA_PLAYER_LOADOUT_END = 43,
DOTA_LOADOUT_TYPE_NONE = 44,
DOTA_LOADOUT_TYPE_COUNT = 45
}
declare enum modifierfunction {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE = 0,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE_PROC = 1,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE_POST_CRIT = 2,
MODIFIER_PROPERTY_BASEATTACK_BONUSDAMAGE = 3,
MODIFIER_PROPERTY_PROCATTACK_BONUS_DAMAGE_PHYSICAL = 4,
MODIFIER_PROPERTY_PROCATTACK_BONUS_DAMAGE_MAGICAL = 5,
MODIFIER_PROPERTY_PROCATTACK_BONUS_DAMAGE_PURE = 6,
MODIFIER_PROPERTY_PROCATTACK_FEEDBACK = 7,
MODIFIER_PROPERTY_PRE_ATTACK = 8,
MODIFIER_PROPERTY_INVISIBILITY_LEVEL = 9,
MODIFIER_PROPERTY_PERSISTENT_INVISIBILITY = 10,
MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT = 11,
MODIFIER_PROPERTY_MOVESPEED_BASE_OVERRIDE = 12,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE = 13,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE_UNIQUE = 14,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE_UNIQUE_2 = 15,
MODIFIER_PROPERTY_MOVESPEED_BONUS_UNIQUE = 16,
MODIFIER_PROPERTY_MOVESPEED_BONUS_UNIQUE_2 = 17,
MODIFIER_PROPERTY_MOVESPEED_ABSOLUTE = 18,
MODIFIER_PROPERTY_MOVESPEED_ABSOLUTE_MIN = 19,
MODIFIER_PROPERTY_MOVESPEED_LIMIT = 20,
MODIFIER_PROPERTY_MOVESPEED_MAX = 21,
MODIFIER_PROPERTY_ATTACKSPEED_BASE_OVERRIDE = 22,
MODIFIER_PROPERTY_FIXED_ATTACK_RATE = 23,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT = 24,
MODIFIER_PROPERTY_COOLDOWN_REDUCTION_CONSTANT = 25,
MODIFIER_PROPERTY_BASE_ATTACK_TIME_CONSTANT = 26,
MODIFIER_PROPERTY_ATTACK_POINT_CONSTANT = 27,
MODIFIER_PROPERTY_DAMAGEOUTGOING_PERCENTAGE = 28,
MODIFIER_PROPERTY_DAMAGEOUTGOING_PERCENTAGE_ILLUSION = 29,
MODIFIER_PROPERTY_TOTALDAMAGEOUTGOING_PERCENTAGE = 30,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE = 31,
MODIFIER_PROPERTY_HEAL_AMPLIFY_PERCENTAGE = 32,
MODIFIER_PROPERTY_MAGICDAMAGEOUTGOING_PERCENTAGE = 33,
MODIFIER_PROPERTY_BASEDAMAGEOUTGOING_PERCENTAGE = 34,
MODIFIER_PROPERTY_BASEDAMAGEOUTGOING_PERCENTAGE_UNIQUE = 35,
MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE = 36,
MODIFIER_PROPERTY_INCOMING_PHYSICAL_DAMAGE_PERCENTAGE = 37,
MODIFIER_PROPERTY_INCOMING_PHYSICAL_DAMAGE_CONSTANT = 38,
MODIFIER_PROPERTY_INCOMING_SPELL_DAMAGE_CONSTANT = 39,
MODIFIER_PROPERTY_EVASION_CONSTANT = 40,
MODIFIER_PROPERTY_NEGATIVE_EVASION_CONSTANT = 41,
MODIFIER_PROPERTY_AVOID_DAMAGE = 42,
MODIFIER_PROPERTY_AVOID_SPELL = 43,
MODIFIER_PROPERTY_MISS_PERCENTAGE = 44,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS = 45,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS_UNIQUE = 46,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS_UNIQUE_ACTIVE = 47,
MODIFIER_PROPERTY_MAGICAL_RESISTANCE_DIRECT_MODIFICATION = 48,
MODIFIER_PROPERTY_MAGICAL_RESISTANCE_BONUS = 49,
MODIFIER_PROPERTY_MAGICAL_RESISTANCE_DECREPIFY_UNIQUE = 50,
MODIFIER_PROPERTY_BASE_MANA_REGEN = 51,
MODIFIER_PROPERTY_MANA_REGEN_CONSTANT = 52,
MODIFIER_PROPERTY_MANA_REGEN_CONSTANT_UNIQUE = 53,
MODIFIER_PROPERTY_MANA_REGEN_PERCENTAGE = 54,
MODIFIER_PROPERTY_MANA_REGEN_TOTAL_PERCENTAGE = 55,
MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT = 56,
MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE = 57,
MODIFIER_PROPERTY_HEALTH_BONUS = 58,
MODIFIER_PROPERTY_MANA_BONUS = 59,
MODIFIER_PROPERTY_EXTRA_STRENGTH_BONUS = 60,
MODIFIER_PROPERTY_EXTRA_HEALTH_BONUS = 61,
MODIFIER_PROPERTY_EXTRA_MANA_BONUS = 62,
MODIFIER_PROPERTY_EXTRA_HEALTH_PERCENTAGE = 63,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS = 64,
MODIFIER_PROPERTY_STATS_AGILITY_BONUS = 65,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS = 66,
MODIFIER_PROPERTY_CAST_RANGE_BONUS = 67,
MODIFIER_PROPERTY_CAST_RANGE_BONUS_STACKING = 68,
MODIFIER_PROPERTY_ATTACK_RANGE_BONUS = 69,
MODIFIER_PROPERTY_ATTACK_RANGE_BONUS_UNIQUE = 70,
MODIFIER_PROPERTY_MAX_ATTACK_RANGE = 71,
MODIFIER_PROPERTY_PROJECTILE_SPEED_BONUS = 72,
MODIFIER_PROPERTY_REINCARNATION = 73,
MODIFIER_PROPERTY_RESPAWNTIME = 74,
MODIFIER_PROPERTY_RESPAWNTIME_PERCENTAGE = 75,
MODIFIER_PROPERTY_RESPAWNTIME_STACKING = 76,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE = 77,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE_STACKING = 78,
MODIFIER_PROPERTY_CASTTIME_PERCENTAGE = 79,
MODIFIER_PROPERTY_MANACOST_PERCENTAGE = 80,
MODIFIER_PROPERTY_DEATHGOLDCOST = 81,
MODIFIER_PROPERTY_EXP_RATE_BOOST = 82,
MODIFIER_PROPERTY_PREATTACK_CRITICALSTRIKE = 83,
MODIFIER_PROPERTY_PREATTACK_TARGET_CRITICALSTRIKE = 84,
MODIFIER_PROPERTY_MAGICAL_CONSTANT_BLOCK = 85,
MODIFIER_PROPERTY_PHYSICAL_CONSTANT_BLOCK = 86,
MODIFIER_PROPERTY_PHYSICAL_CONSTANT_BLOCK_SPECIAL = 87,
MODIFIER_PROPERTY_TOTAL_CONSTANT_BLOCK_UNAVOIDABLE_PRE_ARMOR = 88,
MODIFIER_PROPERTY_TOTAL_CONSTANT_BLOCK = 89,
MODIFIER_PROPERTY_OVERRIDE_ANIMATION = 90,
MODIFIER_PROPERTY_OVERRIDE_ANIMATION_WEIGHT = 91,
MODIFIER_PROPERTY_OVERRIDE_ANIMATION_RATE = 92,
MODIFIER_PROPERTY_ABSORB_SPELL = 93,
MODIFIER_PROPERTY_REFLECT_SPELL = 94,
MODIFIER_PROPERTY_DISABLE_AUTOATTACK = 95,
MODIFIER_PROPERTY_BONUS_DAY_VISION = 96,
MODIFIER_PROPERTY_BONUS_NIGHT_VISION = 97,
MODIFIER_PROPERTY_BONUS_NIGHT_VISION_UNIQUE = 98,
MODIFIER_PROPERTY_BONUS_VISION_PERCENTAGE = 99,
MODIFIER_PROPERTY_FIXED_DAY_VISION = 100,
MODIFIER_PROPERTY_FIXED_NIGHT_VISION = 101,
MODIFIER_PROPERTY_MIN_HEALTH = 102,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PHYSICAL = 103,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_MAGICAL = 104,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PURE = 105,
MODIFIER_PROPERTY_IS_ILLUSION = 106,
MODIFIER_PROPERTY_ILLUSION_LABEL = 107,
MODIFIER_PROPERTY_SUPER_ILLUSION = 108,
MODIFIER_PROPERTY_SUPER_ILLUSION_WITH_ULTIMATE = 109,
MODIFIER_PROPERTY_TURN_RATE_PERCENTAGE = 110,
MODIFIER_PROPERTY_DISABLE_HEALING = 111,
MODIFIER_PROPERTY_ALWAYS_ALLOW_ATTACK = 112,
MODIFIER_PROPERTY_OVERRIDE_ATTACK_MAGICAL = 113,
MODIFIER_PROPERTY_UNIT_STATS_NEEDS_REFRESH = 114,
MODIFIER_PROPERTY_BOUNTY_CREEP_MULTIPLIER = 115,
MODIFIER_PROPERTY_BOUNTY_OTHER_MULTIPLIER = 116,
MODIFIER_EVENT_ON_SPELL_TARGET_READY = 117,
MODIFIER_EVENT_ON_ATTACK_RECORD = 118,
MODIFIER_EVENT_ON_ATTACK_START = 119,
MODIFIER_EVENT_ON_ATTACK = 120,
MODIFIER_EVENT_ON_ATTACK_LANDED = 121,
MODIFIER_EVENT_ON_ATTACK_FAIL = 122,
MODIFIER_EVENT_ON_ATTACK_ALLIED = 123,
MODIFIER_EVENT_ON_PROJECTILE_DODGE = 124,
MODIFIER_EVENT_ON_ORDER = 125,
MODIFIER_EVENT_ON_UNIT_MOVED = 126,
MODIFIER_EVENT_ON_ABILITY_START = 127,
MODIFIER_EVENT_ON_ABILITY_EXECUTED = 128,
MODIFIER_EVENT_ON_ABILITY_FULLY_CAST = 129,
MODIFIER_EVENT_ON_BREAK_INVISIBILITY = 130,
MODIFIER_EVENT_ON_ABILITY_END_CHANNEL = 131,
MODIFIER_EVENT_ON_PROCESS_UPGRADE = 132,
MODIFIER_EVENT_ON_REFRESH = 133,
MODIFIER_EVENT_ON_TAKEDAMAGE = 134,
MODIFIER_EVENT_ON_STATE_CHANGED = 135,
MODIFIER_EVENT_ON_ORB_EFFECT = 136,
MODIFIER_EVENT_ON_ATTACKED = 137,
MODIFIER_EVENT_ON_DEATH = 138,
MODIFIER_EVENT_ON_RESPAWN = 139,
MODIFIER_EVENT_ON_SPENT_MANA = 140,
MODIFIER_EVENT_ON_TELEPORTING = 141,
MODIFIER_EVENT_ON_TELEPORTED = 142,
MODIFIER_EVENT_ON_SET_LOCATION = 143,
MODIFIER_EVENT_ON_HEALTH_GAINED = 144,
MODIFIER_EVENT_ON_MANA_GAINED = 145,
MODIFIER_EVENT_ON_TAKEDAMAGE_KILLCREDIT = 146,
MODIFIER_EVENT_ON_HERO_KILLED = 147,
MODIFIER_EVENT_ON_HEAL_RECEIVED = 148,
MODIFIER_EVENT_ON_BUILDING_KILLED = 149,
MODIFIER_EVENT_ON_MODEL_CHANGED = 150,
MODIFIER_PROPERTY_TOOLTIP = 151,
MODIFIER_PROPERTY_MODEL_CHANGE = 152,
MODIFIER_PROPERTY_MODEL_SCALE = 153,
MODIFIER_PROPERTY_IS_SCEPTER = 154,
MODIFIER_PROPERTY_TRANSLATE_ACTIVITY_MODIFIERS = 155,
MODIFIER_PROPERTY_TRANSLATE_ATTACK_SOUND = 156,
MODIFIER_PROPERTY_LIFETIME_FRACTION = 157,
MODIFIER_PROPERTY_PROVIDES_FOW_POSITION = 158,
MODIFIER_PROPERTY_SPELLS_REQUIRE_HP = 159,
MODIFIER_PROPERTY_FORCE_DRAW_MINIMAP = 160,
MODIFIER_PROPERTY_DISABLE_TURNING = 161,
MODIFIER_PROPERTY_IGNORE_CAST_ANGLE = 162,
MODIFIER_PROPERTY_CHANGE_ABILITY_VALUE = 163,
MODIFIER_PROPERTY_ABILITY_LAYOUT = 164,
MODIFIER_EVENT_ON_DOMINATED = 165,
MODIFIER_PROPERTY_TEMPEST_DOUBLE = 166,
MODIFIER_PROPERTY_PRESERVE_PARTICLES_ON_MODEL_CHANGE = 167,
MODIFIER_EVENT_ON_ATTACK_FINISHED = 168,
MODIFIER_PROPERTY_IGNORE_COOLDOWN = 169,
MODIFIER_PROPERTY_CAN_ATTACK_TREES = 170,
MODIFIER_PROPERTY_VISUAL_Z_DELTA = 171,
MODIFIER_PROPERTY_INCOMING_DAMAGE_ILLUSION = 172,
MODIFIER_FUNCTION_LAST = 173,
MODIFIER_FUNCTION_INVALID = 255
}
declare enum modifierstate {
MODIFIER_STATE_ROOTED = 0,
MODIFIER_STATE_DISARMED = 1,
MODIFIER_STATE_ATTACK_IMMUNE = 2,
MODIFIER_STATE_SILENCED = 3,
MODIFIER_STATE_MUTED = 4,
MODIFIER_STATE_STUNNED = 5,
MODIFIER_STATE_HEXED = 6,
MODIFIER_STATE_INVISIBLE = 7,
MODIFIER_STATE_INVULNERABLE = 8,
MODIFIER_STATE_MAGIC_IMMUNE = 9,
MODIFIER_STATE_PROVIDES_VISION = 10,
MODIFIER_STATE_NIGHTMARED = 11,
MODIFIER_STATE_BLOCK_DISABLED = 12,
MODIFIER_STATE_EVADE_DISABLED = 13,
MODIFIER_STATE_UNSELECTABLE = 14,
MODIFIER_STATE_CANNOT_TARGET_ENEMIES = 15,
MODIFIER_STATE_CANNOT_MISS = 16,
MODIFIER_STATE_SPECIALLY_DENIABLE = 17,
MODIFIER_STATE_FROZEN = 18,
MODIFIER_STATE_COMMAND_RESTRICTED = 19,
MODIFIER_STATE_NOT_ON_MINIMAP = 20,
MODIFIER_STATE_NOT_ON_MINIMAP_FOR_ENEMIES = 21,
MODIFIER_STATE_LOW_ATTACK_PRIORITY = 22,
MODIFIER_STATE_NO_HEALTH_BAR = 23,
MODIFIER_STATE_FLYING = 24,
MODIFIER_STATE_NO_UNIT_COLLISION = 25,
MODIFIER_STATE_NO_TEAM_MOVE_TO = 26,
MODIFIER_STATE_NO_TEAM_SELECT = 27,
MODIFIER_STATE_PASSIVES_DISABLED = 28,
MODIFIER_STATE_DOMINATED = 29,
MODIFIER_STATE_BLIND = 30,
MODIFIER_STATE_OUT_OF_GAME = 31,
MODIFIER_STATE_FAKE_ALLY = 32,
MODIFIER_STATE_FLYING_FOR_PATHING_PURPOSES_ONLY = 33,
MODIFIER_STATE_TRUESIGHT_IMMUNE = 34,
MODIFIER_STATE_LAST = 35
}
declare enum DOTAModifierAttribute_t {
MODIFIER_ATTRIBUTE_NONE = 0,
MODIFIER_ATTRIBUTE_PERMANENT = 1,
MODIFIER_ATTRIBUTE_MULTIPLE = 2,
MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE = 4
}
declare enum Attributes {
DOTA_ATTRIBUTE_STRENGTH = 0,
DOTA_ATTRIBUTE_AGILITY = 1,
DOTA_ATTRIBUTE_INTELLECT = 2,
DOTA_ATTRIBUTE_MAX = 3,
DOTA_ATTRIBUTE_INVALID = -1
}
declare enum ParticleAttachment_t {
PATTACH_INVALID = -1,
PATTACH_ABSORIGIN = 0,
PATTACH_ABSORIGIN_FOLLOW = 1,
PATTACH_CUSTOMORIGIN = 2,
PATTACH_CUSTOMORIGIN_FOLLOW = 3,
PATTACH_POINT = 4,
PATTACH_POINT_FOLLOW = 5,
PATTACH_EYES_FOLLOW = 6,
PATTACH_OVERHEAD_FOLLOW = 7,
PATTACH_WORLDORIGIN = 8,
PATTACH_ROOTBONE_FOLLOW = 9,
PATTACH_RENDERORIGIN_FOLLOW = 10,
PATTACH_MAIN_VIEW = 11,
PATTACH_WATERWAKE = 12,
PATTACH_CENTER_FOLLOW = 13,
MAX_PATTACH_TYPES = 14
}
declare enum DOTA_MOTION_CONTROLLER_PRIORITY {
DOTA_MOTION_CONTROLLER_PRIORITY_LOWEST = 0,
DOTA_MOTION_CONTROLLER_PRIORITY_LOW = 1,
DOTA_MOTION_CONTROLLER_PRIORITY_MEDIUM = 2,
DOTA_MOTION_CONTROLLER_PRIORITY_HIGH = 3,
DOTA_MOTION_CONTROLLER_PRIORITY_HIGHEST = 4
}
declare enum DOTASpeechType_t {
DOTA_SPEECH_USER_INVALID = 0,
DOTA_SPEECH_USER_SINGLE = 1,
DOTA_SPEECH_USER_TEAM = 2,
DOTA_SPEECH_USER_TEAM_NEARBY = 3,
DOTA_SPEECH_USER_NEARBY = 4,
DOTA_SPEECH_USER_ALL = 5,
DOTA_SPEECH_GOOD_TEAM = 6,
DOTA_SPEECH_BAD_TEAM = 7,
DOTA_SPEECH_SPECTATOR = 8,
DOTA_SPEECH_RECIPIENT_TYPE_MAX = 9
}
declare enum DOTAAbilitySpeakTrigger_t {
DOTA_ABILITY_SPEAK_START_ACTION_PHASE = 0,
DOTA_ABILITY_SPEAK_CAST = 1
}
declare enum DotaCustomUIType_t {
DOTA_CUSTOM_UI_TYPE_HUD = 0,
DOTA_CUSTOM_UI_TYPE_HERO_SELECTION = 1,
DOTA_CUSTOM_UI_TYPE_GAME_INFO = 2,
DOTA_CUSTOM_UI_TYPE_GAME_SETUP = 3,
DOTA_CUSTOM_UI_TYPE_FLYOUT_SCOREBOARD = 4,
DOTA_CUSTOM_UI_TYPE_HUD_TOP_BAR = 5,
DOTA_CUSTOM_UI_TYPE_END_SCREEN = 6,
DOTA_CUSTOM_UI_TYPE_COUNT = 7,
DOTA_CUSTOM_UI_TYPE_INVALID = -1
}
declare enum DotaDefaultUIElement_t {
DOTA_DEFAULT_UI_TOP_TIMEOFDAY = 0,
DOTA_DEFAULT_UI_TOP_HEROES = 1,
DOTA_DEFAULT_UI_FLYOUT_SCOREBOARD = 2,
DOTA_DEFAULT_UI_ACTION_PANEL = 3,
DOTA_DEFAULT_UI_ACTION_MINIMAP = 4,
DOTA_DEFAULT_UI_INVENTORY_PANEL = 5,
DOTA_DEFAULT_UI_INVENTORY_SHOP = 6,
DOTA_DEFAULT_UI_INVENTORY_ITEMS = 7,
DOTA_DEFAULT_UI_INVENTORY_QUICKBUY = 8,
DOTA_DEFAULT_UI_INVENTORY_COURIER = 9,
DOTA_DEFAULT_UI_INVENTORY_PROTECT = 10,
DOTA_DEFAULT_UI_INVENTORY_GOLD = 11,
DOTA_DEFAULT_UI_SHOP_SUGGESTEDITEMS = 12,
DOTA_DEFAULT_UI_HERO_SELECTION_TEAMS = 13,
DOTA_DEFAULT_UI_HERO_SELECTION_GAME_NAME = 14,
DOTA_DEFAULT_UI_HERO_SELECTION_CLOCK = 15,
DOTA_DEFAULT_UI_TOP_MENU_BUTTONS = 16,
DOTA_DEFAULT_UI_TOP_BAR_BACKGROUND = 17,
DOTA_DEFAULT_UI_ENDGAME = 18,
DOTA_DEFAULT_UI_ENDGAME_CHAT = 19,
DOTA_DEFAULT_UI_ELEMENT_COUNT = 20
}
declare enum PlayerUltimateStateOrTime_t {
PLAYER_ULTIMATE_STATE_READY = 0,
PLAYER_ULTIMATE_STATE_NO_MANA = -1,
PLAYER_ULTIMATE_STATE_NOT_LEVELED = -2,
PLAYER_ULTIMATE_STATE_HIDDEN = -3
}
declare enum PlayerOrderIssuer_t {
DOTA_ORDER_ISSUER_SELECTED_UNITS = 0,
DOTA_ORDER_ISSUER_CURRENT_UNIT_ONLY = 1,
DOTA_ORDER_ISSUER_HERO_ONLY = 2,
DOTA_ORDER_ISSUER_PASSED_UNIT_ONLY = 3
}
declare enum OrderQueueBehavior_t {
DOTA_ORDER_QUEUE_DEFAULT = 0,
DOTA_ORDER_QUEUE_NEVER = 1,
DOTA_ORDER_QUEUE_ALWAYS = 2
}
declare enum CLICK_BEHAVIORS {
DOTA_CLICK_BEHAVIOR_NONE = 0,
DOTA_CLICK_BEHAVIOR_MOVE = 1,
DOTA_CLICK_BEHAVIOR_ATTACK = 2,
DOTA_CLICK_BEHAVIOR_CAST = 3,
DOTA_CLICK_BEHAVIOR_DROP_ITEM = 4,
DOTA_CLICK_BEHAVIOR_DROP_SHOP_ITEM = 5,
DOTA_CLICK_BEHAVIOR_DRAG = 6,
DOTA_CLICK_BEHAVIOR_LEARN_ABILITY = 7,
DOTA_CLICK_BEHAVIOR_PATROL = 8,
DOTA_CLICK_BEHAVIOR_VECTOR_CAST = 9,
DOTA_CLICK_BEHAVIOR_RIGHT_CLICK_TARGET = 10,
DOTA_CLICK_BEHAVIOR_RADAR = 11,
DOTA_CLICK_BEHAVIOR_LAST = 12
}
declare enum AbilityLearnResult_t {
ABILITY_CAN_BE_UPGRADED = 0,
ABILITY_CANNOT_BE_UPGRADED_NOT_UPGRADABLE = 1,
ABILITY_CANNOT_BE_UPGRADED_AT_MAX = 2,
ABILITY_CANNOT_BE_UPGRADED_REQUIRES_LEVEL = 3,
ABILITY_NOT_LEARNABLE = 4
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_workorderservice_Information {
interface tab_f1tab_actualcost_Sections {
tab_6_section_1: DevKit.Controls.Section;
}
interface tab_f1tab_durationsaleamt_Sections {
f1tab_durationsaleamt_section_2: DevKit.Controls.Section;
tab_4_section_1: DevKit.Controls.Section;
}
interface tab_f1tab_estimateinfo_Sections {
f1tab_3_section_estimatesaleamt: DevKit.Controls.Section;
f1tab_estimateinfo_section_cost: DevKit.Controls.Section;
}
interface tab_f1tab_other_Sections {
tab_7_section_1: DevKit.Controls.Section;
}
interface tab_f1tab_relatesto_Sections {
tab_5_section_1: DevKit.Controls.Section;
}
interface tab_f1tab_actualcost extends DevKit.Controls.ITab {
Section: tab_f1tab_actualcost_Sections;
}
interface tab_f1tab_durationsaleamt extends DevKit.Controls.ITab {
Section: tab_f1tab_durationsaleamt_Sections;
}
interface tab_f1tab_estimateinfo extends DevKit.Controls.ITab {
Section: tab_f1tab_estimateinfo_Sections;
}
interface tab_f1tab_other extends DevKit.Controls.ITab {
Section: tab_f1tab_other_Sections;
}
interface tab_f1tab_relatesto extends DevKit.Controls.ITab {
Section: tab_f1tab_relatesto_Sections;
}
interface Tabs {
f1tab_actualcost: tab_f1tab_actualcost;
f1tab_durationsaleamt: tab_f1tab_durationsaleamt;
f1tab_estimateinfo: tab_f1tab_estimateinfo;
f1tab_other: tab_f1tab_other;
f1tab_relatesto: tab_f1tab_relatesto;
}
interface Body {
Tab: Tabs;
/** Enter any additional costs associated with this service. The values are manually entered. Note: additional cost is not unit dependent. */
msdyn_AdditionalCost: DevKit.Controls.Money;
/** Agreement Booking Service linked to this Work Order Service */
msdyn_AgreementBookingService: DevKit.Controls.Lookup;
/** Shows the resource booking detail where this product was added. */
msdyn_Booking: DevKit.Controls.Lookup;
/** Enter the commission costs associated with this service. The value is manually specified and isn't automatically calculated. */
msdyn_CommissionCosts: DevKit.Controls.Money;
/** Unique identifier for Customer Asset associated with Work Order Service. */
msdyn_CustomerAsset: DevKit.Controls.Lookup;
/** Enter the description of the service as presented to the customer. The value defaults to the description defined on the service. */
msdyn_Description: DevKit.Controls.String;
/** Choose whether to disable entitlement selection for this work order service. */
msdyn_DisableEntitlement: DevKit.Controls.Boolean;
/** Specify any discount amount on this service. Note: If you enter a discount amount you cannot enter a discount % */
msdyn_DiscountAmount: DevKit.Controls.Money;
/** Specify any discount % on this service. Note: If you enter a discount % it will overwrite the discount $ */
msdyn_DiscountPercent: DevKit.Controls.Double;
/** Shows the actual duration of service. */
msdyn_Duration: DevKit.Controls.Integer;
/** Enter the quantity you wish to bill the customer for. By default, this will default to the same value as "Quantity." */
msdyn_DurationToBill: DevKit.Controls.Integer;
/** Entitlement to apply to the Work Order Service. */
msdyn_Entitlement: DevKit.Controls.Lookup;
/** Enter a discount amount on the subtotal amount. Note: If you enter a discount amount you cannot enter a discount % */
msdyn_EstimateDiscountAmount: DevKit.Controls.Money;
/** Enter a discount % on the subtotal amount. Note: If you enter a discount % it will overwrite the discount $ */
msdyn_EstimateDiscountPercent: DevKit.Controls.Double;
/** Enter the estimated duration of this service. */
msdyn_EstimateDuration: DevKit.Controls.Integer;
/** Shows the total amount for this service, excluding discounts. */
msdyn_EstimateSubtotal: DevKit.Controls.Money;
/** Shows the estimated total amount of this service, including discounts. */
msdyn_EstimateTotalAmount: DevKit.Controls.Money;
/** Shows the estimated total cost of this service. */
msdyn_EstimateTotalCost: DevKit.Controls.Money;
/** Shows the estimated sale amount per unit. */
msdyn_EstimateUnitAmount: DevKit.Controls.Money;
/** Shows the estimated cost amount per unit. */
msdyn_EstimateUnitCost: DevKit.Controls.Money;
/** Enter any internal notes you want to track on this service. */
msdyn_InternalDescription: DevKit.Controls.String;
msdyn_LineOrder: DevKit.Controls.Integer;
/** Enter the current status of the line, estimate or used. */
msdyn_LineStatus: DevKit.Controls.OptionSet;
/** Enter the amount charged as a minimum charge. */
msdyn_MinimumChargeAmount: DevKit.Controls.Money;
/** Enter the duration of up to how long the minimum charge applies. */
msdyn_MinimumChargeDuration: DevKit.Controls.Integer;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Price List that determines the pricing for this service */
msdyn_PriceList: DevKit.Controls.Lookup;
/** Service proposed or used for this work order */
msdyn_Service: DevKit.Controls.Lookup;
/** Enter the total amount excluding discounts. */
msdyn_Subtotal: DevKit.Controls.Money;
/** Specify if service is taxable. If you do not wish to charge tax set this field to No. */
msdyn_Taxable: DevKit.Controls.Boolean;
msdyn_TotalAmount: DevKit.Controls.Money;
/** Shows the total cost of this service. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs. */
msdyn_TotalCost: DevKit.Controls.Money;
/** The unit that determines the final quantity for this service */
msdyn_Unit: DevKit.Controls.Lookup;
/** Enter the amount you want to charge the customer per unit. By default, this is calculated based on the selected price list. The amount can be changed. */
msdyn_UnitAmount: DevKit.Controls.Money;
/** Shows the actual cost per unit. */
msdyn_UnitCost: DevKit.Controls.Money;
/** The work order this service relates to */
msdyn_WorkOrder: DevKit.Controls.Lookup;
/** The Incident related to this product */
msdyn_WorkOrderIncident: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Unique identifier of the currency associated with the entity. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Work Order Service */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
navProcessSessions: DevKit.Controls.NavigationItem
}
}
class Formmsdyn_workorderservice_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_workorderservice_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_workorderservice_Information */
Body: DevKit.Formmsdyn_workorderservice_Information.Body;
/** The Footer section of form msdyn_workorderservice_Information */
Footer: DevKit.Formmsdyn_workorderservice_Information.Footer;
/** The Navigation of form msdyn_workorderservice_Information */
Navigation: DevKit.Formmsdyn_workorderservice_Information.Navigation;
}
namespace FormWork_Order_Service_Mobile {
interface tab_fstab_estimate_Sections {
fstab_estimate_section_cost: DevKit.Controls.Section;
fstab_estimate_section_sale: DevKit.Controls.Section;
}
interface tab_fstab_general_Sections {
fstab_general_section_5: DevKit.Controls.Section;
fstab_general_section_description: DevKit.Controls.Section;
fstab_general_section_general: DevKit.Controls.Section;
fstab_general_section_misc: DevKit.Controls.Section;
fstab_sub_grids_section: DevKit.Controls.Section;
}
interface tab_fstab_pricing_Sections {
fstab_pricing_section_cost: DevKit.Controls.Section;
fstab_pricing_section_minimum_charge: DevKit.Controls.Section;
fstab_pricing_section_sale: DevKit.Controls.Section;
}
interface tab_fstab_estimate extends DevKit.Controls.ITab {
Section: tab_fstab_estimate_Sections;
}
interface tab_fstab_general extends DevKit.Controls.ITab {
Section: tab_fstab_general_Sections;
}
interface tab_fstab_pricing extends DevKit.Controls.ITab {
Section: tab_fstab_pricing_Sections;
}
interface Tabs {
fstab_estimate: tab_fstab_estimate;
fstab_general: tab_fstab_general;
fstab_pricing: tab_fstab_pricing;
}
interface Body {
Tab: Tabs;
/** Enter any additional costs associated with this service. The values are manually entered. Note: additional cost is not unit dependent. */
msdyn_AdditionalCost: DevKit.Controls.Money;
/** Shows the resource booking detail where this product was added. */
msdyn_Booking: DevKit.Controls.Lookup;
/** Enter the commission costs associated with this service. The value is manually specified and isn't automatically calculated. */
msdyn_CommissionCosts: DevKit.Controls.Money;
/** Unique identifier for Customer Asset associated with Work Order Service. */
msdyn_CustomerAsset: DevKit.Controls.Lookup;
/** Enter the description of the service as presented to the customer. The value defaults to the description defined on the service. */
msdyn_Description: DevKit.Controls.String;
/** Choose whether to disable entitlement selection for this work order service. */
msdyn_DisableEntitlement: DevKit.Controls.Boolean;
/** Specify any discount amount on this service. Note: If you enter a discount amount you cannot enter a discount % */
msdyn_DiscountAmount: DevKit.Controls.Money;
/** Specify any discount % on this service. Note: If you enter a discount % it will overwrite the discount $ */
msdyn_DiscountPercent: DevKit.Controls.Double;
/** Shows the actual duration of service. */
msdyn_Duration: DevKit.Controls.Integer;
/** Enter the quantity you wish to bill the customer for. By default, this will default to the same value as "Quantity." */
msdyn_DurationToBill: DevKit.Controls.Integer;
/** Entitlement to apply to the Work Order Service. */
msdyn_Entitlement: DevKit.Controls.Lookup;
/** Enter a discount amount on the subtotal amount. Note: If you enter a discount amount you cannot enter a discount % */
msdyn_EstimateDiscountAmount: DevKit.Controls.Money;
/** Enter a discount % on the subtotal amount. Note: If you enter a discount % it will overwrite the discount $ */
msdyn_EstimateDiscountPercent: DevKit.Controls.Double;
/** Enter the estimated duration of this service. */
msdyn_EstimateDuration: DevKit.Controls.Integer;
/** Shows the total amount for this service, excluding discounts. */
msdyn_EstimateSubtotal: DevKit.Controls.Money;
/** Shows the estimated total amount of this service, including discounts. */
msdyn_EstimateTotalAmount: DevKit.Controls.Money;
/** Shows the estimated total cost of this service. */
msdyn_EstimateTotalCost: DevKit.Controls.Money;
/** Shows the estimated sale amount per unit. */
msdyn_EstimateUnitAmount: DevKit.Controls.Money;
/** Shows the estimated cost amount per unit. */
msdyn_EstimateUnitCost: DevKit.Controls.Money;
/** Enter any internal notes you want to track on this service. */
msdyn_InternalDescription: DevKit.Controls.String;
msdyn_LineOrder: DevKit.Controls.Integer;
/** Enter the current status of the line, estimate or used. */
msdyn_LineStatus: DevKit.Controls.OptionSet;
/** Enter the amount charged as a minimum charge. */
msdyn_MinimumChargeAmount: DevKit.Controls.Money;
/** Enter the duration of up to how long the minimum charge applies. */
msdyn_MinimumChargeDuration: DevKit.Controls.Integer;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Price List that determines the pricing for this service */
msdyn_PriceList: DevKit.Controls.Lookup;
/** Service proposed or used for this work order */
msdyn_Service: DevKit.Controls.Lookup;
/** Enter the total amount excluding discounts. */
msdyn_Subtotal: DevKit.Controls.Money;
/** Specify if service is taxable. If you do not wish to charge tax set this field to No. */
msdyn_Taxable: DevKit.Controls.Boolean;
msdyn_TotalAmount: DevKit.Controls.Money;
/** Shows the total cost of this service. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs. */
msdyn_TotalCost: DevKit.Controls.Money;
/** The unit that determines the final quantity for this service */
msdyn_Unit: DevKit.Controls.Lookup;
/** Enter the amount you want to charge the customer per unit. By default, this is calculated based on the selected price list. The amount can be changed. */
msdyn_UnitAmount: DevKit.Controls.Money;
/** Shows the actual cost per unit. */
msdyn_UnitCost: DevKit.Controls.Money;
/** The work order this service relates to */
msdyn_WorkOrder: DevKit.Controls.Lookup;
/** The Incident related to this product */
msdyn_WorkOrderIncident: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Unique identifier of the currency associated with the entity. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
interface Navigation {
nav_msdyn_msdyn_workorderservice_invoicedetail: DevKit.Controls.NavigationItem,
navAsyncOperations: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
}
class FormWork_Order_Service_Mobile extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Work_Order_Service_Mobile
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Work_Order_Service_Mobile */
Body: DevKit.FormWork_Order_Service_Mobile.Body;
/** The Navigation of form Work_Order_Service_Mobile */
Navigation: DevKit.FormWork_Order_Service_Mobile.Navigation;
}
class msdyn_workorderserviceApi {
/**
* DynamicsCrm.DevKit msdyn_workorderserviceApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the exchange rate for the currency associated with the entity with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Shows the sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Enter any additional costs associated with this service. The values are manually entered. Note: additional cost is not unit dependent. */
msdyn_AdditionalCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the additional cost in the base currency. */
msdyn_additionalcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Agreement Booking Service linked to this Work Order Service */
msdyn_AgreementBookingService: DevKit.WebApi.LookupValue;
/** Shows the resource booking detail where this product was added. */
msdyn_Booking: DevKit.WebApi.LookupValue;
/** Shows the sale amount per unit calculated by the system considering the minimum charge, if applicable. */
msdyn_CalculatedUnitAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the calculated unit amount in the base currency. */
msdyn_calculatedunitamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter the commission costs associated with this service. The value is manually specified and isn't automatically calculated. */
msdyn_CommissionCosts: DevKit.WebApi.MoneyValue;
/** Shows the value of the commission costs in the base currency. */
msdyn_commissioncosts_Base: DevKit.WebApi.MoneyValueReadonly;
/** Unique identifier for Customer Asset associated with Work Order Service. */
msdyn_CustomerAsset: DevKit.WebApi.LookupValue;
/** Enter the description of the service as presented to the customer. The value defaults to the description defined on the service. */
msdyn_Description: DevKit.WebApi.StringValue;
/** Choose whether to disable entitlement selection for this work order service. */
msdyn_DisableEntitlement: DevKit.WebApi.BooleanValue;
/** Specify any discount amount on this service. Note: If you enter a discount amount you cannot enter a discount % */
msdyn_DiscountAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the discount Amount in the base currency. */
msdyn_discountamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Specify any discount % on this service. Note: If you enter a discount % it will overwrite the discount $ */
msdyn_DiscountPercent: DevKit.WebApi.DoubleValue;
/** Shows the actual duration of service. */
msdyn_Duration: DevKit.WebApi.IntegerValue;
/** Enter the quantity you wish to bill the customer for. By default, this will default to the same value as "Quantity." */
msdyn_DurationToBill: DevKit.WebApi.IntegerValue;
/** Entitlement to apply to the Work Order Service. */
msdyn_Entitlement: DevKit.WebApi.LookupValue;
/** Shows the estimated sale amount per unit calculated by the system considering the initial charge (if applicable). */
msdyn_EstimateCalculatedUnitAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimate calculated unit amount in the base currency. */
msdyn_estimatecalculatedunitamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter a discount amount on the subtotal amount. Note: If you enter a discount amount you cannot enter a discount % */
msdyn_EstimateDiscountAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimate discount amount in the base currency. */
msdyn_estimatediscountamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter a discount % on the subtotal amount. Note: If you enter a discount % it will overwrite the discount $ */
msdyn_EstimateDiscountPercent: DevKit.WebApi.DoubleValue;
/** Enter the estimated duration of this service. */
msdyn_EstimateDuration: DevKit.WebApi.IntegerValue;
/** Shows the total amount for this service, excluding discounts. */
msdyn_EstimateSubtotal: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimate subtotal in the base currency. */
msdyn_estimatesubtotal_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the estimated total amount of this service, including discounts. */
msdyn_EstimateTotalAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimate total amount in the base currency. */
msdyn_estimatetotalamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the estimated total cost of this service. */
msdyn_EstimateTotalCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimate total cost in the base currency. */
msdyn_estimatetotalcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the estimated sale amount per unit. */
msdyn_EstimateUnitAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimate unit amount in the base currency. */
msdyn_estimateunitamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the estimated cost amount per unit. */
msdyn_EstimateUnitCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimate unit cost in the base currency. */
msdyn_estimateunitcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter any internal notes you want to track on this service. */
msdyn_InternalDescription: DevKit.WebApi.StringValue;
msdyn_InternalFlags: DevKit.WebApi.StringValue;
msdyn_LineOrder: DevKit.WebApi.IntegerValue;
/** Enter the current status of the line, estimate or used. */
msdyn_LineStatus: DevKit.WebApi.OptionSetValue;
/** Enter the amount charged as a minimum charge. */
msdyn_MinimumChargeAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the minimum charge amount in the base currency. */
msdyn_minimumchargeamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter the duration of up to how long the minimum charge applies. */
msdyn_MinimumChargeDuration: DevKit.WebApi.IntegerValue;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Price List that determines the pricing for this service */
msdyn_PriceList: DevKit.WebApi.LookupValue;
/** Service proposed or used for this work order */
msdyn_Service: DevKit.WebApi.LookupValue;
/** Enter the total amount excluding discounts. */
msdyn_Subtotal: DevKit.WebApi.MoneyValue;
/** Shows the value of the subtotal in the base currency. */
msdyn_subtotal_Base: DevKit.WebApi.MoneyValueReadonly;
/** Specify if service is taxable. If you do not wish to charge tax set this field to No. */
msdyn_Taxable: DevKit.WebApi.BooleanValue;
msdyn_TotalAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the total amount in the base currency. */
msdyn_totalamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total cost of this service. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs. */
msdyn_TotalCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the total cost in the base currency. */
msdyn_totalcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** The unit that determines the final quantity for this service */
msdyn_Unit: DevKit.WebApi.LookupValue;
/** Enter the amount you want to charge the customer per unit. By default, this is calculated based on the selected price list. The amount can be changed. */
msdyn_UnitAmount: DevKit.WebApi.MoneyValue;
/** Shows the value of the unit amount in the base currency. */
msdyn_unitamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the actual cost per unit. */
msdyn_UnitCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the unit cost in the base currency. */
msdyn_unitcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** The work order this service relates to */
msdyn_WorkOrder: DevKit.WebApi.LookupValue;
/** The Incident related to this product */
msdyn_WorkOrderIncident: DevKit.WebApi.LookupValue;
/** Shows the entity instances. */
msdyn_workorderserviceId: DevKit.WebApi.GuidValue;
/** Shows the date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Work Order Service */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Work Order Service */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the currency associated with the entity. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Shows the time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_workorderservice {
enum msdyn_LineStatus {
/** 690970000 */
Estimated,
/** 690970001 */
Used
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information','Work Order Service - Mobile'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { expect } from 'chai';
import { FIDO2Client, Fido2ClientErrMissingParameter, Fido2ClientErrRelyPartyNotAllowed } from '..';
import { Fido2Crypto } from '../src/crypto/crypto';
describe('Options', () => {
it('pin available on environment', () => {
expect(process.env.PIN).to.be.an('string');
expect(process.env.PIN).to.have.lengthOf.above(3);
});
describe('make options', () => {
const client = new FIDO2Client({
defaultModal: false,
event: {
onRequest: async (req) => {
return true;
},
onDeviceAttached: async (device) => {
return device;
},
onEnterPin: async () => {
return process.env.PIN || '';
}
}
});
it('missing rp', () => client.makeCredential('https://vincss.net', {
publicKey: {
// rp: {
// name: 'VinCSS',
// id: 'vincss.net'
// },
challenge: Fido2Crypto.random(32),
user: {
name: 'test',
displayName: 'Test',
id: Fido2Crypto.random(32),
icon: 'icon'
},
pubKeyCredParams: [
{
alg: -7,
type: 'public-key'
}, {
type: "public-key",
alg: -257
}
],
authenticatorSelection: {
userVerification: "required"
}
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member rp is undefined.');
}));
it('missing rp.name', () => client.makeCredential('https://vincss.net', {
publicKey: {
rp: {
// name: 'VinCSS',
id: 'vincss.net'
},
challenge: Fido2Crypto.random(32),
user: {
name: 'test',
displayName: 'Test',
id: Fido2Crypto.random(32),
icon: 'icon'
},
pubKeyCredParams: [
{
alg: -7,
type: 'public-key'
}, {
type: "public-key",
alg: -257
}
],
authenticatorSelection: {
userVerification: "required"
}
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member rp.name is undefined.');
}));
it('missing challenge', () => client.makeCredential('https://vincss.net', {
publicKey: {
rp: {
name: 'VinCSS',
id: 'vincss.net'
},
// challenge: Fido2Crypto.random(32),
user: {
name: 'test',
displayName: 'Test',
id: Fido2Crypto.random(32),
icon: 'icon'
},
pubKeyCredParams: [
{
alg: -7,
type: 'public-key'
}, {
type: "public-key",
alg: -257
}
],
authenticatorSelection: {
userVerification: "required"
}
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member challenge is undefined.');
}));
it('missing user', () => client.makeCredential('https://vincss.net', {
publicKey: {
rp: {
name: 'VinCSS',
id: 'vincss.net'
},
challenge: Fido2Crypto.random(32),
// user: {
// name: 'test',
// displayName: 'Test',
// id: Fido2Crypto.random(32),
// icon: 'icon'
// },
pubKeyCredParams: [
{
alg: -7,
type: 'public-key'
}, {
type: "public-key",
alg: -257
}
],
authenticatorSelection: {
userVerification: "required"
}
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member user is undefined.');
}));
it('missing user.name', () => client.makeCredential('https://vincss.net', {
publicKey: {
rp: {
name: 'VinCSS',
id: 'vincss.net'
},
challenge: Fido2Crypto.random(32),
user: {
// name: 'test',
displayName: 'Test',
id: Fido2Crypto.random(32),
icon: 'icon'
},
pubKeyCredParams: [
{
alg: -7,
type: 'public-key'
}, {
type: "public-key",
alg: -257
}
],
authenticatorSelection: {
userVerification: "required"
}
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member user.name is undefined.');
}));
it('missing user.displayName', () => client.makeCredential('https://vincss.net', {
publicKey: {
rp: {
name: 'VinCSS',
id: 'vincss.net'
},
challenge: Fido2Crypto.random(32),
user: {
name: 'test',
// displayName: 'Test',
id: Fido2Crypto.random(32),
icon: 'icon'
},
pubKeyCredParams: [
{
alg: -7,
type: 'public-key'
}, {
type: "public-key",
alg: -257
}
],
authenticatorSelection: {
userVerification: "required"
}
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member user.displayName is undefined.');
}));
it('missing user.id', () => client.makeCredential('https://vincss.net', {
publicKey: {
rp: {
name: 'VinCSS',
id: 'vincss.net'
},
challenge: Fido2Crypto.random(32),
user: {
name: 'test',
displayName: 'Test',
// id: Fido2Crypto.random(32),
icon: 'icon'
},
pubKeyCredParams: [
{
alg: -7,
type: 'public-key'
}, {
type: "public-key",
alg: -257
}
],
authenticatorSelection: {
userVerification: "required"
}
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member user.id is undefined.');
}));
it('missing pubKeyCredParams', () => client.makeCredential('https://vincss.net', {
publicKey: {
rp: {
name: 'VinCSS',
id: 'vincss.net'
},
challenge: Fido2Crypto.random(32),
user: {
name: 'test',
displayName: 'Test',
id: Fido2Crypto.random(32),
icon: 'icon'
},
// pubKeyCredParams: [
// {
// alg: -7,
// type: 'public-key'
// }, {
// type: "public-key",
// alg: -257
// }
// ],
authenticatorSelection: {
userVerification: "required"
}
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member pubKeyCredParams is undefined.');
}));
});
describe('get options', () => {
const client = new FIDO2Client({
defaultModal: false,
event: {
onRequest: async (req) => {
return true;
},
onDeviceAttached: async (device) => {
return device;
},
onEnterPin: async () => {
return process.env.PIN || '';
}
}
});
it('missing challenge', () => client.getAssertion('https://vincss.net', {
publicKey: {
rpId: 'https://vincss.net',
// challenge: Fido2Crypto.random(32),
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrMissingParameter).to.equal(true);
expect(e.message).to.equal('required member challenge is undefined.');
}));
it('rpId missmatch', () => client.getAssertion('https://vincss.net', {
publicKey: {
rpId: 'https://oauth2.vincss.net',
challenge: Fido2Crypto.random(32),
}
} as any).catch((e: Error) => {
expect(e instanceof Fido2ClientErrRelyPartyNotAllowed).to.equal(true);
}));
});
}); | the_stack |
import { EntityReference, EntityId, EntityIdDataValue, EntityKind,
EntityResult, SearchResult, ResultList, TermResult,
Claim, WBApiResult, EntitySiteLink, TimeDataValue,
GlobeCoordinateValue, QualifiedEntityValue,
EntityMissingError, MalformedEntityIdError } from './types'
import { apiRequest } from './index'
import { wikidataEndpoint, MAX_SIMULTANEOUS_API_REQUESTS, MAX_ENTITIES_PER_API_REQUEST } from './endpoints'
import { ENTITY_PREFIX_LEN } from './sparql'
import { i18n } from '@/i18n'
import { ClaimsMap } from '@/store/entity/claims/types'
import { TaskQueue } from 'cwait'
type Props = 'info' | 'sitelinks' | 'sitelinks/urls' | 'aliases' | 'labels' | 'descriptions' | 'claims' | 'datatype'
export async function getEntities(entityIds: string[],
props: Props[],
lang?: string,
fallback = true): Promise<ResultList<EntityResult>> {
const chunks = []
const ids = entityIds.length
for (let start = 0; start <= ids; start += MAX_ENTITIES_PER_API_REQUEST) {
const end = start + MAX_ENTITIES_PER_API_REQUEST
const chunk = entityIds.slice(start, end)
if (chunk.length) {
chunks.push(chunk)
}
}
const queue = new TaskQueue(Promise, MAX_SIMULTANEOUS_API_REQUESTS)
const getChunk = queue.wrap(getEntityChunk)
const results = await Promise.all(chunks.map((chunk) => {
return getChunk(chunk, props, lang, fallback)
}))
const entities: ResultList<EntityResult> = {}
for (const chunk of results) {
if (chunk !== undefined) {
for (const [key, entity] of Object.entries(chunk)) {
entities[key] = entity
}
}
}
return entities
}
async function getEntityChunk(entityIds: string[],
props: Props[],
lang?: string,
fallback = true): Promise<ResultList<EntityResult>> {
const langCode = lang || i18n.locale
const response = await apiRequest(wikidataEndpoint, {
action: 'wbgetentities',
ids: entityIds.join('|'),
props: props.join('|'),
languages: langCode,
languagefallback: fallback,
}) as WBApiResult
return response.entities!
}
export async function getLabels(entityIds: string[], lang?: string, fallback = true) {
const entities = await getEntities(entityIds, ['labels'], lang, fallback)
const langCode = lang || i18n.locale
const labels = new Map<string, Map<string, string>>()
const nativeLabels = new Map<string, string>()
labels.set(langCode, nativeLabels)
for (const [entityId, entity] of Object.entries(entities)) {
const { kind } = parseEntityId(entityId)
let label
if (!('labels' in entity)) {
label = { value: entityId, language: langCode }
} else {
label = entity.labels![langCode]
}
if (label !== undefined) {
nativeLabels.set(entityId, label.value)
if (label.language !== langCode) {
// label in fallback language, save also to original language
if (!labels.has(label.language)) {
labels.set(label.language, new Map<string, string>())
}
labels.get(label.language)!.set(entityId, label.value)
}
} else {
// no label in native or fallback language, use id
nativeLabels.set(entityId, entityId)
}
}
return labels
}
function parseAliases(entityId: string, data: ResultList<TermResult>, lang?: string) {
const langCode = lang || i18n.locale
const aliases = new Map<string, Map<string, string[]>>()
const nativeAliases = new Map<string, string[]>()
aliases.set(langCode, nativeAliases)
if (!(langCode in data)) {
return aliases
}
const theAliases = []
for (const entry of Object.entries(data[langCode])) {
const alias = entry[1]
theAliases.push(alias.value)
if (alias.language !== langCode) {
// alias in fallback language, save also to original language
if (!aliases.has(alias.language)) {
aliases.set(alias.language, new Map<string, string[]>())
}
const fallbackAliases = aliases.get(alias.language)!
const otherAliases = fallbackAliases.get(entityId) || []
otherAliases.push(alias.value)
fallbackAliases.set(entityId, otherAliases)
}
}
nativeAliases.set(entityId, theAliases)
return aliases
}
function parseTerms(entityId: string, data: ResultList<TermResult>, lang?: string) {
const langCode = lang || i18n.locale
const terms = new Map<string, Map<string, string>>()
const nativeTerms = new Map<string, string>()
terms.set(langCode, nativeTerms)
if (!(langCode in data)) {
return terms
}
const term = data[langCode]
nativeTerms.set(entityId, term.value)
if (term.language !== langCode) {
if (!terms.has(term.language)) {
terms.set(term.language, new Map<string, string>())
}
terms.get(term.language)!.set(entityId, term.value)
}
return terms
}
export async function getEntityInfo(entityId: EntityId) {
try {
const _id = parseEntityId(entityId)
} catch (err) {
throw err
}
const entities = await getEntities([entityId], ['info']) || []
if (!(entityId in entities) ||
('missing' in entities[entityId])) {
throw new EntityMissingError(entityId)
}
}
export async function getEntityData(entityId: EntityId, lang?: string, fallback = true) {
const entities = await getEntities([entityId],
['aliases', 'labels', 'descriptions', 'info',
'claims', 'datatype', 'sitelinks'],
lang,
fallback)
if ('missing' in entities[entityId]) {
throw new EntityMissingError(entityId)
}
const entity = entities[entityId]
const labels = parseTerms(entityId, entity.labels!)
const aliases = parseAliases(entityId, entity.aliases!)
const descriptions = parseTerms(entityId, entity.descriptions!)
const claims = new Map<string, Map<string, Claim>>()
const links = entities[entityId].sitelinks || {}
const sitelinks = new Map<string, EntitySiteLink>(Object.entries(links))
const datatype = entity.datatype
claims.set(entityId,
new Map<string, Claim>(Object.entries(entities[entityId].claims!)))
return {
labels,
aliases,
descriptions,
claims,
sitelinks,
datatype,
}
}
export function parseEntityId(entityId: string): EntityReference {
const prefix = entityId.slice(0, 1).toUpperCase()
const id = parseInt(entityId.slice(1), 10)
let kind = '' as EntityKind
switch (prefix) {
case 'P':
kind = 'property'
break
case 'Q':
kind = 'item'
break
case 'L':
kind = 'lexeme'
if (isNaN(id)) {
const [entity, sub] = entityId.slice(1).split('-')
if (!entity || !sub) {
throw new MalformedEntityIdError(entityId, `Ill-formed numeric part ${entityId.slice(1)}`)
}
const subPrefix = sub.slice(0, 1).toUpperCase()
const subId = parseInt(sub.slice(1), 10)
const mainId = parseInt(entity, 10)
if (isNaN(mainId)) {
throw new MalformedEntityIdError(entityId, `Ill-formed numeric part ${entity}`)
}
if (isNaN(subId)) {
throw new MalformedEntityIdError(entityId, `Ill-formed numeric part ${sub.slice(1)}`)
}
switch (subPrefix) {
case 'S':
kind = 'sense'
break
case 'F':
kind = 'form'
break
default:
throw new MalformedEntityIdError(entityId, `Unknown subPrefix ${subPrefix}`)
}
return {
id: mainId,
kind,
subId,
}
}
break
default:
throw new MalformedEntityIdError(entityId, `Unknown prefix ${prefix}`)
}
if (isNaN(id)) {
throw new MalformedEntityIdError(entityId, `Ill-formed numeric part ${entityId.slice(1)}`)
}
return {
id,
kind,
}
}
export async function searchEntities(search: string,
options: {
lang?: string
kind?: EntityKind,
limit?: number,
offset?: number,
fallback?: boolean,
}): Promise<ResultList<SearchResult>> {
const langCode = options.lang || i18n.locale
const params = {
action: 'wbsearchentities',
search,
language: langCode,
} as any
if (options.kind !== 'item') {
params.type = options.kind
}
if (options.limit !== 7) {
params.limit = options.limit
}
if (options.offset !== undefined) {
params.continue = options.offset
}
if (options.fallback !== undefined && !options.fallback) {
params.strictlanguage = true
}
const response = await apiRequest(wikidataEndpoint, params) as WBApiResult
return response.search!
}
export async function siteLinkUrls(entityId: EntityId) {
const entities = await getEntities([entityId], ['sitelinks/urls'])
const urls: any = {}
if (entities !== undefined) {
const entity = entities[entityId]
if (entity !== undefined) {
for (const [site, sitelink] of Object.entries(entity.sitelinks!)) {
urls[site] = sitelink.url!
}
}
}
return urls
}
export function relatedEntityIds(claims: ClaimsMap) {
const entityIds = new Set()
for (const [propertyId, theClaims] of claims) {
entityIds.add(propertyId)
for (const claim of theClaims) {
const mainsnak = claim.mainsnak
entityIds.add(mainsnak.property)
if (mainsnak.snaktype === 'value' &&
['wikibase-item', 'wikibase-property', 'wikibase-lexeme'].includes(mainsnak.datatype)) {
const datavalue = (mainsnak.datavalue as EntityIdDataValue)
entityIds.add(datavalue.value.id)
}
if ('references' in claim) {
for (const reference of claim.references) {
for (const [propId, snaks] of Object.entries(reference.snaks)) {
entityIds.add(propId)
for (const snak of snaks) {
if (snak.snaktype === 'value' &&
snak.datatype === 'wikibase-item') {
const datavalue = (snak.datavalue as EntityIdDataValue)
entityIds.add(datavalue.value.id)
}
}
}
}
}
if ('qualifiers' in claim) {
for (const [propId, snaks] of Object.entries(claim.qualifiers!)) {
entityIds.add(propId)
for (const snak of snaks) {
if (snak.snaktype === 'value' &&
snak.datatype === 'wikibase-item') {
const datavalue = (snak.datavalue as EntityIdDataValue)
entityIds.add(datavalue.value.id)
}
}
}
}
}
}
return entityIds
}
export function wikidataUrl(entityId: EntityId, lang?: string) {
let forceLang = ''
if (lang !== undefined) {
forceLang = `?uselang=${lang}`
}
return `https://www.wikidata.org/entity/${entityId}${forceLang}`
}
function makeComponentValid(component: string) {
if (component === '00') {
return '01'
}
return component
}
export function dateFromTimeData(data: TimeDataValue) {
let timestring = data.value.time
const precision = data.value.precision
const calendar = data.value.calendarmodel.slice(ENTITY_PREFIX_LEN)
let negative = false
if (timestring.startsWith('+')) {
timestring = timestring.slice(1)
} else if (timestring.startsWith('-')) {
timestring = timestring.slice(1)
negative = true
}
let TZ = 'Z'
if (timestring.endsWith('Z')) {
timestring = timestring.slice(0, timestring.length - 1)
} else {
[ timestring, TZ ] = timestring.split('+')
}
const [ date, time ] = timestring.split('T')
let [ year, month, day ] = date.split('-')
const [ hour, minute, second ] = time.split(':')
if (['0000', '+0000', '-0000'].includes(year)) {
year = '0001'
}
const prefix = negative ? '-00' : ''
month = makeComponentValid(month)
day = makeComponentValid(day)
const result = new Date(`${prefix}${year}-${month}-${day}T${hour}:${minute}:${second}${TZ}`)
return { time: result,
format: `precision-${precision}`,
calendar,
year,
month,
day,
hour,
minute,
second,
negative,
}
}
function extractCoordinateComponents(value: number) {
const degrees = Math.floor(value)
value -= degrees
const minutes = Math.floor(value * 60)
value *= 60
value -= Math.floor(value)
const seconds = Math.floor(value * 60)
return { degrees,
minutes,
seconds,
}
}
export function coordinateFromGlobeCoordinate(data: GlobeCoordinateValue) {
const globe = data.value.globe.slice(ENTITY_PREFIX_LEN)
const precision = data.value.precision.toExponential()
const places = Number(precision.split('e-')[1])
const latitude = data.value.latitude
const lat = Math.abs(latitude).toFixed(places)
const ns = (latitude >= 0) ? 'N' : 'S'
const { degrees: lad, minutes: lam, seconds: las } = extractCoordinateComponents(Number(lat))
const longitude = Number(data.value.longitude)
const lon = Math.abs(longitude).toFixed(places)
const we = (longitude >= 0) ? 'W' : 'E'
const { degrees: lod, minutes: lom, seconds: los } = extractCoordinateComponents(Number(lon))
const coordinate = `(${lad}°${lam}'${las}" ${ns}, ${lod}°${lom}'${los}" ${we})`
return {
coordinate,
globe,
}
}
export function idsFromQualifiedEntity(entity: QualifiedEntityValue): EntityId[] {
const ids = [entity.value.id]
for (const [propId, snaks] of entity.qualifiers) {
ids.push(propId)
for (const snak of snaks) {
if (snak.snaktype === 'value' && snak.datavalue.type === 'wikibase-entityid') {
ids.push((snak.datavalue as EntityIdDataValue).value.id)
}
}
}
return ids
}
export function isItemId(entityId: EntityId) {
const { kind } = parseEntityId(entityId)
return kind === 'item'
}
export function isPropertyId(entityId: EntityId) {
const { kind } = parseEntityId(entityId)
return kind === 'property'
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreSyncBaseProvider, CoreSyncBlockedError } from '@classes/base-sync';
import { CoreNetworkError } from '@classes/errors/network-error';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreFileUploaderStoreFilesResult } from '@features/fileuploader/services/fileuploader';
import { CoreApp } from '@services/app';
import { CoreFileEntry } from '@services/file-helper';
import { CoreSites } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { Translate, makeSingleton } from '@singletons';
import { CoreEvents } from '@singletons/events';
import { AddonModWorkshop,
AddonModWorkshopAction,
AddonModWorkshopData,
AddonModWorkshopProvider,
AddonModWorkshopSubmissionType,
} from './workshop';
import { AddonModWorkshopHelper } from './workshop-helper';
import { AddonModWorkshopOffline,
AddonModWorkshopOfflineAssessment,
AddonModWorkshopOfflineEvaluateAssessment,
AddonModWorkshopOfflineEvaluateSubmission,
AddonModWorkshopOfflineSubmission,
} from './workshop-offline';
/**
* Service to sync workshops.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWorkshopSyncProvider extends CoreSyncBaseProvider<AddonModWorkshopSyncResult> {
static readonly AUTO_SYNCED = 'addon_mod_workshop_autom_synced';
static readonly MANUAL_SYNCED = 'addon_mod_workshop_manual_synced';
protected componentTranslatableString = 'workshop';
constructor() {
super('AddonModWorkshopSyncProvider');
}
/**
* Check if an workshop has data to synchronize.
*
* @param workshopId Workshop ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean: true if has data to sync, false otherwise.
*/
hasDataToSync(workshopId: number, siteId?: string): Promise<boolean> {
return AddonModWorkshopOffline.hasWorkshopOfflineData(workshopId, siteId);
}
/**
* Try to synchronize all workshops that need it and haven't been synchronized in a while.
*
* @param siteId Site ID to sync. If not defined, sync all sites.
* @param force Wether to force sync not depending on last execution.
* @return Promise resolved when the sync is done.
*/
syncAllWorkshops(siteId?: string, force?: boolean): Promise<void> {
return this.syncOnSites('all workshops', this.syncAllWorkshopsFunc.bind(this, !!force), siteId);
}
/**
* Sync all workshops on a site.
*
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID to sync.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
protected async syncAllWorkshopsFunc(force: boolean, siteId: string): Promise<void> {
const workshopIds = await AddonModWorkshopOffline.getAllWorkshops(siteId);
// Sync all workshops that haven't been synced for a while.
const promises = workshopIds.map(async (workshopId) => {
const data = force
? await this.syncWorkshop(workshopId, siteId)
: await this.syncWorkshopIfNeeded(workshopId, siteId);
if (data && data.updated) {
// Sync done. Send event.
CoreEvents.trigger(AddonModWorkshopSyncProvider.AUTO_SYNCED, {
workshopId: workshopId,
warnings: data.warnings,
}, siteId);
}
});
await Promise.all(promises);
}
/**
* Sync a workshop only if a certain time has passed since the last time.
*
* @param workshopId Workshop ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the workshop is synced or if it doesn't need to be synced.
*/
async syncWorkshopIfNeeded(workshopId: number, siteId?: string): Promise<AddonModWorkshopSyncResult | undefined> {
const needed = await this.isSyncNeeded(workshopId, siteId);
if (needed) {
return this.syncWorkshop(workshopId, siteId);
}
}
/**
* Try to synchronize a workshop.
*
* @param workshopId Workshop ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
syncWorkshop(workshopId: number, siteId?: string): Promise<AddonModWorkshopSyncResult> {
siteId = siteId || CoreSites.getCurrentSiteId();
const currentSyncPromise = this.getOngoingSync(workshopId, siteId);
if (currentSyncPromise) {
// There's already a sync ongoing for this discussion, return the promise.
return currentSyncPromise;
}
// Verify that workshop isn't blocked.
if (CoreSync.isBlocked(AddonModWorkshopProvider.COMPONENT, workshopId, siteId)) {
this.logger.debug(`Cannot sync workshop '${workshopId}' because it is blocked.`);
throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate }));
}
this.logger.debug(`Try to sync workshop '${workshopId}' in site ${siteId}'`);
const syncPromise = this.performSyncWorkshop(workshopId, siteId);
return this.addOngoingSync(workshopId, syncPromise, siteId);
}
/**
* Perform the workshop sync.
*
* @param workshopId Workshop ID.
* @param siteId Site ID.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
protected async performSyncWorkshop(workshopId: number, siteId: string): Promise<AddonModWorkshopSyncResult> {
const result: AddonModWorkshopSyncResult = {
warnings: [],
updated: false,
};
// Sync offline logs.
await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(AddonModWorkshopProvider.COMPONENT, workshopId, siteId));
// Get offline submissions to be sent.
const syncs = await Promise.all([
// Get offline submissions to be sent.
CoreUtils.ignoreErrors(AddonModWorkshopOffline.getSubmissions(workshopId, siteId), []),
// Get offline submission assessments to be sent.
CoreUtils.ignoreErrors(AddonModWorkshopOffline.getAssessments(workshopId, siteId), []),
// Get offline submission evaluations to be sent.
CoreUtils.ignoreErrors(AddonModWorkshopOffline.getEvaluateSubmissions(workshopId, siteId), []),
// Get offline assessment evaluations to be sent.
CoreUtils.ignoreErrors(AddonModWorkshopOffline.getEvaluateAssessments(workshopId, siteId), []),
]);
let courseId: number | undefined;
// Get courseId from the first object
for (const x in syncs) {
if (syncs[x].length > 0 && syncs[x][0].courseid) {
courseId = syncs[x][0].courseid;
break;
}
}
if (!courseId) {
// Sync finished, set sync time.
await CoreUtils.ignoreErrors(this.setSyncTime(workshopId, siteId));
// Nothing to sync.
return result;
}
if (!CoreApp.isOnline()) {
// Cannot sync in offline.
throw new CoreNetworkError();
}
const workshop = await AddonModWorkshop.getWorkshopById(courseId, workshopId, { siteId });
const submissionsActions: AddonModWorkshopOfflineSubmission[] = syncs[0];
const assessments: AddonModWorkshopOfflineAssessment[] = syncs[1];
const submissionEvaluations: AddonModWorkshopOfflineEvaluateSubmission[] = syncs[2];
const assessmentEvaluations: AddonModWorkshopOfflineEvaluateAssessment[] = syncs[3];
const offlineSubmissions: Record<string, AddonModWorkshopOfflineSubmission[]> = {};
const promises: Promise<void>[] = [];
submissionsActions.forEach((action) => {
offlineSubmissions[action.submissionid] = offlineSubmissions[action.submissionid] || [];
offlineSubmissions[action.submissionid].push(action);
});
Object.keys(offlineSubmissions).forEach((submissionId) => {
const submissionActions = offlineSubmissions[submissionId];
promises.push(this.syncSubmission(workshop, submissionActions, result, siteId).then(() => {
result.updated = true;
return;
}));
});
assessments.forEach((assessment) => {
promises.push(this.syncAssessment(workshop, assessment, result, siteId).then(() => {
result.updated = true;
return;
}));
});
submissionEvaluations.forEach((evaluation) => {
promises.push(this.syncEvaluateSubmission(workshop, evaluation, result, siteId).then(() => {
result.updated = true;
return;
}));
});
assessmentEvaluations.forEach((evaluation) => {
promises.push(this.syncEvaluateAssessment(workshop, evaluation, result, siteId).then(() => {
result.updated = true;
return;
}));
});
await Promise.all(promises);
if (result.updated) {
// Data has been sent to server. Now invalidate the WS calls.
await CoreUtils.ignoreErrors(AddonModWorkshop.invalidateContentById(workshopId, courseId, siteId));
}
// Sync finished, set sync time.
await CoreUtils.ignoreErrors(this.setSyncTime(workshopId, siteId));
// All done, return the warnings.
return result;
}
/**
* Synchronize a submission.
*
* @param workshop Workshop.
* @param submissionActions Submission actions offline data.
* @param result Object with the result of the sync.
* @param siteId Site ID.
* @return Promise resolved if success, rejected otherwise.
*/
protected async syncSubmission(
workshop: AddonModWorkshopData,
submissionActions: AddonModWorkshopOfflineSubmission[],
result: AddonModWorkshopSyncResult,
siteId: string,
): Promise<void> {
let discardError: string | undefined;
// Sort entries by timemodified.
submissionActions = submissionActions.sort((a, b) => a.timemodified - b.timemodified);
let timemodified = 0;
let submissionId = submissionActions[0].submissionid;
if (submissionId > 0) {
// Is editing.
try {
const submission = await AddonModWorkshop.getSubmission(workshop.id, submissionId, {
cmId: workshop.coursemodule,
siteId,
});
timemodified = submission.timemodified;
} catch {
timemodified = -1;
}
}
if (timemodified < 0 || timemodified >= submissionActions[0].timemodified) {
// The entry was not found in Moodle or the entry has been modified, discard the action.
result.updated = true;
discardError = Translate.instant('addon.mod_workshop.warningsubmissionmodified');
await AddonModWorkshopOffline.deleteAllSubmissionActions(workshop.id, siteId);
this.addOfflineDataDeletedWarning(result.warnings, workshop.name, discardError);
return;
}
submissionActions.forEach(async (action) => {
submissionId = action.submissionid > 0 ? action.submissionid : submissionId;
try {
let attachmentsId: number | undefined;
// Upload attachments first if any.
if (action.attachmentsid) {
const files = await AddonModWorkshopHelper.getSubmissionFilesFromOfflineFilesObject(
action.attachmentsid,
workshop.id,
siteId,
);
attachmentsId = await AddonModWorkshopHelper.uploadOrStoreSubmissionFiles(
workshop.id,
files,
false,
siteId,
);
} else {
// Remove all files.
attachmentsId = await AddonModWorkshopHelper.uploadOrStoreSubmissionFiles(
workshop.id,
[],
false,
siteId,
);
}
if (workshop.submissiontypefile == AddonModWorkshopSubmissionType.SUBMISSION_TYPE_DISABLED) {
attachmentsId = undefined;
}
// Perform the action.
switch (action.action) {
case AddonModWorkshopAction.ADD:
submissionId = await AddonModWorkshop.addSubmissionOnline(
workshop.id,
action.title,
action.content,
attachmentsId,
siteId,
);
break;
case AddonModWorkshopAction.UPDATE:
await AddonModWorkshop.updateSubmissionOnline(
submissionId,
action.title,
action.content,
attachmentsId,
siteId,
);
break;
case AddonModWorkshopAction.DELETE:
await AddonModWorkshop.deleteSubmissionOnline(submissionId, siteId);
}
} catch (error) {
if (error && CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error, this means it cannot be performed. Discard.
discardError = CoreTextUtils.getErrorMessageFromError(error);
}
// Couldn't connect to server, reject.
throw error;
}
// Delete the offline data.
result.updated = true;
await AddonModWorkshopOffline.deleteSubmissionAction(
action.workshopid,
action.action,
siteId,
);
// Delete stored files.
if (action.action == AddonModWorkshopAction.ADD || action.action == AddonModWorkshopAction.UPDATE) {
return AddonModWorkshopHelper.deleteSubmissionStoredFiles(
action.workshopid,
siteId,
);
}
});
if (discardError) {
// Submission was discarded, add a warning.
this.addOfflineDataDeletedWarning(result.warnings, workshop.name, discardError);
}
}
/**
* Synchronize an assessment.
*
* @param workshop Workshop.
* @param assessment Assessment offline data.
* @param result Object with the result of the sync.
* @param siteId Site ID.
* @return Promise resolved if success, rejected otherwise.
*/
protected async syncAssessment(
workshop: AddonModWorkshopData,
assessmentData: AddonModWorkshopOfflineAssessment,
result: AddonModWorkshopSyncResult,
siteId: string,
): Promise<void> {
let discardError: string | undefined;
const assessmentId = assessmentData.assessmentid;
let timemodified = 0;
try {
const assessment = await AddonModWorkshop.getAssessment(workshop.id, assessmentId, {
cmId: workshop.coursemodule,
siteId,
});
timemodified = assessment.timemodified;
} catch {
timemodified = -1;
}
if (timemodified < 0 || timemodified >= assessmentData.timemodified) {
// The entry was not found in Moodle or the entry has been modified, discard the action.
result.updated = true;
discardError = Translate.instant('addon.mod_workshop.warningassessmentmodified');
await AddonModWorkshopOffline.deleteAssessment(workshop.id, assessmentId, siteId);
this.addOfflineDataDeletedWarning(result.warnings, workshop.name, discardError);
return;
}
let attachmentsId = 0;
const inputData = assessmentData.inputdata;
try {
let files: CoreFileEntry[] = [];
// Upload attachments first if any.
if (inputData.feedbackauthorattachmentsid && typeof inputData.feedbackauthorattachmentsid !== 'number') {
files = await AddonModWorkshopHelper.getAssessmentFilesFromOfflineFilesObject(
<CoreFileUploaderStoreFilesResult>inputData.feedbackauthorattachmentsid,
workshop.id,
assessmentId,
siteId,
);
}
attachmentsId =
await AddonModWorkshopHelper.uploadOrStoreAssessmentFiles(workshop.id, assessmentId, files, false, siteId);
inputData.feedbackauthorattachmentsid = attachmentsId || 0;
await AddonModWorkshop.updateAssessmentOnline(assessmentId, inputData, siteId);
} catch (error) {
if (error && CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error, this means it cannot be performed. Discard.
discardError = CoreTextUtils.getErrorMessageFromError(error);
} else {
// Couldn't connect to server, reject.
throw error;
}
}
// Delete the offline data.
result.updated = true;
await AddonModWorkshopOffline.deleteAssessment(workshop.id, assessmentId, siteId);
await AddonModWorkshopHelper.deleteAssessmentStoredFiles(workshop.id, assessmentId, siteId);
if (discardError) {
// Assessment was discarded, add a warning.
this.addOfflineDataDeletedWarning(result.warnings, workshop.name, discardError);
}
}
/**
* Synchronize a submission evaluation.
*
* @param workshop Workshop.
* @param evaluate Submission evaluation offline data.
* @param result Object with the result of the sync.
* @param siteId Site ID.
* @return Promise resolved if success, rejected otherwise.
*/
protected async syncEvaluateSubmission(
workshop: AddonModWorkshopData,
evaluate: AddonModWorkshopOfflineEvaluateSubmission,
result: AddonModWorkshopSyncResult,
siteId: string,
): Promise<void> {
let discardError: string | undefined;
const submissionId = evaluate.submissionid;
let timemodified = 0;
try {
const submission = await AddonModWorkshop.getSubmission(workshop.id, submissionId, {
cmId: workshop.coursemodule,
siteId,
});
timemodified = submission.timemodified;
} catch {
timemodified = -1;
}
if (timemodified < 0 || timemodified >= evaluate.timemodified) {
// The entry was not found in Moodle or the entry has been modified, discard the action.
result.updated = true;
discardError = Translate.instant('addon.mod_workshop.warningsubmissionmodified');
await AddonModWorkshopOffline.deleteEvaluateSubmission(workshop.id, submissionId, siteId);
this.addOfflineDataDeletedWarning(result.warnings, workshop.name, discardError);
return;
}
try {
await AddonModWorkshop.evaluateSubmissionOnline(
submissionId,
evaluate.feedbacktext,
evaluate.published,
evaluate.gradeover,
siteId,
);
} catch (error) {
if (error && CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error, this means it cannot be performed. Discard.
discardError = CoreTextUtils.getErrorMessageFromError(error);
} else {
// Couldn't connect to server, reject.
throw error;
}
}
// Delete the offline data.
result.updated = true;
await AddonModWorkshopOffline.deleteEvaluateSubmission(workshop.id, submissionId, siteId);
if (discardError) {
// Assessment was discarded, add a warning.
this.addOfflineDataDeletedWarning(result.warnings, workshop.name, discardError);
}
}
/**
* Synchronize a assessment evaluation.
*
* @param workshop Workshop.
* @param evaluate Assessment evaluation offline data.
* @param result Object with the result of the sync.
* @param siteId Site ID.
* @return Promise resolved if success, rejected otherwise.
*/
protected async syncEvaluateAssessment(
workshop: AddonModWorkshopData,
evaluate: AddonModWorkshopOfflineEvaluateAssessment,
result: AddonModWorkshopSyncResult,
siteId: string,
): Promise<void> {
let discardError: string | undefined;
const assessmentId = evaluate.assessmentid;
let timemodified = 0;
try {
const assessment = await AddonModWorkshop.getAssessment(workshop.id, assessmentId, {
cmId: workshop.coursemodule,
siteId,
});
timemodified = assessment.timemodified;
} catch {
timemodified = -1;
}
if (timemodified < 0 || timemodified >= evaluate.timemodified) {
// The entry was not found in Moodle or the entry has been modified, discard the action.
result.updated = true;
discardError = Translate.instant('addon.mod_workshop.warningassessmentmodified');
return AddonModWorkshopOffline.deleteEvaluateAssessment(workshop.id, assessmentId, siteId);
}
try {
await AddonModWorkshop.evaluateAssessmentOnline(
assessmentId,
evaluate.feedbacktext,
evaluate.weight,
evaluate.gradinggradeover,
siteId,
);
} catch (error) {
if (error && CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error, this means it cannot be performed. Discard.
discardError = CoreTextUtils.getErrorMessageFromError(error);
} else {
// Couldn't connect to server, reject.
throw error;
}
}
// Delete the offline data.
result.updated = true;
await AddonModWorkshopOffline.deleteEvaluateAssessment(workshop.id, assessmentId, siteId);
if (discardError) {
// Assessment was discarded, add a warning.
this.addOfflineDataDeletedWarning(result.warnings, workshop.name, discardError);
}
}
}
export const AddonModWorkshopSync = makeSingleton(AddonModWorkshopSyncProvider);
export type AddonModWorkshopAutoSyncData = {
workshopId: number;
warnings: string[];
};
export type AddonModWorkshopSyncResult = {
warnings: string[];
updated: boolean;
}; | the_stack |
import { NumberFormatOptions, DateFormatOptions, merge } from '@syncfusion/ej2-base';
import { TextAlign, ClipMode, ValueAccessor, IEditCell, IFilter } from '@syncfusion/ej2-grids';
import { IGanttCellFormatter } from '../base/interface';
import { SortComparer} from '@syncfusion/ej2-grids';
/**
* Configures column collection in Gantt.
*/
export class Column {
/**
* If `allowEditing` set to false, then it disables editing of a particular column.
* By default all columns are editable.
*
* @default true
*/
public allowEditing: boolean = true;
/**
* If `allowReordering` set to false, then it disables reorder of a particular column.
* By default all columns can be reorder.
*
* @default true
*/
public allowReordering: boolean = true;
/**
* If `allowResizing` is set to false, it disables resize option of a particular column.
* By default all the columns can be resized.
*
* @default true
*/
public allowResizing: boolean = true;
/**
* If `allowSorting` set to false, then it disables sorting option of a particular column.
* By default all columns are sortable.
*
* @default true
*/
public allowSorting: boolean = true;
/**
* If `allowFiltering` set to false, then it disables filtering option and filter bar element of a particular column.
* By default all columns are filterable.
*
* @default true
*/
public allowFiltering: boolean = true;
/**
* It is used to customize the default filter options for a specific columns.
* * ui - to render custom component for specific column it has following functions.
* * ui.create – It is used for creating custom components.
* * ui.read - It is used for read the value from the component.
* * ui.write - It is used to apply component model as dynamically.
*
* @default null
*/
public filter: IFilter;
/**
* Defines the cell content's overflow mode. The available modes are
* * `Clip` - Truncates the cell content when it overflows its area.
* * `Ellipsis` - Displays ellipsis when the cell content overflows its area.
* * `EllipsisWithTooltip` - Displays ellipsis when the cell content overflows its area
* also it will display tooltip while hover on ellipsis applied cell.
*
* @default Syncfusion.EJ2.Grids.ClipMode.EllipsisWithTooltip
* @isEnumeration true
* @aspType Syncfusion.EJ2.Grids.ClipMode
*/
public clipMode: ClipMode;
/**
* The CSS styles and attributes of the content cells of a particular column can be customized.
*
* @default null
*/
public customAttributes: { [x: string]: Object };
/**
* If `disableHtmlEncode` is set to true, it encodes the HTML of the header and content cells.
*
* @default false
*/
public disableHtmlEncode: boolean;
/**
* If `displayAsCheckBox` is set to true, it displays the column value as a check box instead of Boolean value.
*
* @default false
*/
public displayAsCheckBox: boolean;
/**
* Defines the type of component for editing.
*
* @default 'stringedit'
*/
public editType: string;
/**
* Defines the custom sort comparer function.
*/
public sortComparer: SortComparer | string;
/**
* Defines the field name of column which is mapped with mapping name of DataSource.
* The `field` name must be a valid JavaScript identifier,
* the first character must be an alphabet and should not contain spaces and special characters.
*/
public field: string;
/**
* It is used to change display value with the given format and does not affect the original data.
* Gets the format from the user which can be standard or custom
* [`number`](../../../common/internationalization/#number-formatting)
* and [`date`](../../../common/internationalization/#formatting) formats.
*
* @default null
* @aspType string
*/
public format: string | NumberFormatOptions | DateFormatOptions;
/**
* Defines the method which is used to achieve custom formatting from an external function.
* This function triggers before rendering of each cell.
*
* @default null
*/
public formatter: { new(): IGanttCellFormatter } | Function | IGanttCellFormatter;
/**
* Defines the header template as string or HTML element ID which is used to add customized element in the column header.
*
* @default null
*/
public headerTemplate: string;
/**
* Defines the header text of column which is used to display in column header.
* If `headerText` is not defined, then field name value will be assigned to header text.
*
* @default null
*/
public headerText: string;
/**
* Define the alignment of column header which is used to align the text of column header.
*
* @default Syncfusion.EJ2.Grids.TextAlign.Left
* @isEnumeration true
* @aspType Syncfusion.EJ2.Grids.TextAlign
*/
public headerTextAlign: TextAlign;
/**
* Column visibility can change based on [`Media Queries`](http://cssmediaqueries.com/what-are-css-media-queries.html).
* `hideAtMedia` accepts only valid Media Queries.
*
* @default null
*/
public hideAtMedia: string;
/**
* Defines the maximum width of the column in pixel or percentage, which will restrict resizing beyond this pixel or percentage.
*
* @default null
*/
public maxWidth: string | number;
/**
* Defines the minimum width of the column in pixels or percentage.
*
* @default null
*/
public minWidth: string | number;
/**
* Defines the column template that renders customized element in each cell of the column.
* It accepts either template string or HTML element ID.
*
* @default null
*/
public template: string;
/**
* Defines the alignment of the column in both header and content cells.
*
* @default Syncfusion.EJ2.Grids.TextAlign.Left
* @isEnumeration true
* @aspType Syncfusion.EJ2.Grids.TextAlign
*/
public textAlign: TextAlign;
/**
* Defines the method used to apply custom cell values from external function and display this on each cell rendered.
*
* @default null
*/
public valueAccessor: ValueAccessor | string;
/**
* If `visible` is set to false, hides the particular column. By default, columns are displayed.
*
* @default true
*/
public visible: boolean;
/**
* Defines the width of the column in pixels or percentage.
*
* @default null
*/
public width: string | number;
/**
* If `isPrimaryKey` is set to true, considers this column as the primary key constraint.
*
* @default false
*/
public isPrimaryKey: boolean;
/**
* Defines the `IEditCell` object to customize default edit cell.
*
* @default {}
*/
public edit: IEditCell = {};
constructor(options: ColumnModel) {
merge(this, options);
}
}
/**
* Interface for a class GanttColumn
*/
export interface ColumnModel {
/**
* If `allowEditing` set to false, then it disables editing of a particular column.
* By default all columns are editable.
*
* @default true
*/
allowEditing?: boolean;
/**
* If `allowReordering` set to false, then it disables reorder of a particular column.
* By default all columns can be reorder.
*
* @default true
*/
allowReordering?: boolean;
/**
* If `allowResizing` is set to false, it disables resize option of a particular column.
* By default all the columns can be resized.
*
* @default true
*/
allowResizing?: boolean;
/**
* If `allowSorting` set to false, then it disables sorting option of a particular column.
* By default all columns are sortable.
*
* @default true
*/
allowSorting?: boolean;
/**
* If `allowFiltering` set to false, then it disables filtering option and filter bar element of a particular column.
* By default all columns are filterable.
*
* @default true
*/
allowFiltering?: boolean;
/**
* It is used to customize the default filter options for a specific columns.
* * ui - to render custom component for specific column it has following functions.
* * ui.create – It is used for creating custom components.
* * ui.read - It is used for read the value from the component.
* * ui.write - It is used to apply component model as dynamically.
*
* @default null
*/
filter?: IFilter;
/**
* Defines the cell content's overflow mode. The available modes are
* * `Clip` - Truncates the cell content when it overflows its area.
* * `Ellipsis` - Displays ellipsis when the cell content overflows its area.
* * `EllipsisWithTooltip` - Displays ellipsis when the cell content overflows its area
* also it will display tooltip while hover on ellipsis applied cell.
*
* @default Syncfusion.EJ2.Grids.ClipMode.EllipsisWithTooltip
* @isEnumeration true
* @aspType Syncfusion.EJ2.Grids.ClipMode
*/
clipMode?: ClipMode;
/**
* The CSS styles and attributes of the content cells of a particular column can be customized.
*
* @default null
*/
customAttributes?: { [x: string]: Object };
/**
* If `disableHtmlEncode` is set to true, it encodes the HTML of the header and content cells.
*
* @default false
*/
disableHtmlEncode?: boolean;
/**
* If `displayAsCheckBox` is set to true, it displays the column value as a check box instead of Boolean value.
*
* @default false
*/
displayAsCheckBox?: boolean;
/**
* Defines the field name of column which is mapped with mapping name of DataSource.
* The `field` name must be a valid JavaScript identifier,
* the first character must be an alphabet and should not contain spaces and special characters.
*
* @default null
*/
field?: string;
/**
* Defines the type of component for editing.
*
* @default 'stringedit'
*/
editType?: string;
/**
* It is used to change display value with the given format and does not affect the original data.
* Gets the format from the user which can be standard or custom
* [`number`](../../../common/internationalization/#number-formatting)
* and [`date`](../../../common/internationalization/#formatting) formats.
*
* @default null
* @aspType string
*/
format?: string | NumberFormatOptions | DateFormatOptions;
/**
* Defines the method which is used to achieve custom formatting from an external function.
* This function triggers before rendering of each cell.
*
* @default null
*/
formatter?: { new(): IGanttCellFormatter } | Function | IGanttCellFormatter;
/**
* Defines the header template as string or HTML element ID which is used to add customized element in the column header.
*
* @default null
*/
headerTemplate?: string;
/**
* Defines the header text of column which is used to display in column header.
* If `headerText` is not defined, then field name value will be assigned to header text.
*
* @default null
*/
headerText?: string;
/**
* Define the alignment of column header which is used to align the text of column header.
*
* @default Syncfusion.EJ2.Grids.TextAlign.Left
* @isEnumeration true
* @aspType Syncfusion.EJ2.Grids.TextAlign
*/
headerTextAlign?: TextAlign;
/**
* Column visibility can change based on [`Media Queries`](http://cssmediaqueries.com/what-are-css-media-queries.html).
* `hideAtMedia` accepts only valid Media Queries.
*
* @default null
*/
hideAtMedia?: string;
/**
* Defines the maximum width of the column in pixel or percentage, which will restrict resizing beyond this pixel or percentage.
*
* @default null
*/
maxWidth?: string | number;
/**
* Defines the minimum width of the column in pixels or percentage.
*
* @default null
*/
minWidth?: string | number;
/**
* Defines the column template that renders customized element in each cell of the column.
* It accepts either template string or HTML element ID.
*
* @default null
*/
template?: string;
/**
* Defines the alignment of the column in both header and content cells.
*
* @default Syncfusion.EJ2.Grids.TextAlign.Left
* @isEnumeration true
* @aspType Syncfusion.EJ2.Grids.TextAlign
*/
textAlign?: TextAlign;
/**
* Defines the method used to apply custom cell values from external function and display this on each cell rendered.
*
* @default null
*/
valueAccessor?: ValueAccessor | string;
/**
* If `visible` is set to false, hides the particular column. By default, columns are displayed.
*
* @default true
*/
visible?: boolean;
/**
* Defines the width of the column in pixels or percentage.
*
* @default null
*/
width?: string | number;
/**
* If `isPrimaryKey` is set to true, considers this column as the primary key constraint.
*
* @default false
*/
isPrimaryKey?: boolean;
/**
* Defines the `IEditCell` object to customize default edit cell.
*
* @default {}
*/
edit?: IEditCell;
/**
* To define column type.
*
* @private
*/
type?: string;
/**
* Defines the sort comparer property.
*
* @default null
*/
sortComparer?: SortComparer | string;
} | 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/backupsMappers";
import * as Parameters from "../models/parameters";
import { StorSimple8000SeriesManagementClientContext } from "../storSimple8000SeriesManagementClientContext";
/** Class representing a Backups. */
export class Backups {
private readonly client: StorSimple8000SeriesManagementClientContext;
/**
* Create a Backups.
* @param {StorSimple8000SeriesManagementClientContext} client Reference to the service client.
*/
constructor(client: StorSimple8000SeriesManagementClientContext) {
this.client = client;
}
/**
* Retrieves all the backups in a device.
* @param deviceName The device name
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.BackupsListByDeviceResponse>
*/
listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: Models.BackupsListByDeviceOptionalParams): Promise<Models.BackupsListByDeviceResponse>;
/**
* @param deviceName The device name
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
listByDevice(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.BackupList>): void;
/**
* @param deviceName The device name
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options: Models.BackupsListByDeviceOptionalParams, callback: msRest.ServiceCallback<Models.BackupList>): void;
listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: Models.BackupsListByDeviceOptionalParams | msRest.ServiceCallback<Models.BackupList>, callback?: msRest.ServiceCallback<Models.BackupList>): Promise<Models.BackupsListByDeviceResponse> {
return this.client.sendOperationRequest(
{
deviceName,
resourceGroupName,
managerName,
options
},
listByDeviceOperationSpec,
callback) as Promise<Models.BackupsListByDeviceResponse>;
}
/**
* Deletes the backup.
* @param deviceName The device name
* @param backupName The backup name.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(deviceName,backupName,resourceGroupName,managerName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Clones the backup element as a new volume.
* @param deviceName The device name
* @param backupName The backup name.
* @param backupElementName The backup element name.
* @param parameters The clone request object.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
clone(deviceName: string, backupName: string, backupElementName: string, parameters: Models.CloneRequest, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginClone(deviceName,backupName,backupElementName,parameters,resourceGroupName,managerName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Restores the backup on the device.
* @param deviceName The device name
* @param backupName The backupSet name
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
restore(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginRestore(deviceName,backupName,resourceGroupName,managerName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Deletes the backup.
* @param deviceName The device name
* @param backupName The backup name.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
deviceName,
backupName,
resourceGroupName,
managerName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Clones the backup element as a new volume.
* @param deviceName The device name
* @param backupName The backup name.
* @param backupElementName The backup element name.
* @param parameters The clone request object.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginClone(deviceName: string, backupName: string, backupElementName: string, parameters: Models.CloneRequest, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
deviceName,
backupName,
backupElementName,
parameters,
resourceGroupName,
managerName,
options
},
beginCloneOperationSpec,
options);
}
/**
* Restores the backup on the device.
* @param deviceName The device name
* @param backupName The backupSet name
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginRestore(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
deviceName,
backupName,
resourceGroupName,
managerName,
options
},
beginRestoreOperationSpec,
options);
}
/**
* Retrieves all the backups in a device.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.BackupsListByDeviceNextResponse>
*/
listByDeviceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupsListByDeviceNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByDeviceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BackupList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByDeviceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BackupList>): void;
listByDeviceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BackupList>, callback?: msRest.ServiceCallback<Models.BackupList>): Promise<Models.BackupsListByDeviceNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByDeviceNextOperationSpec,
callback) as Promise<Models.BackupsListByDeviceNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByDeviceOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backups",
urlParameters: [
Parameters.deviceName,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion,
Parameters.filter0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BackupList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backups/{backupName}",
urlParameters: [
Parameters.deviceName,
Parameters.backupName,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCloneOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backups/{backupName}/elements/{backupElementName}/clone",
urlParameters: [
Parameters.deviceName,
Parameters.backupName,
Parameters.backupElementName,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.CloneRequest,
required: true
}
},
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginRestoreOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backups/{backupName}/restore",
urlParameters: [
Parameters.deviceName,
Parameters.backupName,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByDeviceNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BackupList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import {
createElement,
Child,
Children,
Context,
Element,
Fragment,
} from "../index";
import {renderer} from "../dom";
describe("sync generator component", () => {
afterEach(() => {
renderer.render(null, document.body);
document.body.innerHTML = "";
});
test("basic", () => {
const Component = jest.fn(function* Component(
this: Context,
{message}: {message: string},
): Generator<Element> {
let i = 0;
for ({message} of this) {
if (++i > 2) {
return <span>Final</span>;
}
yield <span>{message}</span>;
}
});
renderer.render(
<div>
<Component message="Hello 1" />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div><span>Hello 1</span></div>");
renderer.render(
<div>
<Component message="Hello 2" />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div><span>Hello 2</span></div>");
renderer.render(
<div>
<Component message="Hello 3" />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div><span>Final</span></div>");
expect(Component).toHaveBeenCalledTimes(1);
});
test("refresh", () => {
let ctx!: Context;
function* Component(this: Context): Generator<Element> {
ctx = this;
let i = 1;
while (true) {
yield <span>Hello {i++}</span>;
}
}
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div><span>Hello 1</span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div><span>Hello 2</span></div>");
ctx.refresh();
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div><span>Hello 4</span></div>");
});
test("updating undefined to component", () => {
function NestedComponent() {
return <span>Hello</span>;
}
let ctx!: Context;
function* Component(this: Context): Generator<Element> {
ctx = this;
let mounted = false;
while (true) {
let component: Element | undefined;
if (mounted) {
component = <NestedComponent />;
}
yield <span>{component}</span>;
mounted = true;
}
}
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div><span></span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div><span><span>Hello</span></span></div>",
);
});
test("refresh undefined to nested component", () => {
function NestedComponent() {
return <span>Hello</span>;
}
let ctx!: Context;
function* Component(this: Context): Generator<Element> {
ctx = this;
let mounted = false;
while (true) {
let component: Element | undefined;
if (mounted) {
component = <NestedComponent />;
}
yield <span>{component}</span>;
mounted = true;
}
}
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div><span></span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div><span><span>Hello</span></span></div>",
);
});
test("refresh null to element", () => {
let ctx!: Context;
function* Component(this: Context): Generator<Child> {
ctx = this;
yield null;
yield <span>Hello</span>;
yield null;
yield <span>Hello again</span>;
}
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div><span>Hello</span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div><span>Hello again</span></div>",
);
});
test("refresh with different child", () => {
let ctx!: Context;
function* Component(this: Context): Generator<Child> {
ctx = this;
yield <span>1</span>;
yield <div>2</div>;
yield <span>3</span>;
yield null;
}
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div><span>1</span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div><div>2</div></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div><span>3</span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div></div>");
});
test("refresh with different child and siblings", () => {
let ctx!: Context;
function* Component(this: Context): Generator<Child> {
if (ctx === undefined) {
ctx = this;
}
yield <span>Hello</span>;
yield <div>Hello</div>;
yield <span>Hello</span>;
yield null;
}
renderer.render(
<div>
<Component />
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual(
"<div><span>Hello</span><span>Hello</span></div>",
);
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div><div>Hello</div><span>Hello</span></div>",
);
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div><span>Hello</span><span>Hello</span></div>",
);
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div><span>Hello</span></div>");
});
test("refresh fragment", () => {
let ctx!: Context;
function* Component(this: Context): Generator<Child> {
ctx = this;
yield (
<Fragment>
{null}
<span>2</span>
{null}
</Fragment>
);
yield (
<Fragment>
<span>1</span>
<span>2</span>
<span>3</span>
</Fragment>
);
yield (
<Fragment>
<span>1</span>
{null}
{null}
</Fragment>
);
yield (
<Fragment>
{null}
{null}
<span>3</span>
</Fragment>
);
yield (
<Fragment>
{true}
{false}
{undefined}
</Fragment>
);
}
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div><span>2</span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div><span>1</span><span>2</span><span>3</span></div>",
);
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div><span>1</span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div><span>3</span></div>");
ctx.refresh();
expect(document.body.innerHTML).toEqual("<div></div>");
});
test("async children", async () => {
const mock = jest.fn();
async function Component({
children,
}: {
children: Children;
}): Promise<Element> {
await new Promise((resolve) => setTimeout(resolve, 100));
return <span>{children}</span>;
}
let ctx!: Context;
function* Gen(this: Context): Generator<Element> {
ctx = this;
let i = 0;
for (const _ of this) {
const yielded = yield <Component>Hello {i++}</Component>;
mock((yielded as any).outerHTML);
}
}
const renderP = renderer.render(
<div>
<Gen />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("");
await renderP;
expect(document.body.innerHTML).toEqual("<div><span>Hello 0</span></div>");
const refreshP = ctx.refresh();
await new Promise((resolve) => setTimeout(resolve));
expect(mock).toHaveBeenCalledWith("<span>Hello 0</span>");
expect(mock).toHaveBeenCalledTimes(1);
expect(document.body.innerHTML).toEqual("<div><span>Hello 0</span></div>");
await refreshP;
expect(document.body.innerHTML).toEqual("<div><span>Hello 1</span></div>");
ctx.refresh();
await new Promise((resolve) => setTimeout(resolve));
expect(mock).toHaveBeenCalledWith("<span>Hello 1</span>");
expect(mock).toHaveBeenCalledTimes(2);
});
test("refreshing doesn’t cause siblings to update", () => {
const mock = jest.fn();
function Sibling(): Element {
mock();
return <div>Sibling</div>;
}
let ctx!: Context;
function* Component(this: Context): Generator<Element> {
ctx = this;
let i = 0;
while (true) {
i++;
yield <div>Hello {i}</div>;
}
}
renderer.render(
<Fragment>
<Component />
<Sibling />
</Fragment>,
document.body,
);
expect(document.body.innerHTML).toEqual(
"<div>Hello 1</div><div>Sibling</div>",
);
expect(mock).toHaveBeenCalledTimes(1);
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div>Hello 2</div><div>Sibling</div>",
);
expect(mock).toHaveBeenCalledTimes(1);
ctx.refresh();
ctx.refresh();
ctx.refresh();
ctx.refresh();
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div>Hello 7</div><div>Sibling</div>",
);
expect(mock).toHaveBeenCalledTimes(1);
renderer.render(
<Fragment>
<Component />
<Sibling />
</Fragment>,
document.body,
);
expect(document.body.innerHTML).toEqual(
"<div>Hello 8</div><div>Sibling</div>",
);
expect(mock).toHaveBeenCalledTimes(2);
});
test("refreshing child doesn’t cause siblings to update", () => {
const mock = jest.fn();
function Sibling(): Element {
mock();
return <div>Sibling</div>;
}
let ctx!: Context;
function* Child(this: Context): Generator<Element> {
ctx = this;
let i = 0;
while (true) {
i++;
yield <div>Hello {i}</div>;
}
}
function* Parent(): Generator<Element> {
while (true) {
yield (
<Fragment>
<Child />
<Sibling />
</Fragment>
);
}
}
renderer.render(<Parent />, document.body);
expect(document.body.innerHTML).toEqual(
"<div>Hello 1</div><div>Sibling</div>",
);
expect(mock).toHaveBeenCalledTimes(1);
ctx.refresh();
expect(document.body.innerHTML).toEqual(
"<div>Hello 2</div><div>Sibling</div>",
);
expect(mock).toHaveBeenCalledTimes(1);
});
test("yield resumes with a node", () => {
let html: string | undefined;
function* Component(): Generator<Element> {
let i = 0;
while (true) {
const node: any = yield <div id={i}>{i}</div>;
html = node.outerHTML;
i++;
}
}
renderer.render(<Component />, document.body);
expect(html).toBeUndefined();
renderer.render(<Component />, document.body);
expect(html).toEqual('<div id="0">0</div>');
expect(document.body.innerHTML).toEqual('<div id="1">1</div>');
renderer.render(<Component />, document.body);
expect(html).toEqual('<div id="1">1</div>');
expect(document.body.innerHTML).toEqual('<div id="2">2</div>');
});
test("generator returns", () => {
const Component = jest.fn(function* Component(): Generator<Child> {
yield "Hello";
return "Goodbye";
});
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div>Hello</div>");
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div>Goodbye</div>");
renderer.render(
<div>
<Component />
</div>,
document.body,
);
renderer.render(
<div>
<Component />
</div>,
document.body,
);
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div>Goodbye</div>");
expect(Component).toHaveBeenCalledTimes(1);
renderer.render(<div>{null}</div>, document.body);
renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div>Hello</div>");
});
test("generator returns with async children and concurrent updates", async () => {
async function Child(): Promise<string> {
return "child";
}
// eslint-disable-next-line require-yield
const Component = jest.fn(function* Component(): Generator<Child> {
return <Child />;
});
renderer.render(
<div>
<Component />
</div>,
document.body,
);
await renderer.render(
<div>
<Component />
</div>,
document.body,
);
expect(document.body.innerHTML).toEqual("<div>child</div>");
await new Promise((resolve) => setTimeout(resolve, 100));
expect(Component).toHaveBeenCalledTimes(1);
});
test("unmount", () => {
const mock = jest.fn();
function* Component(): Generator<Element> {
try {
let i = 0;
while (true) {
yield <div>Hello {i++}</div>;
}
} finally {
mock();
}
}
renderer.render(<Component />, document.body);
renderer.render(<Component />, document.body);
renderer.render(<Component />, document.body);
expect(document.body.innerHTML).toEqual("<div>Hello 2</div>");
expect(mock).toHaveBeenCalledTimes(0);
renderer.render(<div>Goodbye</div>, document.body);
expect(document.body.innerHTML).toEqual("<div>Goodbye</div>");
expect(mock).toHaveBeenCalledTimes(1);
});
test("unmount against string", () => {
const mock = jest.fn();
function* Component(): Generator<Element> {
try {
let i = 0;
while (true) {
yield <div>Hello {i++}</div>;
}
} finally {
mock();
}
}
renderer.render(<Component />, document.body);
renderer.render(<Component />, document.body);
renderer.render(<Component />, document.body);
expect(document.body.innerHTML).toEqual("<div>Hello 2</div>");
expect(mock).toHaveBeenCalledTimes(0);
renderer.render(["Goodbye", null], document.body);
expect(document.body.innerHTML).toEqual("Goodbye");
expect(mock).toHaveBeenCalledTimes(1);
});
test("unmount against null", () => {
const mock = jest.fn();
function* Component(): Generator<Element> {
try {
let i = 0;
while (true) {
yield <div>Hello {i++}</div>;
}
} finally {
mock();
}
}
renderer.render(<Component />, document.body);
renderer.render(<Component />, document.body);
renderer.render(<Component />, document.body);
expect(document.body.innerHTML).toEqual("<div>Hello 2</div>");
expect(mock).toHaveBeenCalledTimes(0);
renderer.render([null, "Goodbye"], document.body);
expect(document.body.innerHTML).toEqual("Goodbye");
expect(mock).toHaveBeenCalledTimes(1);
});
test("unmount against async", async () => {
const mock = jest.fn();
function* Component(): Generator<Element> {
try {
let i = 0;
while (true) {
yield <div>Hello {i++}</div>;
}
} finally {
mock();
}
}
async function Async(): Promise<Element> {
return <div>Goodbye</div>;
}
renderer.render(<Component />, document.body);
renderer.render(<Component />, document.body);
renderer.render(<Component />, document.body);
expect(document.body.innerHTML).toEqual("<div>Hello 2</div>");
expect(mock).toHaveBeenCalledTimes(0);
await renderer.render(<Async />, document.body);
expect(document.body.innerHTML).toEqual("<div>Goodbye</div>");
expect(mock).toHaveBeenCalledTimes(1);
});
test("multiple iterations without a yield throw", () => {
let i = 0;
function* Component(this: Context) {
for (const _ of this) {
// just so the test suite doesn’t enter an infinite loop
if (i > 100) {
yield;
return;
}
i++;
}
}
expect(() => renderer.render(<Component />, document.body)).toThrow(
"Context iterated twice",
);
expect(i).toBe(1);
});
// TODO: it would be nice to test this like other components
test("for await...of throws", async () => {
let ctx: Context;
function* Component(this: Context): Generator<null> {
ctx = this;
yield null;
}
renderer.render(<Component />, document.body);
await expect((() => ctx![Symbol.asyncIterator]().next())()).rejects.toThrow(
"Use for…of",
);
});
}); | the_stack |
import { Dataset } from "plywood";
interface StatusRow {
VARIABLE_NAME: string;
VARIABLE_VALUE: string;
}
let statusData: StatusRow[] = [
{ "VARIABLE_NAME": "Aborted_clients", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Aborted_connects", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Binlog_cache_disk_use", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Binlog_cache_use", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Binlog_stmt_cache_disk_use", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Binlog_stmt_cache_use", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Bytes_received", "VARIABLE_VALUE": "2091" },
{ "VARIABLE_NAME": "Bytes_sent", "VARIABLE_VALUE": "29905" },
{ "VARIABLE_NAME": "Com_admin_commands", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_assign_to_keycache", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_db", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_db_upgrade", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_event", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_function", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_instance", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_procedure", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_server", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_table", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_tablespace", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_alter_user", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_analyze", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_begin", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_binlog", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_call_procedure", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_change_db", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_change_master", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_change_repl_filter", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_check", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_checksum", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_commit", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_db", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_event", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_function", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_index", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_procedure", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_server", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_table", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_trigger", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_udf", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_user", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_create_view", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_dealloc_sql", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_delete", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_delete_multi", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_do", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_db", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_event", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_function", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_index", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_procedure", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_server", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_table", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_trigger", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_user", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_drop_view", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_empty_query", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_execute_sql", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_explain_other", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_flush", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_get_diagnostics", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_grant", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_ha_close", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_ha_open", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_ha_read", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_help", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_insert", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_insert_select", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_install_plugin", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_kill", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_load", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_lock_tables", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_optimize", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_preload_keys", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_prepare_sql", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_purge", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_purge_before_date", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_release_savepoint", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_rename_table", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_rename_user", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_repair", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_replace", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_replace_select", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_reset", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_resignal", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_revoke", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_revoke_all", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_rollback", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_rollback_to_savepoint", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_savepoint", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_select", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Com_set_option", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_signal", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_binlog_events", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_binlogs", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_charsets", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_collations", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_create_db", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_create_event", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_create_func", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_create_proc", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_create_table", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_create_trigger", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_databases", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_engine_logs", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_engine_mutex", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_engine_status", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_events", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_errors", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_fields", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_function_code", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_function_status", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_grants", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_keys", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_master_status", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_open_tables", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_plugins", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_privileges", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_procedure_code", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_procedure_status", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_processlist", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_profile", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_profiles", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_relaylog_events", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_slave_hosts", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_slave_status", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_status", "VARIABLE_VALUE": "23" },
{ "VARIABLE_NAME": "Com_show_storage_engines", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_table_status", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_tables", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_triggers", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_variables", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Com_show_warnings", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_show_create_user", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_shutdown", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_slave_start", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_slave_stop", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_group_replication_start", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_group_replication_stop", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_stmt_execute", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_stmt_close", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_stmt_fetch", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_stmt_prepare", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_stmt_reset", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_stmt_send_long_data", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_truncate", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_uninstall_plugin", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_unlock_tables", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_update", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_update_multi", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_xa_commit", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_xa_end", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_xa_prepare", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_xa_recover", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_xa_rollback", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_xa_start", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Com_stmt_reprepare", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Compression", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "Connection_errors_accept", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Connection_errors_internal", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Connection_errors_max_connections", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Connection_errors_peer_address", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Connection_errors_select", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Connection_errors_tcpwrap", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Connections", "VARIABLE_VALUE": "1079" },
{ "VARIABLE_NAME": "Created_tmp_disk_tables", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Created_tmp_files", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Created_tmp_tables", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Delayed_errors", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Delayed_insert_threads", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Delayed_writes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Flush_commands", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Handler_commit", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_delete", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_discover", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_external_lock", "VARIABLE_VALUE": "2" },
{ "VARIABLE_NAME": "Handler_mrr_init", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_prepare", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_read_first", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_read_key", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_read_last", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_read_next", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_read_prev", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_read_rnd", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_read_rnd_next", "VARIABLE_VALUE": "1018" },
{ "VARIABLE_NAME": "Handler_rollback", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_savepoint", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_savepoint_rollback", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_update", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Handler_write", "VARIABLE_VALUE": "508" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_dump_status", "VARIABLE_VALUE": "Dumping of buffer pool not started" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_load_status", "VARIABLE_VALUE": "Buffer pool(s) load completed at 160929 1:13:58" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_resize_status", "VARIABLE_VALUE": "" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_pages_data", "VARIABLE_VALUE": "7162" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_bytes_data", "VARIABLE_VALUE": "117342208" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_pages_dirty", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_bytes_dirty", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_pages_flushed", "VARIABLE_VALUE": "5521" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_pages_free", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_pages_misc", "VARIABLE_VALUE": "5" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_pages_total", "VARIABLE_VALUE": "8191" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_read_ahead_rnd", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_read_ahead", "VARIABLE_VALUE": "12142" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_read_ahead_evicted", "VARIABLE_VALUE": "70" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_read_requests", "VARIABLE_VALUE": "435489940" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_reads", "VARIABLE_VALUE": "4081" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_wait_free", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_buffer_pool_write_requests", "VARIABLE_VALUE": "8674489" },
{ "VARIABLE_NAME": "Innodb_data_fsyncs", "VARIABLE_VALUE": "45" },
{ "VARIABLE_NAME": "Innodb_data_pending_fsyncs", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_data_pending_reads", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_data_pending_writes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_data_read", "VARIABLE_VALUE": "265867776" },
{ "VARIABLE_NAME": "Innodb_data_reads", "VARIABLE_VALUE": "16249" },
{ "VARIABLE_NAME": "Innodb_data_writes", "VARIABLE_VALUE": "5638" },
{ "VARIABLE_NAME": "Innodb_data_written", "VARIABLE_VALUE": "91144192" },
{ "VARIABLE_NAME": "Innodb_dblwr_pages_written", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_dblwr_writes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_log_waits", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_log_write_requests", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_log_writes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_os_log_fsyncs", "VARIABLE_VALUE": "30" },
{ "VARIABLE_NAME": "Innodb_os_log_pending_fsyncs", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_os_log_pending_writes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_os_log_written", "VARIABLE_VALUE": "47104" },
{ "VARIABLE_NAME": "Innodb_page_size", "VARIABLE_VALUE": "16384" },
{ "VARIABLE_NAME": "Innodb_pages_created", "VARIABLE_VALUE": "1125" },
{ "VARIABLE_NAME": "Innodb_pages_read", "VARIABLE_VALUE": "16222" },
{ "VARIABLE_NAME": "Innodb_pages_written", "VARIABLE_VALUE": "5522" },
{ "VARIABLE_NAME": "Innodb_row_lock_current_waits", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_row_lock_time", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_row_lock_time_avg", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_row_lock_time_max", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_row_lock_waits", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_rows_deleted", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_rows_inserted", "VARIABLE_VALUE": "641715" },
{ "VARIABLE_NAME": "Innodb_rows_read", "VARIABLE_VALUE": "414887194" },
{ "VARIABLE_NAME": "Innodb_rows_updated", "VARIABLE_VALUE": "1755882" },
{ "VARIABLE_NAME": "Innodb_num_open_files", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_truncated_status_writes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Innodb_available_undo_logs", "VARIABLE_VALUE": "128" },
{ "VARIABLE_NAME": "Key_blocks_not_flushed", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Key_blocks_unused", "VARIABLE_VALUE": "6695" },
{ "VARIABLE_NAME": "Key_blocks_used", "VARIABLE_VALUE": "3" },
{ "VARIABLE_NAME": "Key_read_requests", "VARIABLE_VALUE": "6" },
{ "VARIABLE_NAME": "Key_reads", "VARIABLE_VALUE": "3" },
{ "VARIABLE_NAME": "Key_write_requests", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Key_writes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Last_query_cost", "VARIABLE_VALUE": "0.000" },
{ "VARIABLE_NAME": "Last_query_partial_plans", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Locked_connects", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Max_execution_time_exceeded", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Max_execution_time_set", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Max_execution_time_set_failed", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Max_used_connections", "VARIABLE_VALUE": "6" },
{ "VARIABLE_NAME": "Max_used_connections_time", "VARIABLE_VALUE": "2016-09-29 01:59:09" },
{ "VARIABLE_NAME": "Not_flushed_delayed_rows", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ongoing_anonymous_transaction_count", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Open_files", "VARIABLE_VALUE": "14" },
{ "VARIABLE_NAME": "Open_streams", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Open_table_definitions", "VARIABLE_VALUE": "109" },
{ "VARIABLE_NAME": "Open_tables", "VARIABLE_VALUE": "131" },
{ "VARIABLE_NAME": "Opened_files", "VARIABLE_VALUE": "181" },
{ "VARIABLE_NAME": "Opened_table_definitions", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Opened_tables", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Performance_schema_accounts_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_cond_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_cond_instances_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_digest_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_file_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_file_handles_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_file_instances_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_hosts_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_index_stat_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_locker_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_memory_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_metadata_lock_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_mutex_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_mutex_instances_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_nested_statement_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_prepared_statements_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_program_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_rwlock_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_rwlock_instances_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_session_connect_attrs_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_socket_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_socket_instances_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_stage_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_statement_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_table_handles_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_table_instances_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_table_lock_stat_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_thread_classes_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_thread_instances_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Performance_schema_users_lost", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Prepared_stmt_count", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Qcache_free_blocks", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Qcache_free_memory", "VARIABLE_VALUE": "1031832" },
{ "VARIABLE_NAME": "Qcache_hits", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Qcache_inserts", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Qcache_lowmem_prunes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Qcache_not_cached", "VARIABLE_VALUE": "1095" },
{ "VARIABLE_NAME": "Qcache_queries_in_cache", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Qcache_total_blocks", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Queries", "VARIABLE_VALUE": "2648" },
{ "VARIABLE_NAME": "Questions", "VARIABLE_VALUE": "29" },
{ "VARIABLE_NAME": "Rsa_public_key", "VARIABLE_VALUE": "" },
{ "VARIABLE_NAME": "Select_full_join", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Select_full_range_join", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Select_range", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Select_range_check", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Select_scan", "VARIABLE_VALUE": "2" },
{ "VARIABLE_NAME": "Slave_open_temp_tables", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Slow_launch_threads", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Slow_queries", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Sort_merge_passes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Sort_range", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Sort_rows", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Sort_scan", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_accept_renegotiates", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_accepts", "VARIABLE_VALUE": "4" },
{ "VARIABLE_NAME": "Ssl_callback_cache_hits", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_cipher", "VARIABLE_VALUE": "" },
{ "VARIABLE_NAME": "Ssl_cipher_list", "VARIABLE_VALUE": "" },
{ "VARIABLE_NAME": "Ssl_client_connects", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_connect_renegotiates", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_ctx_verify_depth", "VARIABLE_VALUE": "18446744073709551615" },
{ "VARIABLE_NAME": "Ssl_ctx_verify_mode", "VARIABLE_VALUE": "5" },
{ "VARIABLE_NAME": "Ssl_default_timeout", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_finished_accepts", "VARIABLE_VALUE": "4" },
{ "VARIABLE_NAME": "Ssl_finished_connects", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_server_not_after", "VARIABLE_VALUE": "Aug 9 22:11:30 2026 GMT" },
{ "VARIABLE_NAME": "Ssl_server_not_before", "VARIABLE_VALUE": "Aug 11 22:11:30 2016 GMT" },
{ "VARIABLE_NAME": "Ssl_session_cache_hits", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_session_cache_misses", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_session_cache_mode", "VARIABLE_VALUE": "SERVER" },
{ "VARIABLE_NAME": "Ssl_session_cache_overflows", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_session_cache_size", "VARIABLE_VALUE": "128" },
{ "VARIABLE_NAME": "Ssl_session_cache_timeouts", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_sessions_reused", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_used_session_cache_entries", "VARIABLE_VALUE": "4" },
{ "VARIABLE_NAME": "Ssl_verify_depth", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_verify_mode", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Ssl_version", "VARIABLE_VALUE": "" },
{ "VARIABLE_NAME": "Table_locks_immediate", "VARIABLE_VALUE": "127" },
{ "VARIABLE_NAME": "Table_locks_waited", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Table_open_cache_hits", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Table_open_cache_misses", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Table_open_cache_overflows", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Tc_log_max_pages_used", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Tc_log_page_size", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Tc_log_page_waits", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "Threads_cached", "VARIABLE_VALUE": "5" },
{ "VARIABLE_NAME": "Threads_connected", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Threads_created", "VARIABLE_VALUE": "6" },
{ "VARIABLE_NAME": "Threads_running", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "Uptime", "VARIABLE_VALUE": "1639155" },
{ "VARIABLE_NAME": "Uptime_since_flush_status", "VARIABLE_VALUE": "1639155" }
];
export function getStatusDataset() {
return Dataset.fromJS(statusData);
} | the_stack |
import {
Composer as APIComposer,
ComposerProps as APIComposerProps,
hooks,
WebSpeechPonyfillFactory
} from 'botframework-webchat-api';
import { Composer as SayComposer } from 'react-say';
import { singleToArray } from 'botframework-webchat-core';
import createEmotion from '@emotion/css/create-instance';
import createStyleSet from './Styles/createStyleSet';
import MarkdownIt from 'markdown-it';
import PropTypes from 'prop-types';
import React, { FC, ReactNode, useCallback, useMemo, useRef, useState } from 'react';
import {
speechSynthesis as bypassSpeechSynthesis,
SpeechSynthesisUtterance as BypassSpeechSynthesisUtterance
} from './hooks/internal/BypassSpeechSynthesisPonyfill';
import addTargetBlankToHyperlinksMarkdown from './Utils/addTargetBlankToHyperlinksMarkdown';
import createCSSKey from './Utils/createCSSKey';
import createDefaultActivityMiddleware from './Middleware/Activity/createCoreMiddleware';
import createDefaultActivityStatusMiddleware from './Middleware/ActivityStatus/createCoreMiddleware';
import createDefaultAttachmentForScreenReaderMiddleware from './Middleware/AttachmentForScreenReader/createCoreMiddleware';
import createDefaultAttachmentMiddleware from './Middleware/Attachment/createCoreMiddleware';
import createDefaultAvatarMiddleware from './Middleware/Avatar/createCoreMiddleware';
import createDefaultCardActionMiddleware from './Middleware/CardAction/createCoreMiddleware';
import createDefaultScrollToEndButtonMiddleware from './Middleware/ScrollToEndButton/createScrollToEndButtonMiddleware';
import createDefaultToastMiddleware from './Middleware/Toast/createCoreMiddleware';
import createDefaultTypingIndicatorMiddleware from './Middleware/TypingIndicator/createCoreMiddleware';
import Dictation from './Dictation';
import downscaleImageToDataURL from './Utils/downscaleImageToDataURL';
import ErrorBox from './ErrorBox';
import mapMap from './Utils/mapMap';
import UITracker from './hooks/internal/UITracker';
import WebChatUIContext from './hooks/internal/WebChatUIContext';
const { useReferenceGrammarID, useStyleOptions } = hooks;
const node_env = process.env.node_env || process.env.NODE_ENV;
const emotionPool = {};
function styleSetToEmotionObjects(styleToEmotionObject, styleSet) {
return mapMap(styleSet, (style, key) => (key === 'options' ? style : styleToEmotionObject(style)));
}
type ComposerCoreProps = {
children?: ReactNode;
extraStyleSet?: any;
nonce?: string;
renderMarkdown?: (markdown: string, { markdownRespectCRLF: boolean }, { externalLinkAlt: string }) => string;
styleSet?: any;
suggestedActionsAccessKey?: boolean | string;
webSpeechPonyfillFactory?: WebSpeechPonyfillFactory;
};
const ComposerCore: FC<ComposerCoreProps> = ({
children,
extraStyleSet,
nonce,
renderMarkdown,
styleSet,
suggestedActionsAccessKey,
webSpeechPonyfillFactory
}) => {
const [dictateAbortable, setDictateAbortable] = useState();
const [referenceGrammarID] = useReferenceGrammarID();
const [styleOptions] = useStyleOptions();
const focusSendBoxCallbacksRef = useRef([]);
const focusTranscriptCallbacksRef = useRef([]);
const internalMarkdownIt = useMemo(() => new MarkdownIt(), []);
const scrollToCallbacksRef = useRef([]);
const scrollToEndCallbacksRef = useRef([]);
// Instead of having a `scrollUpCallbacksRef` and `scrollDownCallbacksRef`, they are combined into a single `scrollRelativeCallbacksRef`.
// The first argument tells whether it should go "up" or "down".
const scrollRelativeCallbacksRef = useRef([]);
const dictationOnError = useCallback(err => {
console.error(err);
}, []);
const internalRenderMarkdownInline = useMemo(
() => markdown => {
const tree = internalMarkdownIt.parseInline(markdown);
// We should add rel="noopener noreferrer" and target="_blank"
const patchedTree = addTargetBlankToHyperlinksMarkdown(tree);
return internalMarkdownIt.renderer.render(patchedTree);
},
[internalMarkdownIt]
);
const styleToEmotionObject = useMemo(() => {
// Emotion doesn't hash with nonce. We need to provide the pooling mechanism.
// 1. If 2 instances use different nonce, they should result in different hash;
// 2. If 2 instances are being mounted, pooling will make sure we render only 1 set of <style> tags, instead of 2.
const emotion =
// Prefix "id-" to prevent object injection attack.
emotionPool[`id-${nonce}`] ||
(emotionPool[`id-${nonce}`] = createEmotion({ key: `webchat--css-${createCSSKey()}`, nonce }));
return style => emotion.css(style);
}, [nonce]);
const patchedStyleSet = useMemo(
() =>
styleSetToEmotionObjects(styleToEmotionObject, {
...(styleSet || createStyleSet(styleOptions)),
...extraStyleSet
}),
[extraStyleSet, styleOptions, styleSet, styleToEmotionObject]
);
const webSpeechPonyfill = useMemo(() => {
const ponyfill = webSpeechPonyfillFactory && webSpeechPonyfillFactory({ referenceGrammarID });
const { speechSynthesis, SpeechSynthesisUtterance } = ponyfill || {};
return {
...ponyfill,
speechSynthesis: speechSynthesis || bypassSpeechSynthesis,
SpeechSynthesisUtterance: SpeechSynthesisUtterance || BypassSpeechSynthesisUtterance
};
}, [referenceGrammarID, webSpeechPonyfillFactory]);
const scrollPositionObserversRef = useRef([]);
const [numScrollPositionObservers, setNumScrollPositionObservers] = useState(0);
const dispatchScrollPosition = useCallback(
event => scrollPositionObserversRef.current.forEach(observer => observer(event)),
[scrollPositionObserversRef]
);
const observeScrollPosition = useCallback(
observer => {
scrollPositionObserversRef.current = [...scrollPositionObserversRef.current, observer];
setNumScrollPositionObservers(scrollPositionObserversRef.current.length);
return () => {
scrollPositionObserversRef.current = scrollPositionObserversRef.current.filter(target => target !== observer);
setNumScrollPositionObservers(scrollPositionObserversRef.current.length);
};
},
[scrollPositionObserversRef, setNumScrollPositionObservers]
);
const transcriptFocusObserversRef = useRef([]);
const [numTranscriptFocusObservers, setNumTranscriptFocusObservers] = useState(0);
const dispatchTranscriptFocus = useCallback(
event => transcriptFocusObserversRef.current.forEach(observer => observer(event)),
[transcriptFocusObserversRef]
);
const observeTranscriptFocus = useCallback(
observer => {
transcriptFocusObserversRef.current = [...transcriptFocusObserversRef.current, observer];
setNumTranscriptFocusObservers(transcriptFocusObserversRef.current.length);
return () => {
transcriptFocusObserversRef.current = transcriptFocusObserversRef.current.filter(target => target !== observer);
setNumTranscriptFocusObservers(transcriptFocusObserversRef.current.length);
};
},
[transcriptFocusObserversRef, setNumTranscriptFocusObservers]
);
const context = useMemo(
() => ({
dictateAbortable,
dispatchScrollPosition,
dispatchTranscriptFocus,
focusSendBoxCallbacksRef,
focusTranscriptCallbacksRef,
internalMarkdownItState: [internalMarkdownIt],
internalRenderMarkdownInline,
nonce,
numScrollPositionObservers,
numTranscriptFocusObservers,
observeScrollPosition,
observeTranscriptFocus,
renderMarkdown,
scrollRelativeCallbacksRef,
scrollToCallbacksRef,
scrollToEndCallbacksRef,
setDictateAbortable,
styleSet: patchedStyleSet,
styleToEmotionObject,
suggestedActionsAccessKey,
webSpeechPonyfill
}),
[
dictateAbortable,
dispatchScrollPosition,
dispatchTranscriptFocus,
focusSendBoxCallbacksRef,
focusTranscriptCallbacksRef,
internalMarkdownIt,
internalRenderMarkdownInline,
nonce,
numScrollPositionObservers,
numTranscriptFocusObservers,
observeScrollPosition,
observeTranscriptFocus,
patchedStyleSet,
renderMarkdown,
scrollRelativeCallbacksRef,
scrollToCallbacksRef,
scrollToEndCallbacksRef,
setDictateAbortable,
styleToEmotionObject,
suggestedActionsAccessKey,
webSpeechPonyfill
]
);
return (
<SayComposer ponyfill={webSpeechPonyfill}>
<WebChatUIContext.Provider value={context}>
{children}
<Dictation onError={dictationOnError} />
</WebChatUIContext.Provider>
</SayComposer>
);
};
ComposerCore.defaultProps = {
children: undefined,
extraStyleSet: undefined,
nonce: undefined,
renderMarkdown: undefined,
styleSet: undefined,
suggestedActionsAccessKey: 'A a Å å',
webSpeechPonyfillFactory: undefined
};
ComposerCore.propTypes = {
extraStyleSet: PropTypes.any,
nonce: PropTypes.string,
renderMarkdown: PropTypes.func,
styleSet: PropTypes.any,
suggestedActionsAccessKey: PropTypes.oneOfType([PropTypes.oneOf([false]), PropTypes.string]),
webSpeechPonyfillFactory: PropTypes.func
};
type ComposerProps = APIComposerProps &
ComposerCoreProps & {
nonce?: string;
webSpeechPonyfillFactory?: WebSpeechPonyfillFactory;
};
const Composer: FC<ComposerProps> = ({
activityMiddleware,
activityStatusMiddleware,
attachmentForScreenReaderMiddleware,
attachmentMiddleware,
avatarMiddleware,
cardActionMiddleware,
children,
extraStyleSet,
renderMarkdown,
scrollToEndButtonMiddleware,
styleSet,
suggestedActionsAccessKey,
toastMiddleware,
typingIndicatorMiddleware,
webSpeechPonyfillFactory,
...composerProps
}) => {
const { nonce, onTelemetry } = composerProps;
const patchedActivityMiddleware = useMemo(
() => [...singleToArray(activityMiddleware), ...createDefaultActivityMiddleware()],
[activityMiddleware]
);
const patchedActivityStatusMiddleware = useMemo(
() => [...singleToArray(activityStatusMiddleware), ...createDefaultActivityStatusMiddleware()],
[activityStatusMiddleware]
);
const patchedAttachmentForScreenReaderMiddleware = useMemo(
() => [
...singleToArray(attachmentForScreenReaderMiddleware),
...createDefaultAttachmentForScreenReaderMiddleware()
],
[attachmentForScreenReaderMiddleware]
);
const patchedAttachmentMiddleware = useMemo(
() => [...singleToArray(attachmentMiddleware), ...createDefaultAttachmentMiddleware()],
[attachmentMiddleware]
);
const patchedAvatarMiddleware = useMemo(
() => [...singleToArray(avatarMiddleware), ...createDefaultAvatarMiddleware()],
[avatarMiddleware]
);
const patchedCardActionMiddleware = useMemo(
() => [...singleToArray(cardActionMiddleware), ...createDefaultCardActionMiddleware()],
[cardActionMiddleware]
);
const patchedToastMiddleware = useMemo(
() => [...singleToArray(toastMiddleware), ...createDefaultToastMiddleware()],
[toastMiddleware]
);
const patchedTypingIndicatorMiddleware = useMemo(
() => [...singleToArray(typingIndicatorMiddleware), ...createDefaultTypingIndicatorMiddleware()],
[typingIndicatorMiddleware]
);
const defaultScrollToEndButtonMiddleware = useMemo(() => createDefaultScrollToEndButtonMiddleware(), []);
const patchedScrollToEndButtonMiddleware = useMemo(
() => [...singleToArray(scrollToEndButtonMiddleware), ...defaultScrollToEndButtonMiddleware],
[defaultScrollToEndButtonMiddleware, scrollToEndButtonMiddleware]
);
return (
<React.Fragment>
<APIComposer
activityMiddleware={patchedActivityMiddleware}
activityStatusMiddleware={patchedActivityStatusMiddleware}
attachmentForScreenReaderMiddleware={patchedAttachmentForScreenReaderMiddleware}
attachmentMiddleware={patchedAttachmentMiddleware}
avatarMiddleware={patchedAvatarMiddleware}
cardActionMiddleware={patchedCardActionMiddleware}
downscaleImageToDataURL={downscaleImageToDataURL}
// Under dev server of create-react-app, "NODE_ENV" will be set to "development".
internalErrorBoxClass={node_env === 'development' ? ErrorBox : undefined}
nonce={nonce}
scrollToEndButtonMiddleware={patchedScrollToEndButtonMiddleware}
toastMiddleware={patchedToastMiddleware}
typingIndicatorMiddleware={patchedTypingIndicatorMiddleware}
{...composerProps}
>
<ComposerCore
extraStyleSet={extraStyleSet}
nonce={nonce}
renderMarkdown={renderMarkdown}
styleSet={styleSet}
suggestedActionsAccessKey={suggestedActionsAccessKey}
webSpeechPonyfillFactory={webSpeechPonyfillFactory}
>
{children}
{onTelemetry && <UITracker />}
</ComposerCore>
</APIComposer>
</React.Fragment>
);
};
Composer.defaultProps = {
...APIComposer.defaultProps,
...ComposerCore.defaultProps,
children: undefined
};
Composer.propTypes = {
...APIComposer.propTypes,
...ComposerCore.propTypes,
children: PropTypes.any
};
export default Composer;
export type { ComposerProps }; | the_stack |
import { BehaviorSubject, Subject, Observable, asapScheduler } from 'rxjs';
import { debounceTime, buffer, map, filter, take } from 'rxjs/operators';
import { ViewContainerRef } from '@angular/core';
import { ON_DESTROY, removeFromArray } from '@pebula/ngrid/core';
import { PblNgridInternalExtensionApi } from '../../ext/grid-ext-api';
import { PblColumn } from '../column/model';
import { ColumnApi } from '../column/management';
import {
RowContextState,
CellContextState,
PblNgridCellContext,
PblNgridRowContext,
CellReference,
GridDataPoint,
PblNgridFocusChangedEvent,
PblNgridSelectionChangedEvent
} from './types';
import { findRowRenderedIndex, resolveCellReference } from './utils';
import { PblRowContext } from './row';
import { PblCellContext } from './cell';
export class ContextApi<T = any> {
private viewCache = new Map<number, PblRowContext<T>>();
private viewCacheGhost = new Set<any>();
private cache = new Map<any, RowContextState<T>>();
private vcRef: ViewContainerRef;
private columnApi: ColumnApi<T>;
private activeFocused: GridDataPoint;
private activeSelected: GridDataPoint[] = [];
private focusChanged$ = new BehaviorSubject<PblNgridFocusChangedEvent>({ prev: undefined, curr: undefined });
private selectionChanged$ = new Subject<PblNgridSelectionChangedEvent>();
/**
* Notify when the focus has changed.
*
* > Note that the notification is not immediate, it will occur on the closest micro-task after the change.
*/
readonly focusChanged: Observable<PblNgridFocusChangedEvent> = this.focusChanged$
.pipe(
buffer<PblNgridFocusChangedEvent>(this.focusChanged$.pipe(debounceTime(0, asapScheduler))),
map( events => ({ prev: events[0].prev, curr: events[events.length - 1].curr }) )
);
/**
* Notify when the selected cells has changed.
*/
readonly selectionChanged: Observable<PblNgridSelectionChangedEvent> = this.selectionChanged$.asObservable();
/**
* The reference to currently focused cell context.
* You can retrieve the actual context or context cell using `findRowInView` and / or `findRowInCache`.
*
* > Note that when virtual scroll is enabled the currently focused cell does not have to exist in the view.
* If this is the case `findRowInView` will return undefined, use `findRowInCache` instead.
*/
get focusedCell(): GridDataPoint | undefined {
return this.activeFocused ? {...this.activeFocused } : undefined;
}
/**
* The reference to currently selected range of cell's context.
* You can retrieve the actual context or context cell using `findRowInView` and / or `findRowInCache`.
*
* > Note that when virtual scroll is enabled the currently selected cells does not have to exist in the view.
* If this is the case `findRowInView` will return undefined, use `findRowInCache` instead.
*/
get selectedCells(): GridDataPoint[] {
return this.activeSelected.slice();
}
constructor(private extApi: PblNgridInternalExtensionApi<T>) {
this.columnApi = extApi.columnApi;
extApi.events
.pipe(
filter( e => e.kind === 'onDataSource'),
take(1),
).subscribe(() => {
this.vcRef = extApi.cdkTable._rowOutlet.viewContainer;
this.syncViewAndContext();
extApi.cdkTable.onRenderRows.subscribe(() => this.syncViewAndContext());
});
extApi.events.pipe(ON_DESTROY).subscribe( e => this.destroy() );
}
/**
* Focus the provided cell.
* If a cell is not provided will un-focus (blur) the currently focused cell (if there is one).
* @param cellRef A Reference to the cell
*/
focusCell(cellRef?: CellReference): void {
if (!cellRef) {
if (this.activeFocused) {
const { rowIdent, colIndex } = this.activeFocused;
this.activeFocused = undefined;
this.updateState(rowIdent, colIndex, { focused: false });
this.emitFocusChanged(this.activeFocused);
const rowContext = this.findRowInView(rowIdent);
if (rowContext) {
this.extApi.grid.rowsApi.syncRows('data', rowContext.index);
}
}
} else {
const ref = resolveCellReference(cellRef, this as any);
if (ref) {
this.focusCell();
if (ref instanceof PblCellContext) {
if (!ref.focused && !this.extApi.grid.viewport.isScrolling) {
this.updateState(ref.rowContext.identity, ref.index, { focused: true });
this.activeFocused = { rowIdent: ref.rowContext.identity, colIndex: ref.index };
this.selectCells( [ this.activeFocused ], true);
this.extApi.grid.rowsApi.syncRows('data', ref.rowContext.index);
}
} else {
this.updateState(ref[0].identity, ref[1], { focused: true });
this.activeFocused = { rowIdent: ref[0].identity, colIndex: ref[1] };
}
this.emitFocusChanged(this.activeFocused);
}
}
}
/**
* Select all provided cells.
* @param cellRef A Reference to the cell
* @param clearCurrent Clear the current selection before applying the new selection.
* Default to false (add to current).
*/
selectCells(cellRefs: CellReference[], clearCurrent?: boolean): void {
const toMarkRendered = new Set<number>();
if (clearCurrent) {
this.unselectCells();
}
const added: GridDataPoint[] = [];
for (const cellRef of cellRefs) {
const ref = resolveCellReference(cellRef, this as any);
if (ref instanceof PblCellContext) {
if (!ref.selected && !this.extApi.grid.viewport.isScrolling) {
const rowIdent = ref.rowContext.identity
const colIndex = ref.index;
this.updateState(rowIdent, colIndex, { selected: true });
const dataPoint = { rowIdent, colIndex };
this.activeSelected.push(dataPoint);
added.push(dataPoint);
toMarkRendered.add(ref.rowContext.index);
}
} else if (ref) {
const [ rowState, colIndex ] = ref;
if (!rowState.cells[colIndex].selected) {
this.updateState(rowState.identity, colIndex, { selected: true });
this.activeSelected.push( { rowIdent: rowState.identity, colIndex } );
}
}
}
if (toMarkRendered.size > 0) {
this.extApi.grid.rowsApi.syncRows('data', ...Array.from(toMarkRendered.values()));
}
this.selectionChanged$.next({ added, removed: [] });
}
/**
* Unselect all provided cells.
* If cells are not provided will un-select all currently selected cells.
* @param cellRef A Reference to the cell
*/
unselectCells(cellRefs?: CellReference[]): void {
const toMarkRendered = new Set<number>();
let toUnselect: CellReference[] = this.activeSelected;
let removeAll = true;
if(Array.isArray(cellRefs)) {
toUnselect = cellRefs;
removeAll = false;
} else {
this.activeSelected = [];
}
const removed: GridDataPoint[] = [];
for (const cellRef of toUnselect) {
const ref = resolveCellReference(cellRef, this as any);
if (ref instanceof PblCellContext) {
if (ref.selected) {
const rowIdent = ref.rowContext.identity
const colIndex = ref.index;
this.updateState(rowIdent, colIndex, { selected: false });
if (!removeAll) {
const wasRemoved = removeFromArray(this.activeSelected, item => item.colIndex === colIndex && item.rowIdent === rowIdent);
if (wasRemoved) {
removed.push({ rowIdent, colIndex })
}
}
toMarkRendered.add(ref.rowContext.index);
}
} else if (ref) {
const [ rowState, colIndex ] = ref;
if (rowState.cells[colIndex].selected) {
this.updateState(rowState.identity, colIndex, { selected: false });
if (!removeAll) {
const wasRemoved = removeFromArray(this.activeSelected, item => item.colIndex === colIndex && item.rowIdent === rowState.identity);
if (wasRemoved) {
removed.push({ rowIdent: rowState.identity, colIndex })
}
}
}
}
}
if (toMarkRendered.size > 0) {
this.extApi.grid.rowsApi.syncRows('data', ...Array.from(toMarkRendered.values()));
}
this.selectionChanged$.next({ added: [], removed });
}
/**
* Clears the entire context, including view cache and memory cache (rows out of view)
* @param syncView If true will sync the view and the context right after clearing which will ensure the view cache is hot and synced with the actual rendered rows
* Some plugins will expect a row to have a context so this might be required.
* The view and context are synced every time rows are rendered so make sure you set this to true only when you know there is no rendering call coming down the pipe.
*/
clear(syncView?: boolean): void {
this.viewCache.clear();
this.viewCacheGhost.clear();
this.cache.clear();
if (syncView === true) {
for (const r of this.extApi.rowsApi.dataRows()) {
this.viewCache.set(r.rowIndex, r.context);
// we're clearing the existing view state on the component
// If in the future we want to update state and not clear, remove this one
// and instead just take the state and put it in the cache.
// e.g. if on column swap we want to swap cells in the context...
r.context.fromState(this.getCreateState(r.context));
this.syncViewAndContext();
}
}
}
saveState(context: PblNgridRowContext<T>) {
if (context instanceof PblRowContext) {
this.cache.set(context.identity, context.getState());
}
}
getRow(row: number | HTMLElement): PblNgridRowContext<T> | undefined {
const index = typeof row === 'number' ? row : findRowRenderedIndex(row);
return this.rowContext(index);
}
getCell(cell: HTMLElement | GridDataPoint): PblNgridCellContext | undefined
/**
* Return the cell context for the cell at the point specified
* @param row
* @param col
*/
getCell(row: number, col: number): PblNgridCellContext | undefined;
getCell(rowOrCellElement: number | HTMLElement | GridDataPoint, col?: number): PblNgridCellContext | undefined {
if (typeof rowOrCellElement === 'number') {
const rowContext = this.rowContext(rowOrCellElement);
if (rowContext) {
return rowContext.cell(col);
}
} else {
const ref = resolveCellReference(rowOrCellElement, this as any);
if (ref instanceof PblCellContext) {
return ref;
}
}
}
getDataItem(cell: CellReference): any {
const ref = resolveCellReference(cell, this as any);
if (ref instanceof PblCellContext) {
return ref.col.getValue(ref.rowContext.$implicit);
} else if (ref) {
const row = this.extApi.grid.ds.source[ref[0].dsIndex];
const column = this.extApi.grid.columnApi.findColumnAt(ref[1]);
return column.getValue(row);
}
}
createCellContext(renderRowIndex: number, column: PblColumn): PblCellContext<T> {
const rowContext = this.rowContext(renderRowIndex);
const colIndex = this.columnApi.indexOf(column);
return rowContext.cell(colIndex);
}
rowContext(renderRowIndex: number): PblRowContext<T> | undefined {
return this.viewCache.get(renderRowIndex);
}
updateState(rowIdentity: any, columnIndex: number, cellState: Partial<CellContextState<T>>): void;
updateState(rowIdentity: any, rowState: Partial<RowContextState<T>>): void;
updateState(rowIdentity: any, rowStateOrCellIndex: Partial<RowContextState<T>> | number, cellState?: Partial<CellContextState<T>>): void {
const currentRowState = this.cache.get(rowIdentity);
if (currentRowState) {
if (typeof rowStateOrCellIndex === 'number') {
const currentCellState = currentRowState.cells[rowStateOrCellIndex];
if (currentCellState) {
Object.assign(currentCellState, cellState);
}
} else {
Object.assign(currentRowState, rowStateOrCellIndex);
}
const rowContext = this.findRowInView(rowIdentity);
if (rowContext) {
rowContext.fromState(currentRowState);
}
}
}
/**
* Try to find a specific row, using the row identity, in the current view.
* If the row is not in the view (or even not in the cache) it will return undefined, otherwise returns the row's context instance (`PblRowContext`)
* @param rowIdentity The row's identity. If a specific identity is used, please provide it otherwise provide the index of the row in the datasource.
*/
findRowInView(rowIdentity: any): PblRowContext<T> | undefined {
const rowState = this.cache.get(rowIdentity);
if (rowState) {
const renderRowIndex = rowState.dsIndex - this.extApi.grid.ds.renderStart;
const rowContext = this.viewCache.get(renderRowIndex);
if (rowContext && rowContext.identity === rowIdentity) {
return rowContext;
}
}
}
/**
* Try to find a specific row context, using the row identity, in the context cache.
* Note that the cache does not hold the context itself but only the state that can later be used to retrieve a context instance. The context instance
* is only used as context for rows in view.
* @param rowIdentity The row's identity. If a specific identity is used, please provide it otherwise provide the index of the row in the datasource.
*/
findRowInCache(rowIdentity: any): RowContextState<T> | undefined;
/**
* Try to find a specific row context, using the row identity, in the context cache.
* Note that the cache does not hold the context itself but only the state that can later be used to retrieve a context instance. The context instance
* is only used as context for rows in view.
* @param rowIdentity The row's identity. If a specific identity is used, please provide it otherwise provide the index of the row in the datasource.
* @param offset When set, returns the row at the offset from the row with the provided row identity. Can be any numeric value (e.g 5, -6, 4).
* @param create Whether to create a new state if the current state does not exist.
*/
findRowInCache(rowIdentity: any, offset: number, create: boolean): RowContextState<T> | undefined;
findRowInCache(rowIdentity: any, offset?: number, create?: boolean): RowContextState<T> | undefined {
const rowState = this.cache.get(rowIdentity);
if (!offset) {
return rowState;
} else {
const dsIndex = rowState.dsIndex + offset;
const identity = this.getRowIdentity(dsIndex);
if (identity !== null) {
let result = this.findRowInCache(identity);
if (!result && create && dsIndex < this.extApi.grid.ds.length) {
result = PblRowContext.defaultState(identity, dsIndex, this.columnApi.columns.length);
this.cache.set(identity, result);
}
return result;
}
}
}
getRowIdentity(dsIndex: number, rowData?: T): string | number | null {
const { ds } = this.extApi.grid;
const { primary } = this.extApi.columnStore;
const row = rowData || ds.source[dsIndex];
if (!row) {
return null;
} else {
return primary ? primary.getValue(row) : dsIndex;
}
}
/** @internal */
_createRowContext(data: T, renderRowIndex: number): PblRowContext<T> {
const context = new PblRowContext<T>(data, this.extApi.grid.ds.renderStart + renderRowIndex, this.extApi);
context.fromState(this.getCreateState(context));
this.addToViewCache(renderRowIndex, context);
return context;
}
_updateRowContext(rowContext: PblRowContext<T>, renderRowIndex: number) {
const dsIndex = this.extApi.grid.ds.renderStart + renderRowIndex;
const identity = this.getRowIdentity(dsIndex, rowContext.$implicit);
if (rowContext.identity !== identity) {
rowContext.saveState();
rowContext.dsIndex = dsIndex;
rowContext.identity = identity;
rowContext.fromState(this.getCreateState(rowContext));
this.addToViewCache(renderRowIndex, rowContext)
}
}
private addToViewCache(rowIndex: number, rowContext: PblRowContext<T>) {
this.viewCache.set(rowIndex, rowContext);
this.viewCacheGhost.delete(rowContext.identity);
}
private getCreateState(context: PblRowContext<T>) {
let state = this.cache.get(context.identity);
if (!state) {
state = PblRowContext.defaultState(context.identity, context.dsIndex, this.columnApi.columns.length);
this.cache.set(context.identity, state);
}
return state;
}
private emitFocusChanged(curr: PblNgridFocusChangedEvent['curr']): void {
this.focusChanged$.next({
prev: this.focusChanged$.value.curr,
curr,
});
}
private destroy(): void {
this.focusChanged$.complete();
this.selectionChanged$.complete();
}
private syncViewAndContext() {
this.viewCacheGhost.forEach( ident => {
if (!this.findRowInView(ident)) {
this.cache.get(ident).firstRender = false
}
});
this.viewCacheGhost = new Set(Array.from(this.viewCache.values()).filter( v => v.firstRender ).map( v => v.identity ));
}
} | the_stack |
import BootstrapNotify from "../../libs/bootstrap-notify/BootstrapNotify";
import ArrayUtils from "../../core/utils/ArrayUtils";
import Loader from "../../libs/loader/Loader";
import NotePreviewDialogs from "./Dialogs/NotePreviewDialogs";
import Tippy from "../../libs/tippy/Tippy";
export default class Search {
/**
* @type Object
*/
private selectors = {
ids: {
searchInput : "#search",
SearchResultWrapper : "#searchResultListWrapper"
},
classes: {
},
other: {
}
};
/**
* @type Object
*/
private methods = {
getSearchResultsDataForTag: '/api/search/get-results-data'
};
/**
* @type Object
*/
private resultTypes = {
file: "file",
note: "note"
};
/**
* @type BootstrapNotify
*/
private bootstrapNotify = new BootstrapNotify();
/**
* @type NotePreviewDialogs
*/
private notePreviewDialogs = new NotePreviewDialogs();
/**
* @description Initialize main logic
*/
public init(): void
{
this.attachAjaxCallOnChangeOfSearchInput();
};
/**
* @description Will attach on change event on the search input
*/
private attachAjaxCallOnChangeOfSearchInput(): void
{
let _this = this;
let searchInput = $(this.selectors.ids.searchInput);
let timeout = null;
searchInput.off('change'); // prevent stacking
searchInput.on('change', () => {
let tags = $(searchInput).val();
let searchResultWrapper = $(_this.selectors.ids.SearchResultWrapper);
if( ArrayUtils.isEmpty(tags)){
if( undefined !== timeout ){
clearTimeout(timeout);
}
$(searchResultWrapper).empty();
$(searchResultWrapper).attr('style', "");
return;
}
let data = {
'tags' : tags
};
// this is used to prevent instant search whenever new character is inserted in search input
if( undefined !== timeout ){
clearTimeout(timeout);
}
Loader.showMainLoader();
timeout = setTimeout( () => {
$.ajax({
method : "POST",
url : _this.methods.getSearchResultsDataForTag,
data : data,
}).always((data)=>{
Loader.hideMainLoader();
let resultsCount = data['searchResults'].length;
let reloadPage = data['reload_page'];
let reloadMessage = data['reload_message'];
if( 0 === resultsCount ){
_this.bootstrapNotify.notify("No results for given tags.", 'danger');
return;
}
//data search result type
let filesSearchResultsList = _this.buildSearchResults(data['searchResults']);
$(searchResultWrapper).empty();
$(searchResultWrapper).append(filesSearchResultsList);
$(searchResultWrapper).css({
"overflow": "scroll"
});
Tippy.init();
_this.bootstrapNotify.notify("Found " + resultsCount + " matching result/s", 'success');
if( reloadPage ){
if( "" !== reloadMessage ){
_this.bootstrapNotify.showBlueNotification(reloadMessage);
}
location.reload();
}
})
}, 2000)
});
};
/**
* @description Will call dialog on given element
*
* @param element
* @param noteId
* @param categoryId
*/
private attachDialogCallOnTargetElement(element: JQuery, noteId: string, categoryId: string): void
{
$(element).on('click', () => {
this.notePreviewDialogs.buildNotePreviewDialog(noteId, categoryId);
})
};
/**
* @description Return UL list with the result list
*
* @param data
*/
private buildSearchResults(data: Array<string>): JQuery
{
let _this = this;
let ul = $('<ul>');
let li = null;
ul.addClass('dropdown-list animated zoomIn list-unstyled');
$.each(data, (index, result) => {
let type:String = result['type'];
let $hr = $("<hr>"); // must be created each time otherwise there are appending issues
$hr.addClass("m-0");
switch(type){
case _this.resultTypes.file:
//@ts-ignore
li = _this.buildFilesSearchResultsListElement(result);
break;
case _this.resultTypes.note:
//@ts-ignore
li = _this.buildNotesSearchResultsListElement(result);
break;
default:
throw({
"message": "Unsupported search result type",
"type" : type,
"result" : result
})
}
$(ul).append(li);
$(ul).append($hr);
});
return ul;
};
/**
* @description Builds single element of search results for files
*
* @param data
*/
private buildFilesSearchResultsListElement(data: Array<string>): JQuery
{
let tagsJson = data['tags'];
let arrayOfTags = JSON.parse(tagsJson);
let tagsList = '';
let module = data['module'];
let filename = data['filename'];
let filePath = data['fullFilePath'];
let directoryPath = data['directoryPath'];
let shortFilename = filename;
let shortLen = 16;
// build list of tags
$.each(arrayOfTags, (idx: Number, tag) => {
tagsList += tag;
if( idx < ( arrayOfTags.length - 1 ) ){
tagsList += ', ';
}
});
// build shortname
if( filename.length > shortLen ) {
shortFilename = filename.substr(0, shortLen) + '...';
}
// build download link
let downloadLink = $("<A>");
downloadLink.attr("download", "");
downloadLink.attr("href", '/' + filePath);
let downloadIcon = $('<i>');
$(downloadIcon).addClass('fa fa-download');
downloadLink.append(downloadIcon);
let moduleIcon = $('<span>');
$(moduleIcon).addClass('search-data-module-icon');
if( 'My Files' === module ){
$(moduleIcon).addClass('fas fa-folder-open d-inline');
}else if( 'My Images' === module ){
$(moduleIcon).addClass('fas fa-image d-inline');
}else if( 'My Video' === module ){
$(moduleIcon).addClass('fas fa-film d-inline');
}
let name = $('<span>');
name.css({
"margin-left": "7px"
});
$(name).html(shortFilename);
$(name).addClass("d-inline search-data-file-name");
let link = $('<a>');
$(link).attr('href', directoryPath);
$(link).append(moduleIcon);
$(link).append(name);
$(link).attr('title', filename);
// combine all to final output list element
let $singleActionDownloadLink = this.buildSingleActionWrapper();
let $li = this.buildListElement("Tags", tagsList);
let $contentWrapper = this.buildContentWrapperForListElement(link);
// build download action
$singleActionDownloadLink.append(downloadLink);
let allActions = [
$singleActionDownloadLink
];
let $actionsWrapperWithActions = this.buildActionsWrapper(allActions);
$($li).append($contentWrapper);
$($li).append($actionsWrapperWithActions);
return $li;
};
/**
* @description Builds single element of search results for notes
*
* @param data
*/
private buildNotesSearchResultsListElement(data: Array<string>): JQuery<HTMLElement>
{
let title = data['title'];
let shortTitle = title;
let category = data['category'];
let categoryId = data['categoryId'];
let noteId = data['noteId'];
let shortLen = 16;
// build short title
if( title.length > shortLen ) {
shortTitle = title.substr(0, shortLen) + '...';
}
// build note preview
let $notePreviewButton = $('<button>');
$notePreviewButton.addClass('note-preview-search-result button-icon d-inline');
this.attachDialogCallOnTargetElement($notePreviewButton, noteId, categoryId);
let previewIcon = $('<i>');
$(previewIcon).addClass('far fa-eye');
$notePreviewButton.append(previewIcon);
let moduleIcon = $('<span>');
$(moduleIcon).addClass('search-data-module-icon');
$(moduleIcon).addClass('fas fa-book d-inline');
let name = $('<span>');
$(name).html(shortTitle);
$(name).addClass("d-inline search-data-file-name");
name.css({
"margin-left": "7px"
});
let link = $('<a>');
$(link).attr('href', '/my-notes/category/' + category + '/' + categoryId);
$(link).append(moduleIcon);
$(link).append(name);
// combine all to final output list element
let $singleActionNotePreview = this.buildSingleActionWrapper();
let $li = this.buildListElement("Title", title);
let $contentWrapper = this.buildContentWrapperForListElement(link);
$singleActionNotePreview.append($notePreviewButton);
let allActions = [
$singleActionNotePreview
];
let $actionsWrapperWithActions = this.buildActionsWrapper(allActions);
$($li).append($contentWrapper);
$($li).append($actionsWrapperWithActions);
return $li;
};
/**
* @description will return single list element used in the search result
*/
private buildListElement(popoverContentName: String, popoverContent: String): JQuery<HTMLElement>
{
let li = $('<li>');
//add popover to list element
$(li).attr(
'data-content',
`<p style='display: flex;'>
<span style='font-weight: bold; '>
${popoverContentName}:
</span>
<span style='word-break: break-all;'>${popoverContent}</span>
</p>`
);
$(li).attr('data-html', "true");
$(li).attr('data-toggle-popover', 'true');
$(li).attr('data-placement', 'right');
$(li).attr('data-offset', "0 -25%");
$(li).attr('data-offset', "0 -25%");
li.addClass('option d-flex justify-content-around');
li.css({
"padding": "10px !important"
});
return li;
}
/**
* @description will return content wrapper element used to contain the link to page
*/
private buildContentWrapperForListElement($link: JQuery<HTMLElement>): JQuery<HTMLElement>
{
let contentWrapper = $('<SPAN>');
contentWrapper.css({
"width": "100%"
})
contentWrapper.append($link);
return contentWrapper;
}
/**
* @description will return single element used as a wrapper for action
*/
private buildSingleActionWrapper(): JQuery<HTMLElement>
{
let $actionWrapperElement = $('<SPAN>');
$actionWrapperElement.addClass("text-center pointer");
$actionWrapperElement.css({
"width" : "50px",
"display": "block"
})
return $actionWrapperElement;
}
/**
* @description will return the actions wrapper filled up with actions
* @param actionsWrappers
*/
private buildActionsWrapper(actionsWrappers: Array<JQuery<HTMLElement>>): JQuery<HTMLElement>
{
let $actionsWrapper = $('<SPAN>')
$.each(actionsWrappers, (index, $element) => {
$actionsWrapper.append($element);
})
return $actionsWrapper;
}
} | the_stack |
import { stub } from 'sinon';
import HttpProvider from 'ethjs-provider-http';
import {
NetworksChainId,
NetworkType,
NetworkState,
} from '../network/NetworkController';
import {
TransactionController,
TransactionStatus,
TransactionMeta,
} from './TransactionController';
import {
ethTxsMock,
tokenTxsMock,
txsInStateMock,
txsInStateWithOutdatedStatusMock,
txsInStateWithOutdatedGasDataMock,
txsInStateWithOutdatedStatusAndGasDataMock,
} from './mocks/txsMock';
const globalAny: any = global;
const mockFlags: { [key: string]: any } = {
estimateGas: null,
};
jest.mock('eth-query', () =>
jest.fn().mockImplementation(() => {
return {
estimateGas: (_transaction: any, callback: any) => {
if (mockFlags.estimateGas) {
callback(new Error(mockFlags.estimateGas));
return;
}
callback(undefined, '0x0');
},
gasPrice: (callback: any) => {
callback(undefined, '0x0');
},
getBlockByNumber: (
_blocknumber: any,
_fetchTxs: boolean,
callback: any,
) => {
callback(undefined, { gasLimit: '0x0' });
},
getCode: (_to: any, callback: any) => {
callback(undefined, '0x0');
},
getTransactionByHash: (_hash: string, callback: any) => {
const txs: any = [
{ transactionHash: '1337', blockNumber: '0x1' },
{ transactionHash: '1338', blockNumber: null },
];
const tx: any = txs.find(
(element: any) => element.transactionHash === _hash,
);
callback(undefined, tx);
},
getTransactionCount: (_from: any, _to: any, callback: any) => {
callback(undefined, '0x0');
},
sendRawTransaction: (_transaction: any, callback: any) => {
callback(undefined, '1337');
},
getTransactionReceipt: (_hash: any, callback: any) => {
const txs: any = [
{ transactionHash: '1337', gasUsed: '0x5208', status: '0x1' },
{ transactionHash: '1111', gasUsed: '0x1108', status: '0x0' },
];
const tx: any = txs.find(
(element: any) => element.transactionHash === _hash,
);
callback(undefined, tx);
},
};
}),
);
/**
* Create a mock implementation of `fetch` that always returns the same data.
*
* @param data - The mock data to return.
* @returns The mock `fetch` implementation.
*/
function mockFetch(data: any) {
return jest.fn().mockImplementation(() =>
Promise.resolve({
json: () => data,
ok: true,
}),
);
}
/**
* Create a mock implementation of `fetch` that returns different mock data for each URL.
*
* @param data - A map of mock data, keyed by URL.
* @returns The mock `fetch` implementation.
*/
function mockFetchs(data: any) {
return jest.fn().mockImplementation((key) =>
Promise.resolve({
json: () => data[key],
ok: true,
}),
);
}
const MOCK_PRFERENCES = { state: { selectedAddress: 'foo' } };
const PROVIDER = new HttpProvider(
'https://ropsten.infura.io/v3/341eacb578dd44a1a049cbc5f6fd4035',
);
const MAINNET_PROVIDER = new HttpProvider(
'https://mainnet.infura.io/v3/341eacb578dd44a1a049cbc5f6fd4035',
);
const MOCK_NETWORK = {
getProvider: () => PROVIDER,
state: {
network: '3',
isCustomNetwork: false,
properties: { isEIP1559Compatible: false },
provider: {
type: 'ropsten' as NetworkType,
chainId: NetworksChainId.ropsten,
},
},
subscribe: () => undefined,
};
const MOCK_NETWORK_CUSTOM = {
getProvider: () => PROVIDER,
state: {
network: '10',
isCustomNetwork: true,
properties: { isEIP1559Compatible: false },
provider: {
type: 'optimism' as NetworkType,
chainId: NetworksChainId.optimism,
},
},
subscribe: () => undefined,
};
const MOCK_NETWORK_WITHOUT_CHAIN_ID = {
getProvider: () => PROVIDER,
isCustomNetwork: false,
state: { network: '3', provider: { type: 'ropsten' as NetworkType } },
subscribe: () => undefined,
};
const MOCK_MAINNET_NETWORK = {
getProvider: () => MAINNET_PROVIDER,
state: {
network: '1',
isCustomNetwork: false,
properties: { isEIP1559Compatible: false },
provider: {
type: 'mainnet' as NetworkType,
chainId: NetworksChainId.mainnet,
},
},
subscribe: () => undefined,
};
const MOCK_CUSTOM_NETWORK = {
getProvider: () => MAINNET_PROVIDER,
state: {
network: '80001',
isCustomNetwork: true,
properties: { isEIP1559Compatible: false },
provider: {
type: 'rpc' as NetworkType,
chainId: '80001',
},
},
subscribe: () => undefined,
};
const TOKEN_TRANSACTION_HASH =
'0x01d1cebeab9da8d887b36000c25fa175737e150f193ea37d5bb66347d834e999';
const ETHER_TRANSACTION_HASH =
'0xa9d17df83756011ea63e1f0ca50a6627df7cac9806809e36680fcf4e88cb9dae';
const ETH_TRANSACTIONS = ethTxsMock(ETHER_TRANSACTION_HASH);
const TOKEN_TRANSACTIONS = tokenTxsMock(TOKEN_TRANSACTION_HASH);
const TRANSACTIONS_IN_STATE: TransactionMeta[] = txsInStateMock(
ETHER_TRANSACTION_HASH,
TOKEN_TRANSACTION_HASH,
);
const TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS: TransactionMeta[] = txsInStateWithOutdatedStatusMock(
ETHER_TRANSACTION_HASH,
TOKEN_TRANSACTION_HASH,
);
const TRANSACTIONS_IN_STATE_WITH_OUTDATED_GAS_DATA: TransactionMeta[] = txsInStateWithOutdatedGasDataMock(
ETHER_TRANSACTION_HASH,
TOKEN_TRANSACTION_HASH,
);
const TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS_AND_GAS_DATA: TransactionMeta[] = txsInStateWithOutdatedStatusAndGasDataMock(
ETHER_TRANSACTION_HASH,
TOKEN_TRANSACTION_HASH,
);
const ETH_TX_HISTORY_DATA = {
message: 'OK',
result: ETH_TRANSACTIONS,
status: '1',
};
const ETH_TX_HISTORY_DATA_FROM_BLOCK = {
message: 'OK',
result: [ETH_TRANSACTIONS[0], ETH_TRANSACTIONS[1]],
status: '1',
};
const TOKEN_TX_HISTORY_DATA = {
message: 'OK',
result: TOKEN_TRANSACTIONS,
status: '1',
};
const TOKEN_TX_HISTORY_DATA_FROM_BLOCK = {
message: 'OK',
result: [TOKEN_TRANSACTIONS[0]],
status: '1',
};
const ETH_TX_HISTORY_DATA_ROPSTEN_NO_TRANSACTIONS_FOUND = {
message: 'No transactions found',
result: [],
status: '0',
};
const MOCK_FETCH_TX_HISTORY_DATA_OK = {
'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=tokentx&tag=latest&page=1': ETH_TX_HISTORY_DATA_ROPSTEN_NO_TRANSACTIONS_FOUND,
'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=tokentx&tag=latest&page=1': TOKEN_TX_HISTORY_DATA,
'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&startBlock=999&offset=40&order=desc&action=tokentx&tag=latest&page=1': TOKEN_TX_HISTORY_DATA_FROM_BLOCK,
'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=txlist&tag=latest&page=1': ETH_TX_HISTORY_DATA,
'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=txlist&tag=latest&page=1': ETH_TX_HISTORY_DATA,
'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&startBlock=999&offset=40&order=desc&action=txlist&tag=latest&page=1': ETH_TX_HISTORY_DATA_FROM_BLOCK,
'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=2&order=desc&action=tokentx&tag=latest&page=1': ETH_TX_HISTORY_DATA_ROPSTEN_NO_TRANSACTIONS_FOUND,
'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=2&order=desc&action=txlist&tag=latest&page=1': ETH_TX_HISTORY_DATA,
};
const MOCK_FETCH_TX_HISTORY_DATA_ERROR = {
status: '0',
};
describe('TransactionController', () => {
beforeEach(() => {
for (const key in mockFlags) {
mockFlags[key] = null;
}
});
it('should set default state', () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
expect(controller.state).toStrictEqual({
methodData: {},
transactions: [],
});
});
it('should set default config', () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
expect(controller.config).toStrictEqual({
interval: 15000,
txHistoryLimit: 40,
});
});
it('should poll and update transaction statuses in the right interval', async () => {
await new Promise((resolve) => {
const mock = stub(
TransactionController.prototype,
'queryTransactionStatuses',
);
new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{ interval: 10 },
);
expect(mock.called).toBe(true);
expect(mock.calledTwice).toBe(false);
setTimeout(() => {
expect(mock.calledTwice).toBe(true);
mock.restore();
resolve('');
}, 15);
});
});
it('should clear previous interval', async () => {
const mock = stub(global, 'clearTimeout');
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{ interval: 1337 },
);
await new Promise((resolve) => {
setTimeout(() => {
controller.poll(1338);
expect(mock.called).toBe(true);
mock.restore();
resolve('');
}, 100);
});
});
it('should not update the state if there are no updates on transaction statuses', async () => {
await new Promise((resolve) => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{ interval: 10 },
);
const func = stub(controller, 'update');
setTimeout(() => {
expect(func.called).toBe(false);
func.restore();
resolve('');
}, 20);
});
});
it('should throw when adding invalid transaction', async () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
await expect(
controller.addTransaction({ from: 'foo' } as any),
).rejects.toThrow('Invalid "from" address');
});
it('should add a valid transaction', async () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({
from,
to: from,
});
expect(controller.state.transactions[0].transaction.from).toBe(from);
expect(controller.state.transactions[0].networkID).toBe(
MOCK_NETWORK.state.network,
);
expect(controller.state.transactions[0].chainId).toBe(
MOCK_NETWORK.state.provider.chainId,
);
expect(controller.state.transactions[0].status).toBe(
TransactionStatus.unapproved,
);
});
it('should add a valid transaction after a network switch', async () => {
const getNetworkState = stub().returns(MOCK_NETWORK.state);
let networkStateChangeListener:
| ((state: NetworkState) => void)
| null = null;
const onNetworkStateChange = (listener: (state: NetworkState) => void) => {
networkStateChangeListener = listener;
};
const getProvider = stub().returns(PROVIDER);
const controller = new TransactionController({
getNetworkState,
onNetworkStateChange,
getProvider,
});
// switch from Ropsten to Mainnet
getNetworkState.returns(MOCK_MAINNET_NETWORK.state);
getProvider.returns(MAINNET_PROVIDER);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
networkStateChangeListener!(MOCK_MAINNET_NETWORK.state);
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({
from,
to: from,
});
expect(controller.state.transactions[0].transaction.from).toBe(from);
expect(controller.state.transactions[0].networkID).toBe(
MOCK_MAINNET_NETWORK.state.network,
);
expect(controller.state.transactions[0].chainId).toBe(
MOCK_MAINNET_NETWORK.state.provider.chainId,
);
expect(controller.state.transactions[0].status).toBe(
TransactionStatus.unapproved,
);
});
it('should add a valid transaction after a switch to custom network', async () => {
const getNetworkState = stub().returns(MOCK_NETWORK.state);
let networkStateChangeListener:
| ((state: NetworkState) => void)
| null = null;
const onNetworkStateChange = (listener: (state: NetworkState) => void) => {
networkStateChangeListener = listener;
};
const getProvider = stub().returns(PROVIDER);
const controller = new TransactionController({
getNetworkState,
onNetworkStateChange,
getProvider,
});
// switch from Ropsten to Mainnet
getNetworkState.returns(MOCK_NETWORK_CUSTOM.state);
getProvider.returns(PROVIDER);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
networkStateChangeListener!(MOCK_NETWORK_CUSTOM.state);
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({
from,
to: from,
});
expect(controller.state.transactions[0].transaction.from).toBe(from);
expect(controller.state.transactions[0].networkID).toBe(
MOCK_NETWORK_CUSTOM.state.network,
);
expect(controller.state.transactions[0].chainId).toBe(
MOCK_NETWORK_CUSTOM.state.provider.chainId,
);
expect(controller.state.transactions[0].status).toBe(
TransactionStatus.unapproved,
);
});
it('should cancel a transaction', async () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
const { result } = await controller.addTransaction({
from,
to: from,
});
controller.cancelTransaction('foo');
const transactionListener = new Promise(async (resolve) => {
controller.hub.once(
`${controller.state.transactions[0].id}:finished`,
() => {
expect(controller.state.transactions[0].transaction.from).toBe(from);
expect(controller.state.transactions[0].status).toBe(
TransactionStatus.rejected,
);
resolve('');
},
);
});
controller.cancelTransaction(controller.state.transactions[0].id);
await expect(result).rejects.toThrow('User rejected the transaction');
await transactionListener;
});
it('should wipe transactions', async () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
controller.wipeTransactions();
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({
from,
to: from,
});
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
});
// This tests the fallback to networkID only when there is no chainId present. Should be removed when networkID is completely removed.
it('should wipe transactions using networkID when there is no chainId', async () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
controller.wipeTransactions();
controller.state.transactions.push({
from: MOCK_PRFERENCES.state.selectedAddress,
id: 'foo',
networkID: '3',
status: TransactionStatus.submitted,
transactionHash: '1337',
} as any);
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
});
it('should approve custom network transaction', async () => {
await new Promise(async (resolve) => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_CUSTOM_NETWORK.state,
onNetworkStateChange: MOCK_CUSTOM_NETWORK.subscribe,
getProvider: MOCK_CUSTOM_NETWORK.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({
from,
gas: '0x0',
gasPrice: '0x0',
to: from,
value: '0x0',
});
controller.hub.once(
`${controller.state.transactions[0].id}:finished`,
() => {
const { transaction, status } = controller.state.transactions[0];
expect(transaction.from).toBe(from);
expect(status).toBe(TransactionStatus.submitted);
resolve('');
},
);
controller.approveTransaction(controller.state.transactions[0].id);
});
});
it('should fail to approve an invalid transaction', async () => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
sign: () => {
throw new Error('foo');
},
},
);
const from = '0xe6509775f3f3614576c0d83f8647752f87cd6659';
const to = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
const { result } = await controller.addTransaction({ from, to });
await controller.approveTransaction(controller.state.transactions[0].id);
const { transaction, status } = controller.state.transactions[0];
expect(transaction.from).toBe(from);
expect(transaction.to).toBe(to);
expect(status).toBe(TransactionStatus.failed);
await expect(result).rejects.toThrow('foo');
});
it('should fail transaction if gas calculation fails', async () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
mockFlags.estimateGas = 'Uh oh';
await expect(
controller.addTransaction({
from,
to: from,
}),
).rejects.toThrow('Uh oh');
});
it('should fail if no sign method defined', async () => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{},
);
const from = '0xe6509775f3f3614576c0d83f8647752f87cd6659';
const to = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
const { result } = await controller.addTransaction({ from, to });
await controller.approveTransaction(controller.state.transactions[0].id);
const { transaction, status } = controller.state.transactions[0];
expect(transaction.from).toBe(from);
expect(transaction.to).toBe(to);
expect(status).toBe(TransactionStatus.failed);
await expect(result).rejects.toThrow('No sign method defined');
});
it('should fail if no chainId is defined', async () => {
const controller = new TransactionController(
{
getNetworkState: () =>
MOCK_NETWORK_WITHOUT_CHAIN_ID.state as NetworkState,
onNetworkStateChange: MOCK_NETWORK_WITHOUT_CHAIN_ID.subscribe,
getProvider: MOCK_NETWORK_WITHOUT_CHAIN_ID.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
const from = '0xe6509775f3f3614576c0d83f8647752f87cd6659';
const to = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
const { result } = await controller.addTransaction({ from, to });
await controller.approveTransaction(controller.state.transactions[0].id);
const { transaction, status } = controller.state.transactions[0];
expect(transaction.from).toBe(from);
expect(transaction.to).toBe(to);
expect(status).toBe(TransactionStatus.failed);
await expect(result).rejects.toThrow('No chainId defined');
});
it('should approve a transaction', async () => {
await new Promise(async (resolve) => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({
from,
gas: '0x0',
gasPrice: '0x0',
to: from,
value: '0x0',
});
controller.hub.once(
`${controller.state.transactions[0].id}:finished`,
() => {
const { transaction, status } = controller.state.transactions[0];
expect(transaction.from).toBe(from);
expect(status).toBe(TransactionStatus.submitted);
resolve('');
},
);
controller.approveTransaction(controller.state.transactions[0].id);
});
});
it('should query transaction statuses', async () => {
await new Promise((resolve) => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
controller.state.transactions.push({
from: MOCK_PRFERENCES.state.selectedAddress,
id: 'foo',
networkID: '3',
chainId: '3',
status: TransactionStatus.submitted,
transactionHash: '1337',
} as any);
controller.state.transactions.push({} as any);
controller.hub.once(
`${controller.state.transactions[0].id}:confirmed`,
() => {
expect(controller.state.transactions[0].status).toBe(
TransactionStatus.confirmed,
);
resolve('');
},
);
controller.queryTransactionStatuses();
});
});
// This tests the fallback to networkID only when there is no chainId present. Should be removed when networkID is completely removed.
it('should query transaction statuses with networkID only when there is no chainId', async () => {
await new Promise((resolve) => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
controller.state.transactions.push({
from: MOCK_PRFERENCES.state.selectedAddress,
id: 'foo',
networkID: '3',
status: TransactionStatus.submitted,
transactionHash: '1337',
} as any);
controller.state.transactions.push({} as any);
controller.hub.once(
`${controller.state.transactions[0].id}:confirmed`,
() => {
expect(controller.state.transactions[0].status).toBe(
TransactionStatus.confirmed,
);
resolve('');
},
);
controller.queryTransactionStatuses();
});
});
it('should keep the transaction status as submitted if the transaction was not added to a block', async () => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
controller.state.transactions.push({
from: MOCK_PRFERENCES.state.selectedAddress,
id: 'foo',
networkID: '3',
status: TransactionStatus.submitted,
transactionHash: '1338',
} as any);
await controller.queryTransactionStatuses();
expect(controller.state.transactions[0].status).toBe(
TransactionStatus.submitted,
);
});
it('should verify the transaction using the correct blockchain', async () => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
controller.state.transactions.push({
from: MOCK_PRFERENCES.state.selectedAddress,
id: 'foo',
networkID: '3',
chainId: '3',
status: TransactionStatus.confirmed,
transactionHash: '1337',
verifiedOnBlockchain: false,
transaction: {
gasUsed: undefined,
},
} as any);
await controller.queryTransactionStatuses();
expect(controller.state.transactions[0].verifiedOnBlockchain).toBe(true);
expect(controller.state.transactions[0].transaction.gasUsed).toBe('0x5208');
});
it('should fetch all the transactions from an address, including incoming transactions, in ropsten', async () => {
globalAny.fetch = mockFetchs(MOCK_FETCH_TX_HISTORY_DATA_OK);
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
const latestBlock = await controller.fetchAll(from);
expect(controller.state.transactions).toHaveLength(4);
expect(latestBlock).toBe('4535101');
expect(controller.state.transactions[0].transaction.to).toBe(from);
});
it('should fetch all the transactions from an address, including incoming token transactions, in mainnet', async () => {
globalAny.fetch = mockFetchs(MOCK_FETCH_TX_HISTORY_DATA_OK);
const controller = new TransactionController({
getNetworkState: () => MOCK_MAINNET_NETWORK.state,
onNetworkStateChange: MOCK_MAINNET_NETWORK.subscribe,
getProvider: MOCK_MAINNET_NETWORK.getProvider,
});
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
const latestBlock = await controller.fetchAll(from);
expect(controller.state.transactions).toHaveLength(17);
expect(latestBlock).toBe('4535101');
expect(controller.state.transactions[0].transaction.to).toBe(from);
});
it('should fetch all the transactions from an address, including incoming token transactions without modifying transactions that have the same data in local and remote', async () => {
globalAny.fetch = mockFetchs(MOCK_FETCH_TX_HISTORY_DATA_OK);
const controller = new TransactionController({
getNetworkState: () => MOCK_MAINNET_NETWORK.state,
onNetworkStateChange: MOCK_MAINNET_NETWORK.subscribe,
getProvider: MOCK_MAINNET_NETWORK.getProvider,
});
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
controller.wipeTransactions();
controller.state.transactions = TRANSACTIONS_IN_STATE;
await controller.fetchAll(from);
expect(controller.state.transactions).toHaveLength(17);
const tokenTransaction = controller.state.transactions.find(
({ transactionHash }) => transactionHash === TOKEN_TRANSACTION_HASH,
) || { id: '' };
const ethTransaction = controller.state.transactions.find(
({ transactionHash }) => transactionHash === ETHER_TRANSACTION_HASH,
) || { id: '' };
expect(tokenTransaction?.id).toStrictEqual('token-transaction-id');
expect(ethTransaction?.id).toStrictEqual('eth-transaction-id');
});
it('should fetch all the transactions from an address, including incoming transactions, in mainnet from block', async () => {
globalAny.fetch = mockFetchs(MOCK_FETCH_TX_HISTORY_DATA_OK);
const controller = new TransactionController({
getNetworkState: () => MOCK_MAINNET_NETWORK.state,
onNetworkStateChange: MOCK_MAINNET_NETWORK.subscribe,
getProvider: MOCK_MAINNET_NETWORK.getProvider,
});
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
const latestBlock = await controller.fetchAll(from, { fromBlock: '999' });
expect(controller.state.transactions).toHaveLength(3);
expect(latestBlock).toBe('4535101');
expect(controller.state.transactions[0].transaction.to).toBe(from);
});
it('should fetch and updated all transactions with outdated status regarding the data provided by the remote source in mainnet', async () => {
globalAny.fetch = mockFetchs(MOCK_FETCH_TX_HISTORY_DATA_OK);
const controller = new TransactionController({
getNetworkState: () => MOCK_MAINNET_NETWORK.state,
onNetworkStateChange: MOCK_MAINNET_NETWORK.subscribe,
getProvider: MOCK_MAINNET_NETWORK.getProvider,
});
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
controller.state.transactions = TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS;
await controller.fetchAll(from);
expect(controller.state.transactions).toHaveLength(17);
const tokenTransaction = controller.state.transactions.find(
({ transactionHash }) => transactionHash === TOKEN_TRANSACTION_HASH,
) || { status: TransactionStatus.failed };
const ethTransaction = controller.state.transactions.find(
({ transactionHash }) => transactionHash === ETHER_TRANSACTION_HASH,
) || { status: TransactionStatus.failed };
expect(tokenTransaction?.status).toStrictEqual(TransactionStatus.confirmed);
expect(ethTransaction?.status).toStrictEqual(TransactionStatus.confirmed);
});
it('should fetch and updated all transactions with outdated gas data regarding the data provided by the remote source in mainnet', async () => {
globalAny.fetch = mockFetchs(MOCK_FETCH_TX_HISTORY_DATA_OK);
const controller = new TransactionController({
getNetworkState: () => MOCK_MAINNET_NETWORK.state,
onNetworkStateChange: MOCK_MAINNET_NETWORK.subscribe,
getProvider: MOCK_MAINNET_NETWORK.getProvider,
});
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
controller.state.transactions = TRANSACTIONS_IN_STATE_WITH_OUTDATED_GAS_DATA;
await controller.fetchAll(from);
expect(controller.state.transactions).toHaveLength(17);
const tokenTransaction = controller.state.transactions.find(
({ transactionHash }) => transactionHash === TOKEN_TRANSACTION_HASH,
) || { transaction: { gasUsed: '0' } };
const ethTransaction = controller.state.transactions.find(
({ transactionHash }) => transactionHash === ETHER_TRANSACTION_HASH,
) || { transaction: { gasUsed: '0x0' } };
expect(tokenTransaction?.transaction.gasUsed).toStrictEqual('21000');
expect(ethTransaction?.transaction.gasUsed).toStrictEqual('0x5208');
});
it('should fetch and updated all transactions with outdated status and gas data regarding the data provided by the remote source in mainnet', async () => {
globalAny.fetch = mockFetchs(MOCK_FETCH_TX_HISTORY_DATA_OK);
const controller = new TransactionController({
getNetworkState: () => MOCK_MAINNET_NETWORK.state,
onNetworkStateChange: MOCK_MAINNET_NETWORK.subscribe,
getProvider: MOCK_MAINNET_NETWORK.getProvider,
});
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
controller.state.transactions = TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS_AND_GAS_DATA;
await controller.fetchAll(from);
expect(controller.state.transactions).toHaveLength(17);
const tokenTransaction = controller.state.transactions.find(
({ transactionHash }) => transactionHash === TOKEN_TRANSACTION_HASH,
) || { status: TransactionStatus.failed, transaction: { gasUsed: '0' } };
const ethTransaction = controller.state.transactions.find(
({ transactionHash }) => transactionHash === ETHER_TRANSACTION_HASH,
) || { status: TransactionStatus.failed, transaction: { gasUsed: '0x0' } };
expect(tokenTransaction?.status).toStrictEqual(TransactionStatus.confirmed);
expect(ethTransaction?.status).toStrictEqual(TransactionStatus.confirmed);
expect(tokenTransaction?.transaction.gasUsed).toStrictEqual('21000');
expect(ethTransaction?.transaction.gasUsed).toStrictEqual('0x5208');
});
it('should return', async () => {
globalAny.fetch = mockFetch(MOCK_FETCH_TX_HISTORY_DATA_ERROR);
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
controller.wipeTransactions();
expect(controller.state.transactions).toHaveLength(0);
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
const result = await controller.fetchAll(from);
expect(controller.state.transactions).toHaveLength(0);
expect(result).toBeUndefined();
});
it('should handle new method data', async () => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_MAINNET_NETWORK.state,
onNetworkStateChange: MOCK_MAINNET_NETWORK.subscribe,
getProvider: MOCK_MAINNET_NETWORK.getProvider,
},
{},
);
const registry = await controller.handleMethodData('0xf39b5b9b');
expect(registry.parsedRegistryMethod).toStrictEqual({
args: [{ type: 'uint256' }, { type: 'uint256' }],
name: 'Eth To Token Swap Input',
});
expect(registry.registryMethod).toStrictEqual(
'ethToTokenSwapInput(uint256,uint256)',
);
});
it('should handle known method data', async () => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_MAINNET_NETWORK.state,
onNetworkStateChange: MOCK_MAINNET_NETWORK.subscribe,
getProvider: MOCK_MAINNET_NETWORK.getProvider,
},
{},
);
const registry = await controller.handleMethodData('0xf39b5b9b');
expect(registry.parsedRegistryMethod).toStrictEqual({
args: [{ type: 'uint256' }, { type: 'uint256' }],
name: 'Eth To Token Swap Input',
});
const registryLookup = stub(controller, 'registryLookup' as any);
await controller.handleMethodData('0xf39b5b9b');
expect(registryLookup.called).toBe(false);
});
it('should stop a transaction', async () => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
const { result } = await controller.addTransaction({
from,
gas: '0x0',
gasPrice: '0x1',
to: from,
value: '0x0',
});
controller.stopTransaction(controller.state.transactions[0].id);
await expect(result).rejects.toThrow('User cancelled the transaction');
});
it('should fail to stop a transaction if no sign method', async () => {
const controller = new TransactionController({
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
});
const from = '0xe6509775f3f3614576c0d83f8647752f87cd6659';
const to = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({ from, to });
controller.stopTransaction('nonexistent');
await expect(
controller.stopTransaction(controller.state.transactions[0].id),
).rejects.toThrow('No sign method defined');
});
it('should speed up a transaction', async () => {
await new Promise(async (resolve) => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
sign: async (transaction: any) => transaction,
},
);
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({
from,
gas: '0x0',
gasPrice: '0x50fd51da',
to: from,
value: '0x0',
});
await controller.speedUpTransaction(controller.state.transactions[0].id);
expect(controller.state.transactions).toHaveLength(2);
expect(controller.state.transactions[1].transaction.gasPrice).toBe(
'0x5916a6d6',
);
resolve('');
});
});
it('should limit tx state to a length of 2', async () => {
await new Promise(async (resolve) => {
globalAny.fetch = mockFetchs(MOCK_FETCH_TX_HISTORY_DATA_OK);
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
interval: 5000,
sign: async (transaction: any) => transaction,
txHistoryLimit: 2,
},
);
const from = '0x6bf137f335ea1b8f193b8f6ea92561a60d23a207';
await controller.fetchAll(from);
await controller.addTransaction({
from,
nonce: '55555',
gas: '0x0',
gasPrice: '0x50fd51da',
to: from,
value: '0x0',
});
expect(controller.state.transactions).toHaveLength(2);
expect(controller.state.transactions[0].transaction.gasPrice).toBe(
'0x4a817c800',
);
resolve('');
});
});
it('should allow tx state to be greater than txHistorylimit due to speed up same nonce', async () => {
await new Promise(async (resolve) => {
const controller = new TransactionController(
{
getNetworkState: () => MOCK_NETWORK.state,
onNetworkStateChange: MOCK_NETWORK.subscribe,
getProvider: MOCK_NETWORK.getProvider,
},
{
interval: 5000,
sign: async (transaction: any) => transaction,
txHistoryLimit: 1,
},
);
const from = '0xc38bf1ad06ef69f0c04e29dbeb4152b4175f0a8d';
await controller.addTransaction({
from,
nonce: '1111111',
gas: '0x0',
gasPrice: '0x50fd51da',
to: from,
value: '0x0',
});
await controller.speedUpTransaction(controller.state.transactions[0].id);
expect(controller.state.transactions).toHaveLength(2);
resolve('');
});
});
}); | the_stack |
import { trimLatexAndAddCSS, preProcessLatex } from './utils';
import { getCollectionHooks } from '../mutationCallbacks';
import { sanitize } from '../vulcan-lib/utils';
import { randomId } from '../../lib/random';
import { convertFromRaw } from 'draft-js';
import { draftToHTML } from '../draftConvert';
import { Revisions, ChangeMetrics } from '../../lib/collections/revisions/collection'
import { extractVersionsFromSemver } from '../../lib/editor/utils'
import { ensureIndex } from '../../lib/collectionUtils'
import { htmlToPingbacks } from '../pingbacks';
import { captureException } from '@sentry/core';
import { diff } from '../vendor/node-htmldiff/htmldiff';
import { editableCollections, editableCollectionsFields, editableCollectionsFieldOptions, sealEditableFields, MakeEditableOptions } from '../../lib/editor/make_editable';
import { getCollection } from '../../lib/vulcan-lib/getCollection';
import { CallbackHook } from '../../lib/vulcan-lib/callbacks';
import { createMutator } from '../vulcan-lib/mutators';
import TurndownService from 'turndown';
import {gfm} from 'turndown-plugin-gfm';
import * as _ from 'underscore';
import markdownIt from 'markdown-it'
import markdownItMathjax from './markdown-mathjax'
import cheerio from 'cheerio';
import markdownItContainer from 'markdown-it-container'
import markdownItFootnote from 'markdown-it-footnote'
import markdownItSub from 'markdown-it-sub'
import markdownItSup from 'markdown-it-sup'
const turndownService = new TurndownService()
turndownService.use(gfm); // Add support for strikethrough and tables
turndownService.remove('style') // Make sure we don't add the content of style tags to the markdown
turndownService.addRule('subscript', {
filter: ['sub'],
replacement: (content) => `~${content}~`
})
turndownService.addRule('supscript', {
filter: ['sup'],
replacement: (content) => `^${content}^`
})
turndownService.addRule('italic', {
filter: ['i'],
replacement: (content) => `*${content}*`
})
const mdi = markdownIt({linkify: true})
mdi.use(markdownItMathjax())
mdi.use(markdownItContainer, 'spoiler')
mdi.use(markdownItFootnote)
mdi.use(markdownItSub)
mdi.use(markdownItSup)
import { mjpage } from 'mathjax-node-page'
import { onStartup, isAnyTest } from '../../lib/executionEnvironment';
// TODO: Now that the make_editable callbacks use createMutator to create
// revisions, we can now add these to the regular ${collection}.create.after
// callbacks
interface AfterCreateRevisionCallbackContext {
revisionID: string
}
export const afterCreateRevisionCallback = new CallbackHook<[AfterCreateRevisionCallbackContext]>("revisions.afterRevisionCreated");
export function mjPagePromise(html: string, beforeSerializationCallback: (dom: any, css: string)=>any): Promise<string> {
// Takes in HTML and replaces LaTeX with CommonHTML snippets
// https://github.com/pkra/mathjax-node-page
return new Promise((resolve, reject) => {
let finished = false;
if (!isAnyTest) {
setTimeout(() => {
if (!finished) {
const errorMessage = `Timed out in mjpage when processing html: ${html}`;
captureException(new Error(errorMessage));
// eslint-disable-next-line no-console
console.error(errorMessage);
finished = true;
resolve(html);
}
}, 10000);
}
const errorHandler = (id, wrapperNode, sourceFormula, sourceFormat, errors) => {
// eslint-disable-next-line no-console
console.log("Error in Mathjax handling: ", id, wrapperNode, sourceFormula, sourceFormat, errors)
reject(`Error in $${sourceFormula}$: ${errors}`)
}
const callbackAndMarkFinished = (dom: any, css: string) => {
finished = true;
return beforeSerializationCallback(dom, css);
};
mjpage(html, { fragment: true, errorHandler, format: ["MathML", "TeX"] } , {html: true, css: true}, resolve)
.on('beforeSerialization', callbackAndMarkFinished);
})
}
// Adapted from: https://github.com/cheeriojs/cheerio/issues/748
const cheerioWrapAll = (toWrap: cheerio.Cheerio, wrapper: string, $: cheerio.Root) => {
if (toWrap.length < 1) {
return toWrap;
}
if (toWrap.length < 2 && ($ as any).wrap) { // wrap not defined in npm version,
return ($ as any).wrap(wrapper); // and git version fails testing.
}
const section = $(wrapper);
let marker = $('<div>');
marker = marker.insertBefore(toWrap.first()); // in jQuery marker would remain current
toWrap.each(function(k, v) { // in Cheerio, we update with the output.
$(v).remove();
section.append($(v));
});
section.insertBefore(marker);
marker.remove();
return section; // This is what jQuery would return, IIRC.
}
const spoilerClass = 'spoiler-v2' // this is the second iteration of a spoiler-tag that we've implemented. Changing the name for backwards-and-forwards compatibility
/// Given HTML which possibly contains elements tagged with with a spoiler class
/// (ie, hidden until mouseover), parse the HTML, and wrap consecutive elements
/// that all have a spoiler tag in a shared spoiler element (so that the
/// mouse-hover will reveal all of them together).
function wrapSpoilerTags(html: string): string {
//@ts-ignore
const $ = cheerio.load(html, null, false)
// Iterate through spoiler elements, collecting them into groups. We do this
// the hard way, because cheerio's sibling-selectors don't seem to work right.
let spoilerBlockGroups: Array<cheerio.Element[]> = [];
let currentBlockGroup: cheerio.Element[] = [];
$(`.${spoilerClass}`).each(function(this: any) {
const element = this;
if (!(element?.previousSibling && $(element.previousSibling).hasClass(spoilerClass))) {
if (currentBlockGroup.length > 0) {
spoilerBlockGroups.push(currentBlockGroup);
currentBlockGroup = [];
}
}
currentBlockGroup.push(element);
});
if (currentBlockGroup.length > 0) {
spoilerBlockGroups.push(currentBlockGroup);
}
// Having collected the elements into groups, wrap each group.
for (let spoilerBlockGroup of spoilerBlockGroups) {
cheerioWrapAll($(spoilerBlockGroup), '<div class="spoilers" />', $);
}
// Serialize back to HTML.
return $.html()
}
const trimLeadingAndTrailingWhiteSpace = (html: string): string => {
//@ts-ignore
const $ = cheerio.load(`<div id="root">${html}</div>`, null, false)
const topLevelElements = $('#root').children().get()
// Iterate once forward until we find non-empty paragraph to trim leading empty paragraphs
removeLeadingEmptyParagraphsAndBreaks(topLevelElements, $)
// Then iterate backwards to trim trailing empty paragraphs
removeLeadingEmptyParagraphsAndBreaks(topLevelElements.reverse(), $)
return $("#root").html() || ""
}
const removeLeadingEmptyParagraphsAndBreaks = (elements: cheerio.Element[], $: cheerio.Root) => {
for (const elem of elements) {
if (isEmptyParagraphOrBreak(elem)) {
$(elem).remove()
} else {
break
}
}
}
const isEmptyParagraphOrBreak = (elem: cheerio.Element) => {
if (elem.type === 'tag' && elem.name === "p") {
if (elem.children?.length === 0) return true
if (elem.children?.length === 1 && elem.children[0]?.type === "text" && elem.children[0]?.data?.trim() === "") return true
return false
}
if (elem.type === 'tag' && elem.name === "br") return true
return false
}
export async function draftJSToHtmlWithLatex(draftJS) {
const draftJSWithLatex = await preProcessLatex(draftJS)
const html = draftToHTML(convertFromRaw(draftJSWithLatex))
const trimmedHtml = trimLeadingAndTrailingWhiteSpace(html)
return wrapSpoilerTags(trimmedHtml)
}
export function htmlToMarkdown(html: string): string {
return turndownService.turndown(html)
}
export function ckEditorMarkupToMarkdown(markup: string): string {
// Sanitized CKEditor markup is just html
return turndownService.turndown(sanitize(markup))
}
export function markdownToHtmlNoLaTeX(markdown: string): string {
const id = randomId()
const renderedMarkdown = mdi.render(markdown, {docId: id})
return trimLeadingAndTrailingWhiteSpace(renderedMarkdown)
}
export async function markdownToHtml(markdown: string): Promise<string> {
const html = markdownToHtmlNoLaTeX(markdown)
return await mjPagePromise(html, trimLatexAndAddCSS)
}
export function removeCKEditorSuggestions(markup: string): string {
// First we remove all suggested deletion and modify formatting tags
const markupWithoutDeletionsAndModifications = markup.replace(
/<suggestion\s*id="[a-zA-Z0-9:]+"\s*suggestion-type="(deletion|formatInline:[a-zA-Z0-9]+|formatBlock:[a-zA-Z0-9]+)" type="(start|end)"><\/suggestion>/g,
''
)
// Then we remove everything between suggested insertions
const markupWithoutInsertions = markupWithoutDeletionsAndModifications.replace(
/<suggestion\s*id="([a-zA-Z0-9:]+)"\s*suggestion-type="insertion" type="start"><\/suggestion>.*<suggestion\s*id="\1"\s*suggestion-type="insertion"\s*type="end"><\/suggestion>/g,
''
)
return markupWithoutInsertions
}
export async function ckEditorMarkupToHtml(markup: string): Promise<string> {
// First we remove any unaccepted suggestions from the markup
const markupWithoutSuggestions = removeCKEditorSuggestions(markup)
// Sanitized CKEditor markup is just html
const html = sanitize(markupWithoutSuggestions)
const trimmedHtml = trimLeadingAndTrailingWhiteSpace(html)
// Render any LaTeX tags we might have in the HTML
return await mjPagePromise(trimmedHtml, trimLatexAndAddCSS)
}
async function dataToHTML(data, type, sanitizeData = false) {
switch (type) {
case "html":
return sanitizeData ? sanitize(data) : await mjPagePromise(data, trimLatexAndAddCSS)
case "ckEditorMarkup":
return await ckEditorMarkupToHtml(data)
case "draftJS":
return await draftJSToHtmlWithLatex(data)
case "markdown":
return await markdownToHtml(data)
default: throw new Error(`Unrecognized format: ${type}`);
}
}
export function dataToMarkdown(data, type) {
if (!data) return ""
switch (type) {
case "markdown": {
return data
}
case "html": {
return htmlToMarkdown(data)
}
case "ckEditorMarkup": {
return ckEditorMarkupToMarkdown(data)
}
case "draftJS": {
try {
const contentState = convertFromRaw(data);
const html = draftToHTML(contentState)
return htmlToMarkdown(html)
} catch(e) {
// eslint-disable-next-line no-console
console.error(e)
}
return ""
}
default: throw new Error(`Unrecognized format: ${type}`);
}
}
export async function dataToWordCount(data, type) {
try {
const markdown = dataToMarkdown(data, type) || ""
return markdown.split(" ").length
} catch(err) {
// eslint-disable-next-line no-console
console.error("Error in dataToWordCount", data, type, err)
return 0
}
}
function getInitialVersion(document: DbPost|DbObject) {
if ((document as DbPost).draft) {
return '0.1.0'
} else {
return '1.0.0'
}
}
export async function getLatestRev(documentId: string, fieldName: string): Promise<DbRevision|null> {
return await Revisions.findOne({documentId: documentId, fieldName}, {sort: {editedAt: -1}})
}
/// Given a revision, return the last revision of the same document/field prior
/// to it (null if the revision is the first).
export async function getPrecedingRev(rev: DbRevision): Promise<DbRevision|null> {
return await Revisions.findOne(
{documentId: rev.documentId, fieldName: rev.fieldName, editedAt: {$lt: rev.editedAt}},
{sort: {editedAt: -1}}
);
}
export async function getNextVersion(documentId: string, updateType = 'minor', fieldName: string, isDraft: boolean) {
const lastRevision = await getLatestRev(documentId, fieldName);
const { major, minor, patch } = extractVersionsFromSemver(lastRevision?.version || "1.0.0")
switch (updateType) {
case "patch":
return `${major}.${minor}.${patch + 1}`
case "minor":
return `${major}.${minor + 1}.0`
case "major":
return `${major+1}.0.0`
case "initial":
return isDraft ? '0.1.0' : '1.0.0'
default:
throw new Error("Invalid updateType, must be one of 'patch', 'minor' or 'major'")
}
}
function versionIsDraft(semver: string, collectionName: CollectionNameString) {
if (collectionName === "Tags")
return false;
const { major, minor, patch } = extractVersionsFromSemver(semver)
return major===0;
}
ensureIndex(Revisions, {documentId: 1, version: 1, fieldName: 1, editedAt: 1})
async function buildRevision({ originalContents, currentUser }) {
const { data, type } = originalContents;
const html = await dataToHTML(data, type, !currentUser.isAdmin)
const wordCount = await dataToWordCount(data, type)
return {
html, wordCount, originalContents,
editedAt: new Date(),
userId: currentUser._id,
};
}
// Given a revised document, check whether fieldName (a content-editor field) is
// different from the previous revision (or there is no previous revision).
const revisionIsChange = async (doc, fieldName: string): Promise<boolean> => {
const id = doc._id;
const previousVersion = await getLatestRev(id, fieldName);
if (!previousVersion)
return true;
if (!_.isEqual(doc[fieldName].originalContents, previousVersion.originalContents)) {
return true;
}
if (doc[fieldName].commitMessage && doc[fieldName].commitMessage.length>0) {
return true;
}
return false;
}
function addEditableCallbacks<T extends DbObject>({collection, options = {}}: {
collection: CollectionBase<T>,
options: MakeEditableOptions
}) {
const {
fieldName = "contents",
pingbacks = false,
} = options
const collectionName = collection.collectionName;
getCollectionHooks(collectionName).createBefore.add(
async function editorSerializationBeforeCreate (doc, { currentUser })
{
if (doc[fieldName]?.originalContents) {
if (!currentUser) { throw Error("Can't create document without current user") }
const { data, type } = doc[fieldName].originalContents
const commitMessage = doc[fieldName].commitMessage;
const html = await dataToHTML(data, type, !currentUser.isAdmin)
const wordCount = await dataToWordCount(data, type)
const version = getInitialVersion(doc)
const userId = currentUser._id
const editedAt = new Date()
const changeMetrics = htmlToChangeMetrics("", html);
const newRevision: Omit<DbRevision, "documentId" | "schemaVersion" | "_id" | "voteCount" | "baseScore" | "extendedScore" | "score" | "inactive" > = {
...(await buildRevision({
originalContents: doc[fieldName].originalContents,
currentUser,
})),
fieldName,
collectionName,
version,
draft: versionIsDraft(version, collectionName),
updateType: 'initial',
commitMessage,
changeMetrics,
};
const firstRevision = await createMutator({
collection: Revisions,
document: newRevision,
validate: false
});
return {
...doc,
[fieldName]: {
...doc[fieldName],
html, version, userId, editedAt, wordCount,
updateType: 'initial'
},
[`${fieldName}_latest`]: firstRevision.data._id,
...(pingbacks ? {
pingbacks: await htmlToPingbacks(html, null),
} : null),
}
}
return doc
});
getCollectionHooks(collectionName).updateBefore.add(
async function editorSerializationEdit (docData, { oldDocument: document, newDocument, currentUser })
{
if (docData[fieldName]?.originalContents) {
if (!currentUser) { throw Error("Can't create document without current user") }
const { data, type } = docData[fieldName].originalContents
const commitMessage = docData[fieldName].commitMessage;
const html = await dataToHTML(data, type, !currentUser.isAdmin)
const wordCount = await dataToWordCount(data, type)
const defaultUpdateType = docData[fieldName].updateType || (!document[fieldName] && 'initial') || 'minor'
const isBeingUndrafted = (document as DbPost).draft && !(newDocument as DbPost).draft
// When a document is undrafted for the first time, we ensure that this constitutes a major update
const { major } = extractVersionsFromSemver((document[fieldName] && document[fieldName].version) ? document[fieldName].version : undefined)
const updateType = (isBeingUndrafted && (major < 1)) ? 'major' : defaultUpdateType
const version = await getNextVersion(document._id, updateType, fieldName, (newDocument as DbPost).draft)
const userId = currentUser._id
const editedAt = new Date()
let newRevisionId;
if (await revisionIsChange(newDocument, fieldName)) {
const previousRev = await getLatestRev(newDocument._id, fieldName);
const changeMetrics = htmlToChangeMetrics(previousRev?.html || "", html);
const newRevision: Omit<DbRevision, '_id' | 'schemaVersion' | "voteCount" | "baseScore" | "extendedScore"| "score" | "inactive" > = {
documentId: document._id,
...await buildRevision({
originalContents: newDocument[fieldName].originalContents,
currentUser,
}),
fieldName,
collectionName,
version,
draft: versionIsDraft(version, collectionName),
updateType,
commitMessage,
changeMetrics,
}
const newRevisionDoc = await createMutator({
collection: Revisions,
document: newRevision,
validate: false
});
newRevisionId = newRevisionDoc.data._id;
} else {
newRevisionId = (await getLatestRev(newDocument._id, fieldName))!._id;
}
await afterCreateRevisionCallback.runCallbacksAsync([{ revisionID: newRevisionId }]);
return {
...docData,
[fieldName]: {
...docData[fieldName],
html, version, userId, editedAt, wordCount
},
[`${fieldName}_latest`]: newRevisionId,
...(pingbacks ? {
pingbacks: await htmlToPingbacks(html, [{
collectionName: collection.collectionName,
documentId: document._id,
}]
),
} : null),
}
}
return docData
});
getCollectionHooks(collectionName).createAfter.add(
async function editorSerializationAfterCreate(newDoc: DbRevision)
{
// Update revision to point to the document that owns it.
const revisionID = newDoc[`${fieldName}_latest`];
await Revisions.rawUpdateOne(
{ _id: revisionID },
{ $set: { documentId: newDoc._id } }
);
await afterCreateRevisionCallback.runCallbacksAsync([{ revisionID: revisionID }]);
return newDoc;
});
}
export function addAllEditableCallbacks() {
sealEditableFields();
for (let collectionName of editableCollections) {
for (let fieldName of editableCollectionsFields[collectionName]) {
const collection = getCollection(collectionName);
const options = editableCollectionsFieldOptions[collectionName][fieldName];
addEditableCallbacks({collection, options});
}
}
}
onStartup(addAllEditableCallbacks);
/// Given an HTML diff, where added sections are marked with <ins> and <del>
/// tags, count the number of chars added and removed. This is used for providing
/// a quick distinguisher between small and large changes, on revision history
/// lists.
const diffToChangeMetrics = (diffHtml: string): ChangeMetrics => {
// @ts-ignore
const parsedHtml = cheerio.load(diffHtml, null, false);
const insertedChars = countCharsInTag(parsedHtml, "ins");
const removedChars = countCharsInTag(parsedHtml, "del");
return { added: insertedChars, removed: removedChars };
}
const countCharsInTag = (parsedHtml: cheerio.Root, tagName: string): number => {
const instancesOfTag = parsedHtml(tagName);
let cumulative = 0;
for (let i=0; i<instancesOfTag.length; i++) {
const tag = instancesOfTag[i];
const text = cheerio(tag).text();
cumulative += text.length;
}
return cumulative;
}
export const htmlToChangeMetrics = (oldHtml: string, newHtml: string): ChangeMetrics => {
const htmlDiff = diff(oldHtml, newHtml);
return diffToChangeMetrics(htmlDiff);
} | the_stack |
import * as assert from 'assert';
import * as sinon from 'sinon';
import * as uuid from 'uuid';
import { QuickPickOptions } from 'vscode';
import {
IAzureConsortiumDto,
IAzureConsortiumMemberDto,
IAzureTransactionNodeDto,
MemberResource,
} from '../src/ARMBlockchain';
import { TransactionNodeResource } from '../src/ARMBlockchain/Operations/TransactionNodeResource';
import { Constants } from '../src/Constants';
import * as helpers from '../src/helpers';
import { ConsortiumItem, ResourceGroupItem, SubscriptionItem } from '../src/Models/QuickPickItems';
describe('Consortium Resource Explorer', () => {
afterEach(() => {
sinon.restore();
});
const getMemberListStub = async (): Promise<IAzureConsortiumMemberDto[]> => [];
const getTransactionNodeListStub = async (): Promise<IAzureTransactionNodeDto[]> => [];
const azureSession = {
credentials: {
signRequest(): void { return; },
},
environment: {
activeDirectoryEndpointUrl: 'string',
activeDirectoryGraphApiVersion: 'string',
activeDirectoryGraphResourceId: 'string',
activeDirectoryResourceId: 'string',
azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: 'string',
azureDataLakeStoreFileSystemEndpointSuffix: 'string',
galleryEndpointUrl: 'string',
keyVaultDnsSuffix: 'string',
managementEndpointUrl: 'string',
mentEndpointUrl: 'string',
name: 'string',
portalUrl: 'string',
publishingProfileUrl: 'string',
resourceManagerEndpointUrl: 'string',
sqlManagementEndpointUrl: '',
sqlServerHostnameSuffix: 'string',
storageEndpointSuffix: 'string',
validateAuthority: true,
},
tenantId: 'string',
userId: 'string',
};
const subscriptionItem = new SubscriptionItem('', uuid.v4(), azureSession);
const resourceGroupItem = new ResourceGroupItem();
const consortiumItem = new ConsortiumItem('', '', '', '', '');
const showQuickPickStub = sinon.stub();
showQuickPickStub
.onCall(0)
.returns(subscriptionItem);
showQuickPickStub
.onCall(1)
.returns(resourceGroupItem as ResourceGroupItem);
showQuickPickStub
.onCall(2)
.returns(consortiumItem as ConsortiumItem);
it('selectProject all method should be executed', async () => {
// Arrange
const subItemTest = {
subscriptionId: uuid.v4(),
} as SubscriptionItem;
const rgItemTest = {
label: uuid.v4(),
} as ResourceGroupItem;
sinon.stub(MemberResource.prototype, 'getMemberList').returns(getMemberListStub());
sinon.stub(TransactionNodeResource.prototype, 'getTransactionNodeList').returns(getTransactionNodeListStub());
sinon.replace(helpers, 'showQuickPick', showQuickPickStub);
const consortiumResourceExplorerRequire = require('../src/resourceExplorers/ConsortiumResourceExplorer');
const consortiumResourceExplorer = consortiumResourceExplorerRequire.ConsortiumResourceExplorer;
sinon.stub(consortiumResourceExplorer.prototype, 'getConsortiumItems').returns(getConsortiaList());
sinon.stub(consortiumResourceExplorer.prototype, 'waitForLogin').returns(Promise.resolve(true));
sinon.stub(consortiumResourceExplorer.prototype, 'getSubscriptionItems')
.returns(Promise.resolve(subItemTest));
sinon.stub(consortiumResourceExplorer.prototype, 'getResourceGroupItems')
.returns(Promise.resolve(rgItemTest));
sinon.stub(consortiumResourceExplorer.prototype, 'createAzureConsortium');
sinon.stub(consortiumResourceExplorer.prototype, 'getAzureConsortium');
// Act
await consortiumResourceExplorer.prototype.selectProject();
// Assert
assert.strictEqual(
(showQuickPickStub.getCall(0).args[1] as QuickPickOptions).placeHolder,
Constants.placeholders.selectSubscription,
'showQuickPick should called with correct arguments',
);
assert.strictEqual(
(showQuickPickStub.getCall(1).args[1] as QuickPickOptions).placeHolder,
Constants.placeholders.selectResourceGroup,
'showQuickPick should called with correct arguments',
);
});
it('loadConsortiumItems returns unselected consortia', async () => {
// Arrange
const excludedItemsTest = [consortiumNameList.consortium1];
const consortiaList = getConsortiaList();
const expectedNumberOfConsortia = (await consortiaList)
.filter((consortium) => !excludedItemsTest.includes(consortium.consortium))
.length;
const consortiumResourceExplorerRequire = require('../src/resourceExplorers/ConsortiumResourceExplorer');
const consortiumResourceExplorer = consortiumResourceExplorerRequire.ConsortiumResourceExplorer;
sinon.stub(consortiumResourceExplorer.prototype, 'getAzureClient')
.returns({ consortiumResource: { getConsortiaList: () => consortiaList }});
const azureClientMock = consortiumResourceExplorer.prototype.getAzureClient();
// Act
const result
= await consortiumResourceExplorer.prototype.loadConsortiumItems(azureClientMock, excludedItemsTest);
// Assert
assert.strictEqual(
result.length,
expectedNumberOfConsortia,
`loadConsortiumItems should return only ${expectedNumberOfConsortia} consortia.`);
assert.strictEqual(
result.find((con: ConsortiumItem) => con.consortiumName === excludedItemsTest[0]),
undefined,
'loadConsortiumItems should not return selected consortium.');
});
it('loadMemberItems returns members which has status "Ready"', async () => {
// Arrange
const consortiumResourceExplorerRequire = require('../src/resourceExplorers/ConsortiumResourceExplorer');
const consortiumResourceExplorer = consortiumResourceExplorerRequire.ConsortiumResourceExplorer;
sinon.stub(consortiumResourceExplorer.prototype, 'getAzureClient')
.returns({ memberResource: { getMemberList: async () => await getMemberList() }});
const azureClientMock = consortiumResourceExplorer.prototype.getAzureClient();
// Act
const result = await consortiumResourceExplorer.prototype.loadMemberItems(azureClientMock, 'consortiumName');
// Assert
assert.strictEqual(
result.length,
result.filter((mem: IAzureConsortiumMemberDto) => mem.status === Constants.consortiumMemberStatuses.ready).length,
`loadMemberItems should return members which has status '${Constants.consortiumMemberStatuses.ready}'.`);
});
it('loadTransactionNodeItems returns transaction nodes for member', async () => {
// Arrange
const expectedTransactionNode = await getTransactionNodeList();
const consortiumResourceExplorerRequire = require('../src/resourceExplorers/ConsortiumResourceExplorer');
const consortiumResourceExplorer = consortiumResourceExplorerRequire.ConsortiumResourceExplorer;
sinon.stub(consortiumResourceExplorer.prototype, 'getAzureClient')
.returns({ transactionNodeResource: { getTransactionNodeList: async () => await getTransactionNodeList() }});
const azureClientMock = consortiumResourceExplorer.prototype.getAzureClient();
// Act
const result = await consortiumResourceExplorer.prototype.loadTransactionNodeItems(azureClientMock, uuid.v4());
// Assert
// We should remember about default transaction node, because of it we use + 1
assert.strictEqual(
result.length,
expectedTransactionNode.length + 1,
'loadTransactionNodeItems should return transaction node and default one.');
});
it('loadTransactionNodeItems returns empty array', async () => {
// Arrange
const consortiumResourceExplorerRequire = require('../src/resourceExplorers/ConsortiumResourceExplorer');
const consortiumResourceExplorer = consortiumResourceExplorerRequire.ConsortiumResourceExplorer;
sinon.stub(consortiumResourceExplorer.prototype, 'getAzureClient')
.returns({ transactionNodeResource: { getTransactionNodeList: () => { throw Error(); }}});
const azureClientMock = consortiumResourceExplorer.prototype.getAzureClient();
// Act
const result = await consortiumResourceExplorer.prototype.loadTransactionNodeItems(azureClientMock, uuid.v4());
// Assert
assert.strictEqual(result.length, 0, 'loadTransactionNodeItems should return empty array.');
});
it('getAzureConsortium returns consortium with member which has transaction nodes', async () => {
// Arrange
const subItemTest = {
subscriptionId: uuid.v4(),
} as SubscriptionItem;
const rgItemTest = {
label: uuid.v4(),
} as ResourceGroupItem;
const azureClient = {
memberResource: { getMemberList: async () => await getMemberList() },
transactionNodeResource: { getTransactionNodeList: async () => await getTransactionNodeList() },
};
const consortiumResourceExplorerRequire = require('../src/resourceExplorers/ConsortiumResourceExplorer');
const consortiumResourceExplorer = consortiumResourceExplorerRequire.ConsortiumResourceExplorer;
sinon.stub(consortiumResourceExplorer.prototype, 'getAzureClient').returns(azureClient);
const expectedNumberOfMembers = (await getMemberList())
.filter((mem: IAzureConsortiumMemberDto) => mem.status === Constants.consortiumMemberStatuses.ready).length;
// We should remember about default transaction node, because of it we use + 1
const expectedNumberOfTransactionNodes = (await getTransactionNodeList()).length + 1;
// Act
const result
= await consortiumResourceExplorer.prototype.getAzureConsortium(azureClient, subItemTest, rgItemTest);
// Assert
const members = result.getChildren();
const transactionNodes = members[0].getChildren();
assert.strictEqual(members.length, expectedNumberOfMembers, `Consortium should have ${expectedNumberOfMembers} members.`);
assert.strictEqual(transactionNodes.length, expectedNumberOfTransactionNodes, `Member should have ${expectedNumberOfTransactionNodes} transaction nodes.`);
});
const consortiumNameList = {
consortium1: 'consortium1',
consortium2: 'consortium2',
consortium3: 'consortium3',
};
async function getConsortiaList(): Promise<IAzureConsortiumDto[]> {
return [{
consortium: consortiumNameList.consortium1,
consortiumManagementAccountAddress: uuid.v4(),
consortiumManagementAccountPassword: uuid.v4(),
dns: uuid.v4(),
location: uuid.v4(),
password: uuid.v4(),
protocol: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
rootContractAddress: uuid.v4(),
userName: uuid.v4(),
validatorNodesSku: {
capacity: 0,
},
},
{
consortium: consortiumNameList.consortium2,
consortiumManagementAccountAddress: uuid.v4(),
consortiumManagementAccountPassword: uuid.v4(),
dns: uuid.v4(),
location: uuid.v4(),
password: uuid.v4(),
protocol: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
rootContractAddress: uuid.v4(),
userName: uuid.v4(),
validatorNodesSku: {
capacity: 0,
},
},
{
consortium: consortiumNameList.consortium3,
consortiumManagementAccountAddress: uuid.v4(),
consortiumManagementAccountPassword: uuid.v4(),
dns: uuid.v4(),
location: uuid.v4(),
password: uuid.v4(),
protocol: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
rootContractAddress: uuid.v4(),
userName: uuid.v4(),
validatorNodesSku: {
capacity: 0,
},
}];
}
async function getMemberList(): Promise<IAzureConsortiumMemberDto[]> {
return [{
dateModified: uuid.v4(),
displayName: uuid.v4(),
joinDate: uuid.v4(),
name: uuid.v4(),
role: uuid.v4(),
status: Constants.consortiumMemberStatuses.ready,
subscriptionId: uuid.v4(),
},
{
dateModified: uuid.v4(),
displayName: uuid.v4(),
joinDate: uuid.v4(),
name: uuid.v4(),
role: uuid.v4(),
status: uuid.v4(),
subscriptionId: uuid.v4(),
}];
}
async function getTransactionNodeList(): Promise<IAzureTransactionNodeDto[]> {
return [{
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
dns: uuid.v4(),
password: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
userName: uuid.v4(),
},
type: uuid.v4(),
},
{
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
dns: uuid.v4(),
password: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
userName: uuid.v4(),
},
type: uuid.v4(),
}];
}
}); | the_stack |
import uuid from './uuid';
import uniq from 'uniq';
type RelDB = ReturnType<typeof createRel>;
function createError(str) {
let err:any = new Error(str);
err.status = 400;
return err;
}
const MAX_INT_LENGTH = 16; // max int in JS is 9007199254740992
const TYPE_UNDEF = '0';
const TYPE_NUM = '1';
const TYPE_STRING = '2';
const TYPE_OBJ = '3';
function serialize(type, id = undefined) {
// simple collation that goes like this:
// undefined < numbers < strings < object
let res = type.replace('_', '') + '_';
if (typeof id === 'number') {
// zpad
id = id.toString();
while (id.length < MAX_INT_LENGTH) {
id = '0' + id;
}
res += TYPE_NUM + '_' + id;
} else if (typeof id === 'undefined') {
// need lowest possible value
res += TYPE_UNDEF;
} else if (typeof id === 'object') {
// need highest possible value
res += TYPE_OBJ;
} else { // string
res += TYPE_STRING + '_' + id;
}
return res;
}
function deserialize(str) {
// should only have to deserialize numbers and strings
let idx = str.indexOf('_');
let collationType = str.charAt(idx + 1);
let id = str.substring(idx + 3);
if (collationType === TYPE_NUM) {
return parseInt(id, 10);
}
return id;
}
function setSchema<T extends {} = {}>(this: PouchDB.Database<T>, schema) {
let db = this as PouchDB.RelDatabase<T>;// & {rel:any}
let keysToSchemas = new Map();
schema.forEach(function (type) {
keysToSchemas.set(type.singular, type);
keysToSchemas.set(type.plural, type);
});
// set default documentType
schema.forEach(function (type) {
type.documentType = type.documentType || type.singular;
});
// validate the relations
schema.forEach(function (type) {
if (type.relations) {
if (!Object.keys(type.relations).length) {
throw new Error('Invalid relations for: ' + type);
}
Object.keys(type.relations).forEach(function (field) {
let relationDef = type.relations[field];
if (Object.keys(relationDef).length !== 1) {
throw new Error('Invalid relationship definition for: ' + field);
}
let relationType = Object.keys(relationDef)[0];
let relatedField = relationDef[relationType];
if (typeof relatedField !== 'string') {
relatedField = relatedField.type;
}
if (!keysToSchemas.get(relatedField)) {
throw new Error('Unknown entity type: ' + relatedField);
}
if (relationType !== 'belongsTo' && relationType !== 'hasMany') {
throw new Error('Invalid relationship type for ' + field + ': ' + relationType);
}
});
}
});
db.rel = createRel(db as PouchDB.Database<T>, keysToSchemas, schema);
return db;
}
function createRel(db:PouchDB.Database, keysToSchemas:any, schema:any) {
/**
* Transform a relational object into a PouchDB doc.
*/
function toRawDoc(typeInfo, obj) {
obj = Object.assign({}, obj);
let doc:any = {};
if (obj.rev) {
doc._rev = obj.rev;
delete obj.rev;
}
if (obj.attachments) {
doc._attachments = obj.attachments;
delete obj.attachments;
}
let id = obj.id || uuid();
delete obj.id;
doc._id = serialize(typeInfo.documentType, id);
if (typeInfo.relations) {
Object.keys(typeInfo.relations).forEach(function (field) {
let relationDef = typeInfo.relations[field];
let relationType = Object.keys(relationDef)[0];
if (relationType === 'belongsTo') {
if (obj[field] && typeof obj[field].id !== 'undefined') {
obj[field] = obj[field].id;
}
} else { // hasMany
let relatedType = relationDef[relationType];
if (relatedType.options && relatedType.options.queryInverse) {
delete obj[field];
return;
}
if (obj[field]) {
let dependents = obj[field].map(function (dependent) {
if (dependent && typeof dependent.id !== 'undefined') {
return dependent.id;
}
return dependent;
});
obj[field] = dependents;
} else {
obj[field] = [];
}
}
});
}
doc.data = obj;
return doc;
}
/**
* Transform a PouchDB doc into a relational object.
*/
function fromRawDoc(pouchDoc) {
let obj = pouchDoc.data;
obj.id = deserialize(pouchDoc._id);
obj.rev = pouchDoc._rev;
if (pouchDoc._attachments) {
obj.attachments = pouchDoc._attachments;
}
return obj;
}
function getTypeInfo(type) {
if (!keysToSchemas.has(type)) {
throw createError('unknown type: ' + JSON.stringify(type));
}
return keysToSchemas.get(type);
}
async function _save(type, obj) {
let typeInfo = getTypeInfo(type);
let pouchDoc = toRawDoc(typeInfo, obj);
let pouchRes = await db.put(pouchDoc);
let res = {
id: deserialize(pouchRes.id),
rev: pouchRes.rev
};
return res;
}
async function _del(type, obj) {
let typeInfo = getTypeInfo(type);
let pouchDoc = toRawDoc(typeInfo, obj);
//TODO: only map id + rev, not relationships or extra option to only set _deleted to support filtered replication
pouchDoc = {
_id : pouchDoc._id,
_rev : pouchDoc._rev,
_deleted: true
};
await db.put(pouchDoc);
return {deleted: true};
}
async function _find(type, idOrIds, foundObjects) {
let typeInfo = getTypeInfo(type);
let opts:any = {
include_docs: true
};
if (typeof idOrIds === 'undefined' || idOrIds === null) {
// find everything
opts.startkey = serialize(typeInfo.documentType);
opts.endkey = serialize(typeInfo.documentType, {});
} else if (Array.isArray(idOrIds)) {
// find multiple by ids
opts.keys = idOrIds.map(function (id) {
return serialize(typeInfo.documentType, id);
});
} else if (typeof idOrIds === 'object') {
if (typeof idOrIds.startkey === 'undefined' || idOrIds.startkey === null) {
opts.startkey = serialize(typeInfo.documentType);
} else {
opts.startkey = serialize(typeInfo.documentType, idOrIds.startkey);
}
if (typeof idOrIds.endkey === 'undefined' || idOrIds.endkey === null) {
opts.endkey = serialize(typeInfo.documentType, {});
} else {
opts.endkey = serialize(typeInfo.documentType, idOrIds.endkey);
}
if (typeof idOrIds.limit !== 'undefined' && idOrIds.limit !== null) {
opts.limit = idOrIds.limit;
}
if (typeof idOrIds.skip !== 'undefined' && idOrIds.skip !== null) {
opts.skip = idOrIds.skip;
}
} else {
// find by single id
opts.key = serialize(typeInfo.documentType, idOrIds);
}
let allDocs = await db.allDocs(opts);
return _parseAlldocs(type, foundObjects, allDocs);
}
//true = deleted, false = exists, null = not in database
async function isDeleted(type, id) {
let typeInfo = getTypeInfo(type);
try {
let doc = await db.get(serialize(typeInfo.documentType, id));
return false;
}
catch (err) {
return err.reason === "deleted" ? true : null;
}
}
function _parseAlldocs(type, foundObjects, pouchRes) {
return _parseRelDocs(type, foundObjects, pouchRes.rows.filter(function (row) {
return row.doc && !row.value.deleted;
}).map(function (row) {
return row.doc;
}));
}
function parseRelDocs(type, pouchDocs) {
return _parseRelDocs(type, new Map(), pouchDocs);
}
async function _parseRelDocs(type, foundObjects, pouchDocs) {
let typeInfo = getTypeInfo(type);
if (!foundObjects.has(type)) {
foundObjects.set(type, new Map());
}
let listsOfFetchTasks = [];
for (let doc of pouchDocs) {
let obj = fromRawDoc(doc);
foundObjects.get(type).set(JSON.stringify(obj.id), obj);
// fetch all relations
for (let field of Object.keys(typeInfo.relations || {})) {
let relationDef = typeInfo.relations[field];
let relationType = Object.keys(relationDef)[0];
let relatedType = relationDef[relationType];
let relationOptions: any = {};
if (typeof relatedType !== 'string') {
relationOptions = relatedType.options || {};
if (relationOptions.async) {
continue;
}
if (relationOptions.queryInverse) {
delete obj[field];
}
relatedType = relatedType.type;
}
if (relationType === 'belongsTo') {
let relatedId = obj[field];
if (typeof relatedId !== 'undefined') {
listsOfFetchTasks.push({
relatedType: relatedType,
relatedIds: [relatedId]
});
}
} else { // hasMany
if (relationOptions.queryInverse) {
//TODO: postpone this until next run, to filter out more objects that are already loaded
await _findHasMany(relatedType, relationOptions.queryInverse,
obj.id, foundObjects);
continue;
}
/* istanbul ignore next */
let relatedIds = (obj[field] || []).filter(function (relatedId) {
return typeof relatedId !== 'undefined';
});
if (relatedIds.length) {
listsOfFetchTasks.push({
relatedType: relatedType,
relatedIds: relatedIds
});
}
}
}
//listsOfFetchTasks = listsOfFetchTasks.concat(docRelations);
}
// fetch in as few http requests as possible
let typesToIds = {};
listsOfFetchTasks.forEach(function (fetchTask) {
/* istanbul ignore next */
if (!fetchTask) {
return;
}
let relatedType = fetchTask.relatedType;
let relatedIds = fetchTask.relatedIds;
for (let i = relatedIds.length - 1; i >= 0; i--) {
let relatedId = relatedIds[i];
if (foundObjects.has(relatedType) &&
foundObjects.get(relatedType).has(JSON.stringify(relatedId))) {
delete relatedIds[i];
continue;
}
}
typesToIds[relatedType] =
(typesToIds[relatedType] || []).concat(fetchTask.relatedIds.filter(Boolean));
});
for (let relatedType of Object.keys(typesToIds)) {
let relatedIds = uniq(typesToIds[relatedType]);
if (relatedIds.length > 0)
await _find(relatedType, relatedIds, foundObjects);
}
let res:any = {};
foundObjects.forEach(function (found, type) {
let typeInfo = getTypeInfo(type);
let list = res[typeInfo.plural] = [];
found.forEach(function (obj) {
list.push(obj);
});
//list.sort(lexCompare);
});
return res;
}
async function putAttachment(type, obj, attachmentId, attachment, attachmentType) {
let dbDocId = serialize(type, obj.id);
let typeInfo = getTypeInfo(type);
let pouchRes = await db.putAttachment(dbDocId, attachmentId, obj.rev, attachment, attachmentType);
let res = pouchRes.rev;
return res;
}
async function removeAttachment(type, obj, attachmentId) {
let dbDocId = serialize(type, obj.id);
let typeInfo = getTypeInfo(type);
let pouchRes = await db.removeAttachment(dbDocId, attachmentId, obj.rev);
let res = pouchRes.rev;
return res;
}
async function getAttachment(type, id, attachmentId, options = undefined) {
options = options || {};
return db.getAttachment(serialize(type, id), attachmentId, options);
}
async function save(type, obj) {
return _save(type, obj);
}
function find(type, idOrIds = undefined) {
return _find(getTypeInfo(type).singular, idOrIds, new Map());
}
async function _findHasMany(type, belongsToKey, belongsToId, foundObjects) {
let selector = {
'_id': {
'$gt': makeDocID({type: type}),
'$lt': makeDocID({type: type, id: {}}),
},
};
selector['data.' + belongsToKey] = belongsToId;
//only use opts for return ids or whole doc? returning normal documents is not really good
let findRes = await db.find({ selector: selector });
return _parseRelDocs(type, foundObjects, findRes.docs);
}
function findHasMany(type, belongsToKey, belongsToId) {
return _findHasMany(type, belongsToKey, belongsToId, new Map());
}
function del(type, obj) {
return _del(type, obj);
}
function parseDocID(str) {
let idx = str.indexOf('_');
let type = str.substring(0, idx);
let relId = deserialize(str);
let defaultType = keysToSchemas.get(type);
if (!defaultType) {
let matchingSchemaTypes = schema.filter(
function (schemaType) { return schemaType.documentType === type; });
if (matchingSchemaTypes.length > 0) {
type = matchingSchemaTypes[0].singular;
}
}
return {
type: type,
id: relId
};
}
function makeDocID(obj) {
let type = obj.type;
let typeInfo = keysToSchemas.get(type);
if (typeInfo) {
type = typeInfo.documentType;
}
return serialize(type, obj.id);
}
return {
save: save,
find: find,
findHasMany: findHasMany,
del: del,
getAttachment: getAttachment,
putAttachment: putAttachment,
removeAttachment: removeAttachment,
parseDocID: parseDocID,
makeDocID: makeDocID,
parseRelDocs: parseRelDocs,
isDeleted: isDeleted,
uuid: uuid,
};
}
export default {setSchema};
declare global {
namespace PouchDB {
interface Static {
//TODO: return PluggedInStatic<T>, which overwrites new and default to return extended Database interface
// so we don't just extend the namespace, but instead really change the result of .plugin
plugin<T extends {}>(plugin: T): Static;
//plugin(plugin: function(Static)): Static;
}
interface Database<Content extends {} = {}> {
setSchema<T extends {} = Content>(schema: any): RelDatabase<T>;
}
interface RelDatabase <Content extends {} = {}> extends Database<Content> {
rel: RelDB;
}
}
} | the_stack |
module android.widget {
import Log = android.util.Log;
import LayoutInflater = android.view.LayoutInflater;
import View = android.view.View;
import ViewGroup = android.view.ViewGroup;
import ArrayList = java.util.ArrayList;
import Arrays = java.util.Arrays;
import Collections = java.util.Collections;
import Comparator = java.util.Comparator;
import List = java.util.List;
import Adapter = android.widget.Adapter;
import BaseAdapter = android.widget.BaseAdapter;
import ImageView = android.widget.ImageView;
import ListView = android.widget.ListView;
import TextView = android.widget.TextView;
import Context = android.content.Context;
/**
* A concrete BaseAdapter that is backed by an array of arbitrary
* objects. By default this class expects that the provided resource id references
* a single TextView. If you want to use a more complex layout, use the constructors that
* also takes a field id. That field id should reference a TextView in the larger layout
* resource.
*
* <p>However the TextView is referenced, it will be filled with the toString() of each object in
* the array. You can add lists or arrays of custom objects. Override the toString() method
* of your objects to determine what text will be displayed for the item in the list.
*
* <p>To use something other than TextViews for the array display, for instance, ImageViews,
* or to have some of data besides toString() results fill the views,
* override {@link #getView(int, View, ViewGroup)} to return the type of view you want.
*/
export class ArrayAdapter<T> extends BaseAdapter {
/**
* Contains the list of objects that represent the data of this ArrayAdapter.
* The content of this list is referred to as "the array" in the documentation.
*/
private mObjects:List<T>;
///**
// * Lock used to modify the content of {@link #mObjects}. Any write operation
// * performed on the array should be synchronized on this lock. This lock is also
// * used by the filter (see {@link #getFilter()} to make a synchronized copy of
// * the original array of data.
// */
//private mLock:any = new any();
/**
* The resource indicating what views to inflate to display the content of this
* array adapter.
*/
private mResource:string;
/**
* The resource indicating what views to inflate to display the content of this
* array adapter in a drop down widget.
*/
private mDropDownResource:string;
/**
* If the inflated resource is not a TextView, {@link #mFieldId} is used to find
* a TextView inside the inflated views hierarchy. This field must contain the
* identifier that matches the one defined in the resource file.
*/
private mFieldId:string;
/**
* Indicates whether or not {@link #notifyDataSetChanged()} must be called whenever
* {@link #mObjects} is modified.
*/
private mNotifyOnChange:boolean = true;
private mContext:Context;
//// A copy of the original mObjects array, initialized from and then used instead as soon as
//// the mFilter ArrayFilter is used. mObjects will then only contain the filtered values.
//private mOriginalValues:ArrayList<T>;
//
//private mFilter:ArrayAdapter.ArrayFilter;
private mInflater:LayoutInflater;
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
*/
constructor(context: Context, resource: string);
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a layout to use when
* instantiating views.
* @param textViewResourceId The id of the TextView within the layout resource to be populated
*/
constructor(context: Context, resource: string, textViewResourceId: string);
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
* @param objects The objects to represent in the ListView.
*/
constructor(context: Context, resource: string, objects: T[]);
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a layout to use when
* instantiating views.
* @param textViewResourceId The id of the TextView within the layout resource to be populated
* @param objects The objects to represent in the ListView.
*/
constructor(context: Context, resource: string, textViewResourceId: string, objects: T[]|List<T>);
constructor(...args) {
super();
if (args.length === 2) {
this.init(args[0], args[1], null, new ArrayList<T>());
} else if (args.length === 3) {
if (args[2] instanceof Array) {
this.init(args[0], args[1], null, <List<T>>Arrays.asList(args[2]));
} else {
this.init(args[0], args[1], args[2], new ArrayList<T>());
}
} else if (args.length === 4) {
this.init(args[0], args[1], args[2], args[3]);
}
}
/**
* Adds the specified object at the end of the array.
*
* @param object The object to add at the end of the array.
*/
add(object:T):void {
{
//if (this.mOriginalValues != null) {
// this.mOriginalValues.add(object);
//} else {
this.mObjects.add(object);
//}
}
if (this.mNotifyOnChange)
this.notifyDataSetChanged();
}
/**
* Adds the specified Collection at the end of the array.
*
* @param collection The Collection to add at the end of the array.
*/
addAll(collection:List<T>):void {
{
//if (this.mOriginalValues != null) {
// this.mOriginalValues.addAll(collection);
//} else {
this.mObjects.addAll(collection);
//}
}
if (this.mNotifyOnChange)
this.notifyDataSetChanged();
}
///**
// * Adds the specified items at the end of the array.
// *
// * @param items The items to add at the end of the array.
// */
//addAll(...items:T):void {
// {
// if (this.mOriginalValues != null) {
// Collections.addAll(this.mOriginalValues, items);
// } else {
// Collections.addAll(this.mObjects, items);
// }
// }
// if (this.mNotifyOnChange)
// this.notifyDataSetChanged();
//}
/**
* Inserts the specified object at the specified index in the array.
*
* @param object The object to insert into the array.
* @param index The index at which the object must be inserted.
*/
insert(object:T, index:number):void {
{
//if (this.mOriginalValues != null) {
// this.mOriginalValues.add(index, object);
//} else {
this.mObjects.add(index, object);
//}
}
if (this.mNotifyOnChange)
this.notifyDataSetChanged();
}
/**
* Removes the specified object from the array.
*
* @param object The object to remove.
*/
remove(object:T):void {
{
//if (this.mOriginalValues != null) {
// this.mOriginalValues.remove(object);
//} else {
this.mObjects.remove(object);
//}
}
if (this.mNotifyOnChange)
this.notifyDataSetChanged();
}
/**
* Remove all elements from the list.
*/
clear():void {
{
//if (this.mOriginalValues != null) {
// this.mOriginalValues.clear();
//} else {
this.mObjects.clear();
//}
}
if (this.mNotifyOnChange)
this.notifyDataSetChanged();
}
/**
* Sorts the content of this adapter using the specified comparator.
*
* @param comparator The comparator used to sort the objects contained
* in this adapter.
*/
sort(comparator:Comparator<T>):void {
{
//if (this.mOriginalValues != null) {
// Collections.sort(this.mOriginalValues, comparator);
//} else {
Collections.sort(this.mObjects, comparator);
//}
}
if (this.mNotifyOnChange)
this.notifyDataSetChanged();
}
/**
* {@inheritDoc}
*/
notifyDataSetChanged():void {
super.notifyDataSetChanged();
this.mNotifyOnChange = true;
}
/**
* Control whether methods that change the list ({@link #add},
* {@link #insert}, {@link #remove}, {@link #clear}) automatically call
* {@link #notifyDataSetChanged}. If set to false, caller must
* manually call notifyDataSetChanged() to have the changes
* reflected in the attached view.
*
* The default is true, and calling notifyDataSetChanged()
* resets the flag to true.
*
* @param notifyOnChange if true, modifications to the list will
* automatically call {@link
* #notifyDataSetChanged}
*/
setNotifyOnChange(notifyOnChange:boolean):void {
this.mNotifyOnChange = notifyOnChange;
}
private init(context:Context, resource:string, textViewResourceId:string, objects:T[]|List<T>):void {
this.mContext = context;
this.mInflater = context.getLayoutInflater();
this.mResource = this.mDropDownResource = resource;
if(objects instanceof Array) objects = Arrays.asList(<T[]>objects);
this.mObjects = <List<T>>objects;
this.mFieldId = textViewResourceId;
}
/**
* Returns the context associated with this array adapter. The context is used
* to create views from the resource passed to the constructor.
*
* @return The Context associated with this adapter.
*/
getContext():Context {
return this.mContext;
}
/**
* {@inheritDoc}
*/
getCount():number {
return this.mObjects.size();
}
/**
* {@inheritDoc}
*/
getItem(position:number):T {
return this.mObjects.get(position);
}
/**
* Returns the position of the specified item in the array.
*
* @param item The item to retrieve the position of.
*
* @return The position of the specified item.
*/
getPosition(item:T):number {
return this.mObjects.indexOf(item);
}
/**
* {@inheritDoc}
*/
getItemId(position:number):number {
return position;
}
/**
* {@inheritDoc}
*/
getView(position:number, convertView:View, parent:ViewGroup):View {
return this.createViewFromResource(position, convertView, parent, this.mResource);
}
private createViewFromResource(position:number, convertView:View, parent:ViewGroup, resource:string):View {
let view:View;
let text:TextView;
if (convertView == null) {
view = this.mInflater.inflate(this.mContext.getResources().getLayout(resource), parent, false);
} else {
view = convertView;
}
try {
if (this.mFieldId == null) {
// If no custom field is assigned, assume the whole resource is a TextView
text = <TextView> view;
} else {
// Otherwise, find the TextView field within the layout
text = <TextView> view.findViewById(this.mFieldId);
}
} catch (e){
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw Error(`new IllegalStateException("ArrayAdapter requires the resource ID to be a TextView", e)`);
}
let item:T = this.getItem(position);
if (typeof item === 'string') {
text.setText(<string><any>item);
} else {
text.setText(item.toString());
}
return view;
}
/**
* <p>Sets the layout resource to create the drop down views.</p>
*
* @param resource the layout resource defining the drop down views
* @see #getDropDownView(int, android.view.View, android.view.ViewGroup)
*/
setDropDownViewResource(resource:string):void {
this.mDropDownResource = resource;
}
/**
* {@inheritDoc}
*/
getDropDownView(position:number, convertView:View, parent:ViewGroup):View {
return this.createViewFromResource(position, convertView, parent, this.mDropDownResource);
}
///**
// * Creates a new ArrayAdapter from external resources. The content of the array is
// * obtained through {@link android.content.res.Resources#getTextArray(int)}.
// *
// * @param context The application's environment.
// * @param textArrayResId The identifier of the array to use as the data source.
// * @param textViewResId The identifier of the layout used to create views.
// *
// * @return An ArrayAdapter<CharSequence>.
// */
//static createFromResource(context:Context, textArrayResId:number, textViewResId:number):ArrayAdapter<string> {
// let strings:string[] = context.getResources().getTextArray(textArrayResId);
// return new ArrayAdapter<string>(context, textViewResId, strings);
//}
///**
// * {@inheritDoc}
// */
//getFilter():Filter {
// if (this.mFilter == null) {
// this.mFilter = new ArrayAdapter.ArrayFilter(this);
// }
// return this.mFilter;
//}
}
export module ArrayAdapter{
///**
// * <p>An array filter constrains the content of the array adapter with
// * a prefix. Each item that does not start with the supplied prefix
// * is removed from the list.</p>
// */
//export class ArrayFilter extends Filter {
// _ArrayAdapter_this:ArrayAdapter;
// constructor(arg:ArrayAdapter){
// super();
// this._ArrayAdapter_this = arg;
// }
//
// protected performFiltering(prefix:string):Filter.FilterResults {
// let results:Filter.FilterResults = new Filter.FilterResults();
// if (this._ArrayAdapter_this.mOriginalValues == null) {
// {
// this._ArrayAdapter_this.mOriginalValues = new ArrayList<T>(this._ArrayAdapter_this.mObjects);
// }
// }
// if (prefix == null || prefix.length() == 0) {
// let list:ArrayList<T>;
// {
// list = new ArrayList<T>(this._ArrayAdapter_this.mOriginalValues);
// }
// results.values = list;
// results.count = list.size();
// } else {
// let prefixString:string = prefix.toString().toLowerCase();
// let values:ArrayList<T>;
// {
// values = new ArrayList<T>(this._ArrayAdapter_this.mOriginalValues);
// }
// const count:number = values.size();
// const newValues:ArrayList<T> = new ArrayList<T>();
// for (let i:number = 0; i < count; i++) {
// const value:T = values.get(i);
// const valueText:string = value.toString().toLowerCase();
// // First match against the whole, non-splitted value
// if (valueText.startsWith(prefixString)) {
// newValues.add(value);
// } else {
// const words:string[] = valueText.split(" ");
// const wordCount:number = words.length;
// // Start at index 0, in case valueText starts with space(s)
// for (let k:number = 0; k < wordCount; k++) {
// if (words[k].startsWith(prefixString)) {
// newValues.add(value);
// break;
// }
// }
// }
// }
// results.values = newValues;
// results.count = newValues.size();
// }
// return results;
// }
//
// protected publishResults(constraint:string, results:Filter.FilterResults):void {
// //noinspection unchecked
// this._ArrayAdapter_this.mObjects = <List<T>> results.values;
// if (results.count > 0) {
// this._ArrayAdapter_this.notifyDataSetChanged();
// } else {
// this._ArrayAdapter_this.notifyDataSetInvalidated();
// }
// }
//}
}
} | the_stack |
import * as React from 'react';
import {
Interactive,
createInteractive,
InteractiveStateChange,
} from 'react-interactive';
import { primaryInput } from 'detect-it';
import * as RadixCheckbox from '@radix-ui/react-checkbox';
import * as RadixLabel from '@radix-ui/react-label';
import { CheckIcon } from '@radix-ui/react-icons';
import { DemoContainer, DemoHeading } from '../ui/DemoContainer';
import { styled } from '../stitches.config';
const TextInput = styled(Interactive.Input, {
display: 'block',
width: '100%',
margin: '8px 0',
backgroundColor: '$formElementsBackground',
border: '1px solid $colors$highContrast',
borderRadius: '4px',
padding: '4px 6px',
'&.hover, &.mouseActive': {
borderColor: '$green',
},
'&.touchActive': {
borderColor: '$blue',
boxShadow: '0 0 0 1px $colors$blue',
},
'&.focusFromTouch': {
borderColor: '$blue',
boxShadow: '0 0 0 1px $colors$blue',
},
'&.focusFromMouse': {
borderColor: '$green',
boxShadow: '0 0 0 1px $colors$green',
},
'&.focusFromKey': {
borderColor: '$purple',
boxShadow: '0 0 0 1px $colors$purple, 2px 3px 4px 0px rgba(0, 0, 0, 0.38)',
},
'&.disabled': {
opacity: 0.5,
},
});
const CheckboxLabel = styled(createInteractive(RadixLabel.Root), {
cursor: 'pointer',
margin: '6px 1px',
display: 'inline-flex',
alignItems: 'center',
// line-height needs to be the same as (or less than) the height of the checkbox
// for the check mark to center vertically inside the checkbox
lineHeight: '17px',
// need to set vertical-align property because display is inline
// and it contains an empty button (the checkbox when un-checked)
// see https://stackoverflow.com/questions/21645695/button-element-without-text-causes-subsequent-buttons-to-be-positioned-wrong
verticalAlign: 'top',
// style the <Checkbox> (which renders a button) when label is hovered/active
'&.hover>button': {
color: '$green',
borderColor: '$green',
backgroundColor: '$formElementsBackground',
},
'&.mouseActive>button': {
boxShadow: '0 0 0 1px $colors$green',
},
'&.touchActive>button': {
color: '$blue',
borderColor: '$blue',
boxShadow: '0 0 0 1px $colors$blue',
},
'&.disabled': {
opacity: 0.5,
cursor: 'unset',
},
});
const Checkbox = styled(createInteractive(RadixCheckbox.Root), {
width: '17px',
height: '17px',
flexShrink: 0,
marginRight: '4px',
backgroundColor: '$formElementsBackground',
border: '1px solid $highContrast',
borderRadius: '2px',
// hover and active styles in label so styles are applied when label is hovered/active
// '&.hover, &.active': {...},
'&.focusFromKey': {
// !important required so hover and active styles from label are not applied
// to border and boxShadow when in the focusFromKey state
borderColor: '$purple !important',
boxShadow:
'0 0 0 1px $colors$purple, 2px 3px 4px 0px rgba(0, 0, 0, 0.38) !important',
},
'&.keyActive': {
color: '$purple',
boxShadow:
'0 0 0 1px $colors$purple, 1px 2px 3px 0px rgba(0, 0, 0, 0.38) !important',
},
});
// select css styling adapted from https://moderncss.dev/custom-select-styles-with-pure-css/
const SelectContainer = styled('div', {
display: 'grid',
gridTemplateAreas: '"select"',
alignItems: 'center',
margin: '8px 0',
// select custom arrow created with clip-path
'&::after': {
content: '',
gridArea: 'select',
justifySelf: 'end',
width: '14px',
height: '8px',
marginRight: '8px',
backgroundColor: '$highContrast',
clipPath: 'polygon(100% 0%, 50% 35%, 0 0%, 50% 100%)',
pointerEvents: 'none',
},
variants: {
disabled: {
true: { opacity: 0.5 },
},
},
});
const Select = styled(Interactive.Select, {
gridArea: 'select',
width: '100%',
backgroundColor: '$formElementsBackground',
border: '1px solid $colors$highContrast',
borderRadius: '4px',
padding: '4px 24px 4px 6px',
'&.hover': {
borderColor: '$green',
},
'&.mouseActive': {
boxShadow: '0 0 0 1px $colors$green',
},
'&.touchActive': {
borderColor: '$blue',
boxShadow: '0 0 0 1px $colors$blue',
},
'&.focusFromKey': {
borderColor: '$purple',
boxShadow: '0 0 0 1px $colors$purple, 2px 3px 4px 0px rgba(0, 0, 0, 0.38)',
},
'&.disabled': {
opacity: 0.5,
},
'&>option': {
// only works in desktop edge, desktop firefox, and chrome on windows
color: '$highContrast',
background: '$colors$pageBackground',
},
});
const Button = styled(Interactive.Button, {
display: 'block',
padding: '8px 26px',
margin: '18px 0 14px',
textAlign: 'center',
backgroundColor: '$formElementsBackground',
border: '1px solid',
borderRadius: '1000px',
'&.hover': {
borderColor: '$green',
boxShadow: '2px 3px 3px 0px rgba(0, 0, 0, 0.38)',
},
// focusFromKey styles are overridden by active styles (below), but not hover styles (above)
'&.focusFromKey': {
borderColor: '$purple',
boxShadow: '0 0 0 1px $colors$purple, 2px 3px 4px 0px rgba(0, 0, 0, 0.38)',
},
'&.mouseActive': {
color: '$green',
borderColor: '$green',
boxShadow: '0 0 0 1px $colors$green, 1px 2px 3px 0px rgba(0, 0, 0, 0.38)',
},
'&.touchActive': {
color: '$blue',
borderColor: '$blue',
boxShadow: '0 0 0 1px $colors$blue',
},
'&.keyActive': {
color: '$purple',
borderColor: '$purple',
boxShadow: '0 0 0 1px $colors$purple, 1px 2px 3px 0px rgba(0, 0, 0, 0.38)',
},
'&.disabled': {
opacity: 0.5,
},
});
// checking for fish easter egg
const Ocean = styled('div', {
position: 'fixed',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'royalblue',
opacity: 0.2,
pointerEvents: 'none',
zIndex: 1,
});
const Fish = styled(Interactive.Button, {
position: 'fixed',
fontSize: '9vmin',
lineHeight: '7vmin',
'&.focusFromKey': {
filter: 'drop-shadow(6px 6px 3px royalblue) hue-rotate(50deg)',
},
zIndex: 2,
});
interface FishType {
id: number;
top: number;
left: number;
}
const createOneFish: (id: number) => FishType = (id) => ({
id,
top: Math.floor(Math.random() * 81),
left: Math.floor(Math.random() * 91),
});
export const FormElements: React.VFC = () => {
const [textInputState, setTextInputState] = React.useState('');
const [textInputInputText, setTextInputInfoText] = React.useState('');
const [checkboxState, setCheckboxState] = React.useState(false);
const [anotherCheckboxState, setAnotherCheckboxState] = React.useState(false);
const [selectInputState, setSelectInputState] = React.useState('placeholder');
const [disableElements, setDisabledElements] = React.useState(false);
if (disableElements) {
textInputState !== '' && setTextInputState('');
checkboxState && setCheckboxState(false);
anotherCheckboxState && setAnotherCheckboxState(false);
selectInputState !== 'placeholder' && setSelectInputState('placeholder');
}
// checking for fish easter egg
const [fishes, setFishes] = React.useState<FishType[]>([]);
const createNewFishes = React.useCallback(() => {
const newFishes = Array(10)
.fill(1)
.map((_, idx) => createOneFish(idx));
setFishes(newFishes);
}, []);
React.useEffect(() => {
if (fishes.length === 1) {
setFishes((fishes) => [createOneFish(fishes[0].id)]);
const intervalId = window.setInterval(
() => {
setFishes((fishes) => [createOneFish(fishes[0].id)]);
},
// if the device is primarily a touch device then make the fish jump faster
// because a user's touch response is usually faster the their mouse response
primaryInput === 'touch' ? 700 : 1000,
);
return () => window.clearInterval(intervalId);
}
}, [fishes.length]);
return (
<DemoContainer id="form-elements">
<DemoHeading>Form Elements</DemoHeading>
<TextInput
type="text"
value={textInputState}
disabled={disableElements}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setTextInputState(e.target.value)
}
onStateChange={({ state }: InteractiveStateChange) => {
let infoText = '';
if (state.focus) {
infoText = 'This has focus for typing';
} else if (disableElements && (state.hover || state.active)) {
infoText = 'Un-disable form elements to use this text input';
}
setTextInputInfoText(infoText);
}}
placeholder={textInputInputText}
/>
<CheckboxLabel disabled={disableElements}>
<Checkbox
disabled={disableElements}
checked={checkboxState}
onCheckedChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setCheckboxState(event.target.checked)
}
>
<RadixCheckbox.Indicator as={CheckIcon} width="15" height="15" />
</Checkbox>
A checkbox for checking
</CheckboxLabel>
<CheckboxLabel disabled={disableElements}>
<Checkbox
disabled={disableElements}
checked={anotherCheckboxState}
onCheckedChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setAnotherCheckboxState(event.target.checked)
}
>
<RadixCheckbox.Indicator as={CheckIcon} width="15" height="15" />
</Checkbox>
Another checkbox for double checking
</CheckboxLabel>
<SelectContainer disabled={disableElements}>
<Select
disabled={disableElements}
value={selectInputState}
onChange={(e: React.ChangeEvent<HTMLSelectElement>) => {
setSelectInputState(e.target.value);
if (e.target.value === 'fishes') {
createNewFishes();
}
}}
// have to also use onMouseDown to setSelectInputState because of
// firefox bug: https://github.com/facebook/react/issues/12584#issuecomment-383233455
// note that other browsers don't fire a mousedown event when the select is open
onMouseDown={(e: any) => {
if (e.target.value) {
setSelectInputState(e.target.value);
}
}}
>
<option value="placeholder" disabled hidden>
Select your favorite type of checking
</option>
<option value="interest">Interest checking</option>
<option value="hockey">Hockey checking</option>
<option value="todo">Checking off a todo item</option>
<option value="double">Double checking everything</option>
<option value="fishes">Checking for fish 🐟🐟🐟🐇</option>
</Select>
</SelectContainer>
{fishes.length > 0 ? (
<>
<Ocean />
{fishes.map((fish, _, fishes) => (
<Fish
key={fish.id}
css={{ top: `${fish.top}vh`, left: `${fish.left}vw` }}
onClick={() => {
setFishes(fishes.filter((f) => f.id !== fish.id));
}}
>
🐟
</Fish>
))}
</>
) : null}
<Button disabled={disableElements}>Button</Button>
<CheckboxLabel css={{ marginBottom: 0 }}>
<Checkbox
onCheckedChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setDisabledElements(event.target.checked)
}
>
<RadixCheckbox.Indicator as={CheckIcon} width="15" height="15" />
</Checkbox>
Disable form elements
</CheckboxLabel>
</DemoContainer>
);
}; | the_stack |
import { Map, Cursor, CursorParams, Strings, Entries, EntriesSummary } from './common';
export class Config {
VERSION: string;
API_BASE: string;
retries: number;
constructor(token: string, secret: string, base?: string);
getAccountToken(): string;
getSecretKey(): string;
}
export namespace Ping {
function ping(config: Config): Promise<string>;
}
export namespace DataSource {
interface DataSource {
uuid?: string;
name: string;
created_at?: string;
status?: string;
system?: string;
}
interface DataSources {
data_sources: DataSource[];
}
interface ListDataSourcesParams {
name?: string;
system?: string;
}
function create(config: Config, data: DataSource): Promise<DataSource>;
function retrieve(config: Config, uuid: string): Promise<DataSource>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListDataSourcesParams): Promise<DataSources>;
}
export namespace Customer {
interface Customer {
id?: number;
data_source_uuid?: string;
data_source_uuids?: Strings;
uuid?: string;
external_id?: string;
external_ids?: Strings;
name?: string;
email?: string;
status?: string;
['customer-since']?: string;
attributes?: Attributes;
address?: {
address_zip?: string;
city?: string;
state?: string;
country?: string;
};
mrr?: number;
arr?: number;
['billing-system-url']?: string;
['chartmogul-url']?: string;
['billing-system-type']?: string;
currency?: string;
['currency-sign']?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
}
interface NewCustomer {
data_source_uuid: string;
external_id: string;
name: string;
email?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
attributes?: NewAttributes;
}
interface UpdateCustomer {
name?: string;
email?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
attributes?: NewAttributes;
}
interface NewAttributes {
tags?: Strings;
custom?: NewCustomAttributes[];
}
interface NewCustomAttributes {
type?: string;
key: string;
value: any;
source?: string;
}
interface Attributes {
tags?: Strings;
stripe?: Map;
clearbit?: Map;
custom?: Map;
}
interface ListCustomersParams extends CursorParams {
data_source_uuid?: string;
status?: string;
system?: string;
external_id?: string;
}
interface SearchCustomersParams extends CursorParams {
email: string;
}
interface MergeID {
customer_uuid?: string;
external_id?: string;
}
interface MergeCustomersParams {
from: MergeID;
into: MergeID;
}
function create(config: Config, data: NewCustomer): Promise<Customer>;
function retrieve(config: Config, uuid: string): Promise<Customer>;
function modify(config: Config, uuid: string, data: UpdateCustomer): Promise<Customer>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListCustomersParams): Promise<Entries<Customer>>;
function search(config: Config, params?: SearchCustomersParams): Promise<Entries<Customer>>;
function merge(config: Config, params?: MergeCustomersParams): Promise<{}>;
function attributes(config: Config, uuid: string): Promise<Attributes>;
}
export namespace Plan {
interface Plan {
uuid?: string;
data_source_uuid?: string;
external_id?: string;
name?: string;
interval_count?: number;
interval_unit?: string;
}
interface ListPlansParams extends CursorParams {
data_source_uuid?: string;
system?: string;
external_id?: string;
}
interface Plans extends Cursor {
plans: Plan[];
}
function create(config: Config, data: Plan): Promise<Plan>;
function retrieve(config: Config, uuid: string): Promise<Plan>;
function modify(config: Config, uuid: string, data: Plan): Promise<Plan>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListPlansParams): Promise<Plans>;
}
export namespace Invoice {
interface Invoice {
uuid?: string;
customer_uuid?: string;
currency?: string;
data_source_uuid?: string;
date?: string;
due_date?: string;
external_id?: string;
line_items?: LineItem[];
transactions?: Transaction[];
}
interface LineItem {
uuid?: string;
account_code?: string;
amount_in_cents?: number;
cancelled_at?: string;
description?: string;
discount_amount_in_cents?: number;
discount_code?: string;
external_id?: string;
plan_uuid?: string;
prorated?: boolean;
quantity?: number;
service_period_end?: string;
service_period_start?: string;
subscription_external_id?: string;
subscription_uuid?: string;
tax_amount_in_cents?: number;
transaction_fees_in_cents?: number;
type?: string;
}
interface Transaction {
uuid?: string;
date?: string;
external_id?: string;
result?: string;
type?: string;
}
interface ListInvoicesParams extends CursorParams {
data_source_uuid?: string;
customer_uuid?: string;
external_id?: string;
}
interface Invoices extends Cursor {
customer_uuid?: string;
invoices: Invoice[];
}
function create(config: Config, uuid: string, data: {
invoices: Invoice[]
}): Promise<Invoice>;
function retrieve(config: Config, uuid: string): Promise<Invoice>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, uuid: string, params?: ListInvoicesParams): Promise<Invoices>;
function all(config: Config, params?: ListInvoicesParams): Promise<Invoices>;
}
export namespace Transaction {
interface Transaction {
uuid?: string;
date: string;
external_id?: string;
result: string;
type: string;
}
function create(config: Config, uuid: string, data: Transaction): Promise<Transaction>;
}
export namespace Subscription {
interface Subscription {
uuid: string;
external_id: string;
customer_uuid: string;
plan_uuid: string;
cancellation_dates: Strings;
data_source_uuid: string;
}
interface CancelSubscriptionParams {
cancelled_at?: string;
cancellation_dates?: Strings;
}
interface Subscriptions extends Cursor {
customer_uuid?: string;
subscriptions: Subscription[];
}
function all(config: Config, uuid: string, data: CursorParams): Promise<Subscriptions>;
function cancel(config: Config, uuid: string, data: CancelSubscriptionParams): Promise<Subscription>;
}
export namespace Tag {
interface Tags {
tags: Strings;
}
interface TagsWithEmail {
email: string;
tags: Strings;
}
function add(config: Config, uuid: string, data: TagsWithEmail): Promise<Entries<Customer.Customer>>;
function add(config: Config, uuid: string, data: Tags): Promise<Tags>;
function remove(config: Config, uuid: string, data: Tags): Promise<Tags>;
}
export namespace CustomAttribute {
import NewCustomAttributes = Customer.NewCustomAttributes;
interface CustomAttributes {
custom: Map;
}
function add(config: Config, uuid: string, data: {
email: string;
custom: NewCustomAttributes[];
}): Promise<Entries<Customer.Customer>>;
function add(config: Config, uuid: string, data: {
custom: NewCustomAttributes[];
}): Promise<CustomAttributes>;
function update(config: Config, uuid: string, data: CustomAttributes): Promise<CustomAttributes>;
function remove(config: Config, uuid: string, data: {
custom: Strings;
}): Promise<CustomAttributes>;
}
export namespace Metrics {
interface Params extends ParamsNoInterval {
interval?: string;
}
interface ParamsNoInterval {
['start-date']: string;
['end-date']: string;
geo?: string;
plans?: string;
}
interface All {
entries: {
date: string;
['customer-churn-rate']: number;
['mrr-churn-rate']: number;
ltv: number;
customers: number;
asp: number;
arpa: number;
arr: number;
mrr: number;
};
}
interface MRR {
date: string;
mrr: number;
['mrr-new-business']: number;
['mrr-expansion']: number;
['mrr-contraction']: number;
['mrr-churn']: number;
['mrr-reactivation']: number;
}
interface ARR {
date: string;
arr: number;
}
interface ARPA {
date: string;
arpa: number;
}
interface ASP {
date: string;
asp: number;
}
interface CustomerCount {
date: string;
customers: number;
}
interface CustomerChurnRate {
date: string;
['customer-churn-rate']: number;
}
interface MRRChurnRate {
date: string;
['mrr-churn-rate']: number;
}
interface LTV {
date: string;
ltv: number;
}
function all(config: Config, params: Params): Promise<All>;
function mrr(config: Config, params: Params): Promise<EntriesSummary<MRR>>;
function arr(config: Config, params: Params): Promise<EntriesSummary<ARR>>;
function asp(config: Config, params: Params): Promise<EntriesSummary<ASP>>;
function arpa(config: Config, params: Params): Promise<EntriesSummary<ARPA>>;
function customerCount(config: Config, params: Params): Promise<EntriesSummary<CustomerCount>>;
function customerChurnRate(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<CustomerChurnRate>>;
function mrrChurnRate(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<MRRChurnRate>>;
function ltv(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<LTV>>;
namespace Customer {
interface MetricsSubscription {
id: number;
external_id: string;
plan: string;
quantity: number;
mrr: number;
arr: number;
status: string;
['billing-cycle']: string;
['billing-cycle-count']: number;
['start-date']: string;
['end-date']: string;
currency: string;
['currency-sign']: string;
}
interface MetricsActivity {
id: number;
date: string;
['activity-arr']: number;
['activity-mrr']: number;
['activity-mrr-movement']: number;
currency: string;
['currency-sign']: string;
description: string;
type: string;
}
function subscriptions(config: Config, uuid: string, params?: CursorParams): Promise<Entries<MetricsSubscription>>;
function activities(config: Config, uuid: string, params?: CursorParams): Promise<Entries<MetricsActivity>>;
}
}
export class ChartMogulError extends Error {
response: any;
httpStatus: number;
}
export class ConfigurationError extends ChartMogulError {}
export class ForbiddenError extends ChartMogulError {}
export class NotFoundError extends ChartMogulError {}
export class ResourceInvalidError extends ChartMogulError {}
export class SchemaInvalidError extends ChartMogulError {} | the_stack |
module WinJSTests {
"use strict";
var testRootEl;
function createSezo(layoutOptions, gids, gds, sezoOptions?) {
var sezoDiv = document.getElementById("sezoDiv"),
listDiv1 = <HTMLElement>sezoDiv.children[0],
listDiv2 = <HTMLElement>sezoDiv.children[1],
layoutName = layoutOptions.type,
orientation = layoutOptions.orientation,
list1 = new WinJS.UI.ListView(listDiv1, {
itemDataSource: gids,
itemTemplate: Helper.syncJSTemplate,
groupDataSource: gds,
groupHeaderTemplate: Helper.syncJSTemplate,
layout: new WinJS.UI[layoutName]({ orientation: orientation })
}),
list2 = new WinJS.UI.ListView(listDiv2, {
itemDataSource: gds,
itemTemplate: Helper.syncJSTemplate,
layout: new WinJS.UI[layoutName]({ orientation: orientation })
}),
sezo = <WinJS.UI.ISemanticZoom> new WinJS.UI.SemanticZoom(sezoDiv, (sezoOptions ? sezoOptions : {}));
// Verify accessibility
var checkAttribute = function (element, attribute, expectedValue) {
var values = element.getAttribute(attribute).match(expectedValue),
value = values ? values[0] : null;
LiveUnit.LoggingCore.logComment("Expected " + attribute + ": " + expectedValue + " Actual: " + value);
LiveUnit.Assert.areEqual(value, expectedValue, "Expected " + attribute + ": " + expectedValue +
" Actual: " + value);
};
checkAttribute(sezo.element, "role", "ms-semanticzoomcontainer");
checkAttribute(sezo.element, "aria-checked", sezo.zoomedOut.toString());
var button = sezo.element.querySelector(".win-semanticzoom-button");
if (button) {
checkAttribute(sezo.element.querySelector(".win-semanticzoom-button"), "aria-hidden", "true");
}
return sezo;
}
function createSezoWithBindingList(layoutOptions, itemCount, sezoOptions?) {
var bl = Helper.createBindingList(itemCount),
groupBL = bl.createGrouped(Helper.groupKey, Helper.groupData),
sezo = createSezo(layoutOptions, groupBL.dataSource, groupBL.groups.dataSource, sezoOptions);
return sezo;
}
function createSezoWithVDS(layoutOptions, itemCount, sezoOptions) {
var vds = Helper.createTestDataSource(itemCount),
groupVDS = WinJS.UI.computeDataSourceGroups(vds, Helper.groupKey, Helper.groupData),
sezo = createSezo(layoutOptions, groupVDS, groupVDS.groups, sezoOptions);
return sezo;
}
function zoomAndVerify(sezo, startIndex, input) {
var listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
list1 = listDiv1.winControl,
list2 = listDiv2.winControl,
zoomItem;
function VerifyIsVisible(listView, index) {
LiveUnit.Assert.isTrue(index >= listView.indexOfFirstVisible, "Expecting index (" + index + ") >= indexOfFirstVisible (" + listView.indexOfFirstVisible + ")");
LiveUnit.Assert.isTrue(index <= listView.indexOfLastVisible, "Expecting index (" + index + ") <= indexOfFirstVisible (" + listView.indexOfLastVisible + ")");
}
return Helper.ListView.waitForReady(list1)().
then(function () {
list1.indexOfFirstVisible = startIndex;
return Helper.ListView.waitForReady(list1)();
}).
then(function () {
// Hit test on the listView to get the item at the viewport center
var style = getComputedStyle(sezo.element),
centerX = WinJS.Utilities.getScrollPosition(list1._viewport).scrollLeft + (parseInt(style.width, 10) / 2),
centerY = list1._viewport.scrollTop + parseInt(style.height, 10) / 2,
centerItemIndex = -1;
var hitTest = list1.layout.hitTest(centerX, centerY);
if (+hitTest.index === hitTest.index) {
centerItemIndex = hitTest.index;
}
LiveUnit.Assert.isTrue(centerItemIndex >= 0, "Hit test failed. Index of item at viewport center: " + centerItemIndex);
// Get the item from datasource
return list1.itemDataSource.itemFromIndex(centerItemIndex);
}).
then(function (itemAtIndex) {
// Save it for verification
zoomItem = itemAtIndex;
return new WinJS.Promise(function (c, e, p) {
sezo.addEventListener("zoomchanged", handler);
function handler(ev) {
sezo.removeEventListener("zoomchanged", handler);
// Yield so that listView can finish the pending work
var item = list2.zoomableView.getCurrentItem.call(list2.zoomableView);
WinJS.Utilities._setImmediate(function () {
c(item);
});
}
// Zoom out
// The sezo behavior when zooming with api and button is same even though they are separate
// code paths internally
if (input === "Api") {
sezo.zoomedOut = true;
} else if (input === "Button") {
sezo._onSeZoButtonZoomOutClick();
}
});
}).
then(Helper.ListView.waitForReady(list2)).
then(function (currentItem: any) {
// currentItem in the zoomed out view should be a group item.
// zoomItem should be belonging to this group.
var expectedCurrItem = {
key: Helper.groupKey(zoomItem),
data: Helper.groupData(zoomItem)
};
LiveUnit.Assert.areEqual(expectedCurrItem.key, currentItem.item.key, "Zoomed out to wrong group");
LiveUnit.Assert.areEqual(JSON.stringify(expectedCurrItem.data), JSON.stringify(currentItem.item.data),
"Zoomed out to wrong group");
// Verify currentItem is visible
VerifyIsVisible(list2, currentItem.item.index);
});
}
function keyboardZoomAndVerify(sezo, startIndex) {
var listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
list1 = listDiv1.winControl,
list2 = listDiv2.winControl,
zoomItem;
function VerifyIsVisible(listView, index) {
LiveUnit.Assert.isTrue(index >= listView.indexOfFirstVisible, "Expecting index (" + index + ") >= indexOfFirstVisible (" + listView.indexOfFirstVisible + ")");
LiveUnit.Assert.isTrue(index <= listView.indexOfLastVisible, "Expecting index (" + index + ") <= indexOfFirstVisible (" + listView.indexOfLastVisible + ")");
}
return Helper.ListView.waitForReady(list1)().
then(function () {
list1.indexOfFirstVisible = startIndex;
return Helper.ListView.waitForReady(list1)();
}).
then(function () {
// Get the item from datasource
return list1.itemDataSource.itemFromIndex(startIndex);
}).
then(function (itemAtIndex) {
// Save it for verification
zoomItem = itemAtIndex;
return new WinJS.Promise(function (c, e, p) {
sezo.addEventListener("zoomchanged", handler);
function handler(ev) {
sezo.removeEventListener("zoomchanged", handler);
// Yield so that listView can finish the pending work
var item = list2.zoomableView.getCurrentItem.call(list2.zoomableView);
WinJS.Utilities._setImmediate(function () {
c(item);
});
}
// Set focus on item at startIndex
list1.currentItem = { index: startIndex, hasFocus: true };
// Zoom out by calling the _onKeyDown handler in sezo
var eventObj = {
ctrlKey: true,
keyCode: WinJS.Utilities.Key.subtract,
stopPropagation: function () { },
preventDefault: function () { }
};
sezo._onKeyDown(eventObj);
});
}).
then(function (currentItem: any) {
// currentItem in the zoomed out view should be a group item.
// zoomItem should be belonging to this group.
var expectedCurrItem = {
key: Helper.groupKey(zoomItem),
data: Helper.groupData(zoomItem)
};
LiveUnit.Assert.areEqual(expectedCurrItem.key, currentItem.item.key, "Zoomed out to wrong group");
LiveUnit.Assert.areEqual(JSON.stringify(expectedCurrItem.data), JSON.stringify(currentItem.item.data),
"Zoomed out to wrong group");
// Verify currentItem is visible
VerifyIsVisible(list2, currentItem.item.index);
});
}
export class SemanticZoomTests {
setUp() {
LiveUnit.LoggingCore.logComment("In setup");
testRootEl = document.createElement("div");
testRootEl.className = "file-listview-css";
var newNode = document.createElement("div");
newNode.id = "SemanticZoomTests";
newNode.innerHTML =
"<div id='sezoDiv' style='width:500px; height:500px'><div id='child1'></div><div id='child2'></div></div>";
testRootEl.appendChild(newNode);
document.body.appendChild(testRootEl);
}
tearDown() {
LiveUnit.LoggingCore.logComment("In tearDown");
WinJS.Utilities.disposeSubTree(testRootEl);
document.body.removeChild(testRootEl);
}
testSezoButtonVisibilityOnLock(complete) {
var sezo = createSezoWithBindingList({ type: "GridLayout", orientation: WinJS.UI.Orientation.horizontal }, 500),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
buttonClass = "win-semanticzoom-button";
if (WinJS.Utilities.isPhone) {
complete();
} else {
Helper.ListView.waitForReady(listDiv1.winControl)().
then(function () {
// Button is shown only on mouse move and pen hover
// Ensure the button is visible
var button = <HTMLElement>document.getElementsByClassName(buttonClass)[0];
sezo._showSemanticZoomButton();
// Lock the sezo
sezo.locked = true;
// Wait for the fadeOut animation to finish before checking the visibility again
return WinJS.Promise.timeout(500).then(function () {
LiveUnit.Assert.areEqual("hidden", button.style.visibility, "Button should be hidden");
});
}).
done(complete, function (er) {
throw er;
});
}
}
testOutOfBoundsGridLayout(complete) {
var sezoDiv = document.getElementById("sezoDiv"),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2");
function simpleRenderer(itemPromise) {
var el = document.createElement("div");
el.style.width = "50px";
el.style.height = "50px";
return {
element: el,
renderComplete: itemPromise.then(function (d) {
el.textContent = d.data;
})
};
}
var inView = new WinJS.UI.ListView(listDiv1, {
itemDataSource: new WinJS.Binding.List([1, 2, 3]).dataSource,
itemTemplate: simpleRenderer,
layout: new WinJS.UI.GridLayout()
});
var outView = new WinJS.UI.ListView(listDiv2, {
itemDataSource: new WinJS.Binding.List([1, 2, 3]).dataSource,
itemTemplate: simpleRenderer,
layout: new WinJS.UI.GridLayout()
});
function doNothingMappingFunction(item) {
return {
groupIndexHint: 0,
firstItemIndexHint: 0,
};
}
var sezoRect = sezoDiv.getBoundingClientRect();
var fakeEventObject: any = {
clientX: sezoRect.left + sezoDiv.offsetWidth - 100,
clientY: sezoRect.top + 50,
preventDefault: function () { },
stopPropagation: function () { },
srcElement: sezoDiv,
ctrlKey: true
};
WinJS.Promise.join([Helper.ListView.waitForReady(inView)(), Helper.ListView.waitForReady(outView)()]).then(function () {
var sezo = <WinJS.UI.ISemanticZoom> new WinJS.UI.SemanticZoom(sezoDiv, {
zoomedInItem: doNothingMappingFunction,
zoomedOutItem: doNothingMappingFunction
});
function onZoomedOut() {
sezo.removeEventListener("zoomchanged", onZoomedOut);
sezo.addEventListener("zoomchanged", onZoomedIn);
fakeEventObject.wheelDelta = 1;
sezo._onMouseWheel(fakeEventObject);
}
function onZoomedIn() {
sezo.removeEventListener("zoomchanged", onZoomedIn);
WinJS.Utilities._setImmediate(complete);
}
sezo.addEventListener("zoomchanged", onZoomedOut);
fakeEventObject.wheelDelta = -1;
sezo._onMouseWheel(fakeEventObject);
});
}
testSezoSizeTruncation(complete) {
var width = "1000.4px";
var height = "800.3px";
var lv1 = new WinJS.UI.ListView();
var lv2 = new WinJS.UI.ListView();
var sezoDiv = document.createElement("div");
sezoDiv.style.width = width;
sezoDiv.style.height = height;
testRootEl.appendChild(sezoDiv);
sezoDiv.appendChild(lv1.element);
sezoDiv.appendChild(lv2.element);
var sezo = new WinJS.UI.SemanticZoom(sezoDiv);
WinJS.Utilities._setImmediate(function () {
var csSezo = getComputedStyle(sezoDiv);
var csLv1 = getComputedStyle(lv1.element);
var csLv2 = getComputedStyle(lv2.element);
LiveUnit.Assert.areEqual(csSezo.width, csLv1.width);
LiveUnit.Assert.areEqual(csSezo.width, csLv2.width);
LiveUnit.Assert.areEqual(csSezo.height, csLv1.height);
LiveUnit.Assert.areEqual(csSezo.height, csLv2.height);
complete();
});
}
testSezoPinching() {
var sezoDiv = document.getElementById("sezoDiv"),
childDiv1 = document.getElementById("child1"),
childDiv2 = document.getElementById("child2");
childDiv1.winControl = {
zoomableView: {
pinching: false,
getPanAxis: function () {
return "horizontal";
},
configureForZoom: function () {
//noop
}
}
}
childDiv2.winControl = {
zoomableView: {
pinching: false,
getPanAxis: function () {
return "horizontal";
},
configureForZoom: function () {
//noop
}
}
}
var sezo = <WinJS.UI.ISemanticZoom> new WinJS.UI.SemanticZoom(sezoDiv);
LiveUnit.Assert.areEqual(false, childDiv1.winControl.zoomableView.pinching);
LiveUnit.Assert.areEqual(false, childDiv2.winControl.zoomableView.pinching);
sezo._pinching = true;
LiveUnit.Assert.areEqual(true, childDiv1.winControl.zoomableView.pinching);
LiveUnit.Assert.areEqual(true, childDiv2.winControl.zoomableView.pinching);
sezo._pinching = false;
LiveUnit.Assert.areEqual(false, childDiv1.winControl.zoomableView.pinching);
LiveUnit.Assert.areEqual(false, childDiv2.winControl.zoomableView.pinching);
}
};
(function () {
function generateTest(input) {
['GridLayout', 'ListLayout'].forEach(function (layoutName) {
[WinJS.UI.Orientation.vertical, WinJS.UI.Orientation.horizontal].forEach(function (orientation) {
function generateTest1(dsType, index) {
return function (complete) {
var sezo = dsType({ type: layoutName, orientation: orientation }, 1000),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
list1 = listDiv1.winControl,
list2 = listDiv2.winControl;
Helper.ListView.waitForReady(list1)().
then(function () {
switch (input) {
case "Api":
case "Button":
return zoomAndVerify(sezo, index, input);
break;
case "Keyboard":
return keyboardZoomAndVerify(sezo, index);
break;
// TODO: add tests for touch inputs
default:
}
}).
done(complete, function (er) {
throw er;
});
};
}
// These tests verify the API zoom feature
SemanticZoomTests.prototype["test" + input + "ZoomFromStartBindingList_" + layoutName + "_" + orientation] = generateTest1(createSezoWithBindingList, 0);
SemanticZoomTests.prototype["test" + input + "ZoomFromMiddleBindingList_" + layoutName + "_" + orientation] = generateTest1(createSezoWithBindingList, 500);
SemanticZoomTests.prototype["test" + input + "ZoomFromEndBindingList_" + layoutName + "_" + orientation] = generateTest1(createSezoWithBindingList, 999);
SemanticZoomTests.prototype["test" + input + "ZoomFromStartVDS_" + layoutName + "_" + orientation] = generateTest1(createSezoWithVDS, 0);
SemanticZoomTests.prototype["test" + input + "ZoomFromMiddleVDS_" + layoutName + "_" + orientation] = generateTest1(createSezoWithVDS, 500);
SemanticZoomTests.prototype["test" + input + "ZoomFromEndVDS_" + layoutName + "_" + orientation] = generateTest1(createSezoWithVDS, 999);
});
});
}
generateTest("Keyboard");
generateTest("Api");
generateTest("Button");
})();
(function () {
function generateTest(layoutName, resize) {
return function (complete) {
var sezo = createSezoWithBindingList({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 200),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2");
Helper.ListView.waitForReady(listDiv1.winControl)().
then(function () {
// Verify the visibility and opacity for in and out views
LiveUnit.Assert.areEqual("visible", getComputedStyle(sezo._viewportIn).visibility,
"Zoomed in view is not visible");
LiveUnit.Assert.areEqual("hidden", getComputedStyle(sezo._viewportOut).visibility,
"Zoomed out view is not hidden");
LiveUnit.Assert.areEqual("1", getComputedStyle(sezo._canvasIn).opacity,
"Zoomed in view is not visible");
LiveUnit.Assert.areEqual("0", getComputedStyle(sezo._canvasOut).opacity,
"Zoomed out view is not hidden");
return new WinJS.Promise(function (c, e, p) {
sezo.addEventListener("zoomchanged", function (ev) {
// Yield so that listView can finish the pending work
WinJS.Utilities._setImmediate(c);
});
sezo.zoomedOut = !sezo.zoomedOut;
if (resize) {
sezo.element.style.width = "400px";
}
});
}).
then(function () {
var isPhone = WinJS.Utilities.isPhone;
// Verify the visibility and opacity for in and out views
LiveUnit.Assert.areEqual((isPhone ? "visible" : "hidden"), getComputedStyle(sezo._viewportIn).visibility,
"Zoomed in view is " + (isPhone ? "" : "not") + "hidden");
LiveUnit.Assert.areEqual("visible", getComputedStyle(sezo._viewportOut).visibility,
"Zoomed out view is not visible");
LiveUnit.Assert.areEqual((isPhone ? "1" : "0"), getComputedStyle(sezo._canvasIn).opacity,
"Zoomed in view is " + (isPhone ? "" : "not") + "hidden");
LiveUnit.Assert.areEqual("1", getComputedStyle(sezo._canvasOut).opacity,
"Zoomed out view is not visible");
}).
done(complete, function (er) {
throw er;
});
};
}
SemanticZoomTests.prototype["testSezoOpacityAndVisibilityWithResizeGridLayout"] = generateTest("GridLayout", true);
SemanticZoomTests.prototype["testSezoOpacityAndVisibilityWithoutResizeGridLayout"] = generateTest("GridLayout", false);
})();
(function () {
function generateTest(layoutName, dsType) {
return function (complete) {
var sezo = dsType({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 200, { initiallyZoomedOut: true }),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2");
Helper.ListView.waitForReady(listDiv2.winControl)().
then(function () {
// Verify the zoomed out view is visible
LiveUnit.Assert.isTrue(sezo.zoomedOut, "Sezo didn't start with zoomed out view when initiallyZoomedOut = true");
// Verify the sezo button is not visible when not on phone, and doesn't exist when on phone
if (WinJS.Utilities.isPhone) {
LiveUnit.Assert.isTrue(sezo.element.querySelectorAll(".win-semanticzoom-button").length === 0);
} else {
LiveUnit.Assert.areEqual(sezo.element.querySelector(".win-semanticzoom-button").style.visibility, "hidden",
"Sezo button is visible in the zoomed out view when it shouldn't be");
}
}).
done(complete, function (er) {
throw er;
});
};
}
SemanticZoomTests.prototype["testStartZoomedOutBindingListGridLayout"] = generateTest("GridLayout", createSezoWithBindingList);
SemanticZoomTests.prototype["testStartZoomedOutVDSGridLayout"] = generateTest("GridLayout", createSezoWithVDS);
})();
(function () {
function generateTest(layoutName, button) {
return function (complete) {
var sezo = createSezoWithBindingList({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 200, { enableButton: button }),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2");
Helper.ListView.waitForReady(listDiv1.winControl)().
then(function () {
// Verify you are in zoomed in view
LiveUnit.Assert.isFalse(sezo.zoomedOut, "Sezo didn't start with zoomed in view");
if (button && !WinJS.Utilities.isPhone) {
// Verify the button is present
LiveUnit.Assert.isNotNull(sezo.element.querySelector(".win-semanticzoom-button"), "Sezo button is not present");
// Button should be visible only on mousemove. Verify button is hidden
LiveUnit.Assert.areEqual((<HTMLElement>sezo.element.querySelector(".win-semanticzoom-button")).style.visibility, "hidden",
"Sezo button is visible when it shouldn't be");
} else {
// Verify the button is not present
LiveUnit.Assert.isNull(sezo.element.querySelector(".win-semanticzoom-button"),
"Sezo button is present in the DOM when it shouldn't be");
}
}).
done(complete, function (er) {
throw er;
});
};
}
SemanticZoomTests.prototype["testSezoButtonEnabledGridLayout"] = generateTest("GridLayout", true);
SemanticZoomTests.prototype["testSezoButtonDisabledGridLayout"] = generateTest("GridLayout", false);
})();
(function () {
["GridLayout", "ListLayout"].forEach(function (layoutName) {
function generateTest(layoutName, dsType) {
return function (complete) {
var sezo = dsType({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 500),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2");
Helper.ListView.waitForReady(listDiv1.winControl)().
then(function () {
// Wait for 2 seconds for the Aria worker to execute
return WinJS.Promise.timeout(2000);
}).
done(complete, function (er) {
throw er;
});
};
}
SemanticZoomTests.prototype["testWaitForAriaWorkerSezoBindingList_" + layoutName] = generateTest(layoutName, createSezoWithBindingList);
SemanticZoomTests.prototype["testWaitForAriaWorkerSezoVDS_" + layoutName] = generateTest(layoutName, createSezoWithVDS);
});
})();
(function () {
function generateTest(fromLayout, toLayout) {
return function (complete) {
var sezo = createSezoWithBindingList({ type: fromLayout, orientation: WinJS.UI.Orientation.horizontal }, 500),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2");
WinJS.Promise.join([Helper.ListView.waitForReady(listDiv1.winControl)(), Helper.ListView.waitForReady(listDiv2.winControl)()]).
then(function () {
return Helper.waitForEvent(sezo, "zoomchanged", function () {
// Zoom
sezo.zoomedOut = !sezo.zoomedOut;
// Change listView layouts without waiting for zoomchanged event shouldn't throw
listDiv1.winControl.layout = new WinJS.UI[toLayout]();
listDiv2.winControl.layout = new WinJS.UI[toLayout]();
});
}).
then(function () {
return WinJS.Promise.join([Helper.ListView.waitForReady(listDiv1.winControl)(), Helper.ListView.waitForReady(listDiv2.winControl)()]);
}).
done(complete, function (er) {
throw er;
});
};
}
// WinBlue: 169137 regression test
SemanticZoomTests.prototype["testChangingListViewLayoutDuringZoomGridToList"] = generateTest("GridLayout", "ListLayout");
SemanticZoomTests.prototype["testChangingListViewLayoutDuringZoomListToGrid"] = generateTest("ListLayout", "GridLayout");
})();
(function () {
function generateTest(layoutName, sezoOptions) {
return function (complete) {
var sezo = createSezoWithBindingList({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 500, sezoOptions),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
startView = sezo.zoomedOut;
WinJS.Promise.timeout().
then(function () {
sezo.locked = true;
sezo.addEventListener("zoomchanged", function (ev) {
LiveUnit.Assert.fail("Zoomchanged should not fire when sezo is locked");
});
sezo.zoomedOut = !sezo.zoomedOut;
return WinJS.Promise.timeout();
}).
then(function () {
// Verify that view didn't change
LiveUnit.Assert.areEqual(startView, sezo.zoomedOut, "View changed even though sezo was locked");
}).
done(complete, function (er) {
throw er;
});
};
}
// Test setting the locked property outside the constructor
SemanticZoomTests.prototype["testLockedZoomedInViewPropertyGridLayout"] = generateTest("GridLayout", { initiallyZoomedOut: false });
SemanticZoomTests.prototype["testLockedZoomedOutViewPropertyGridLayout"] = generateTest("GridLayout", { initiallyZoomedOut: true });
})();
(function () {
function generateTest(layoutName, sezoOptions) {
return function (complete) {
sezoOptions.locked = true;
var sezo = createSezoWithBindingList({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 500, sezoOptions),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
startView = sezo.zoomedOut;
WinJS.Promise.timeout().
then(function () {
sezo.addEventListener("zoomchanged", function (ev) {
LiveUnit.Assert.fail("Zoomchanged should not fire when sezo is locked");
});
sezo.zoomedOut = !sezo.zoomedOut;
return WinJS.Promise.timeout();
}).
then(function () {
// Verify that view didn't change
LiveUnit.Assert.areEqual(startView, sezo.zoomedOut, "View changed even though sezo was locked");
}).
done(complete, function (er) {
throw er;
});
};
}
// Test the locked property in constructor
SemanticZoomTests.prototype["testLockedZoomedInViewCtorGridLayout"] = generateTest("GridLayout", { initiallyZoomedOut: false });
SemanticZoomTests.prototype["testLockedZoomedOutViewCtorGridLayout"] = generateTest("GridLayout", { initiallyZoomedOut: true });
})();
(function () {
function generateTest(layoutName, dsType) {
return function (complete) {
var sezo = dsType({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 0),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2");
Helper.ListView.waitForReady(listDiv1.winControl)().
done(complete, function (er) {
throw er;
});
};
}
SemanticZoomTests.prototype["testEmptySezoBindingListGridLayout"] = generateTest("GridLayout", createSezoWithBindingList);
SemanticZoomTests.prototype["testEmptySezoVDSGridLayout"] = generateTest("GridLayout", createSezoWithVDS);
})();
function generateSezoOnZoomChangedOption(layoutName) {
SemanticZoomTests.prototype["testSezoOnZoomChangedOption" + layoutName] = function (complete) {
function zoomChangedHandler(e) {
WinJS.Utilities._setImmediate(complete);
}
var sezo = createSezoWithBindingList({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 10, { onzoomchanged: zoomChangedHandler }),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2");
sezo.zoomedOut = !sezo.zoomedOut;
};
}
generateSezoOnZoomChangedOption("GridLayout");
function generateDefaultAriaLabel(layoutName) {
SemanticZoomTests.prototype["testDefaultAriaLabel" + layoutName] = function (complete) {
var sezoDiv = document.getElementById("sezoDiv"),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
sezo = createSezoWithBindingList({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 10);
// Verify the default aria-label is empty string
var label = sezoDiv.getAttribute("aria-label");
LiveUnit.Assert.areEqual(label, "", "Default aria-label is not empty");
complete();
};
}
generateDefaultAriaLabel("GridLayout");
function generateSettingAriaLabel(layoutName) {
SemanticZoomTests.prototype["testSettingAriaLabel" + layoutName] = function (complete) {
var sezoDiv = document.getElementById("sezoDiv"),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
mylabel = "mylabel",
sezo;
// Set the aria-label
sezoDiv.setAttribute("aria-label", mylabel);
sezo = createSezoWithBindingList({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 10);
// Verify the aria-label is set
var actualLabel = sezoDiv.getAttribute("aria-label");
LiveUnit.Assert.areEqual(mylabel, actualLabel, "aria-label is wrong");
complete();
};
};
generateSettingAriaLabel("GridLayout");
function generateSezoDispose(layoutName) {
SemanticZoomTests.prototype["testDisposeSezo" + layoutName] = function (complete) {
var sezoDiv = document.getElementById("sezoDiv"),
listDiv1 = document.getElementById("child1"),
listDiv2 = document.getElementById("child2"),
sezo = createSezoWithBindingList({ type: layoutName, orientation: WinJS.UI.Orientation.horizontal }, 10);
LiveUnit.Assert.isTrue(sezo.dispose);
LiveUnit.Assert.isFalse(sezo._disposed);
sezo.dispose();
LiveUnit.Assert.isTrue(sezo._disposed);
complete();
};
}
generateSezoDispose("GridLayout");
}
LiveUnit.registerTestClass("WinJSTests.SemanticZoomTests"); | the_stack |
import { Message, SignedMessage, Cid, MessagePartial, HeadChange, TipSet, BlockHeader, BlockMessages, MessageReceipt, WrappedMessage, ObjStat, TipSetKey, SyncState, MpoolUpdate, PeerID, Address, StorageAsk, Actor, ActorState, NetworkName, SectorOnChainInfo, DeadlineInfo, MinerPower, MinerInfo, Deadline, Partition, BitField, ChainEpoch, Fault, SectorPreCommitInfo, SectorNumber, SectorPreCommitOnChainInfo, SectorExpiration, SectorLocation, MsgLookup, MarketBalance, MarketDeal, DealID, MinerSectors, MsigVesting } from '../Types';
import BigNumber from 'bignumber.js';
import { LotusClient } from '../..';
export class BaseWalletProvider {
public client: LotusClient;
constructor(client: LotusClient) {
this.client = client;
}
public async release() {
return this.client.release();
}
/**
* get balance for address
* @param address
*/
public async getBalance(address: string): Promise<any> {
const ret = await this.client.wallet.balance(address);
return ret as string;
}
/**
* get nonce for address. Note that this method may not be atomic. Use MpoolPushMessage instead.
* @param address
*/
public async getNonce(address: string): Promise<number> {
const ret = await this.client.mpool.getNonce(address);
return ret as number;
}
/**
* send signed message
* @param msg
*/
public async sendSignedMessage(msg: SignedMessage): Promise<Cid> {
const ret = await this.client.mpool.push(msg)
return ret as Cid;
}
/**
* estimate gas fee cap
* @param message
* @param nblocksincl
*/
public async estimateMessageGasFeeCap(message: Message, nblocksincl: number): Promise<string> {
const ret = await this.client.gasEstimate.feeCap(message, nblocksincl);
return ret as string;
}
/**
* estimate gas limit, it fails if message fails to execute.
* @param message
*/
public async estimateMessageGasLimit(message: Message): Promise<number> {
const ret = await this.client.gasEstimate.gasLimit(message);
return ret as number;
}
/**
* estimate gas to succesufully send message, and have it likely be included in the next nblocksincl blocks
* @param nblocksincl
* @param sender
* @param gasLimit
*/
public async estimateMessageGasPremium(nblocksincl: number, sender: string, gasLimit: number): Promise<string> {
const ret = await this.client.gasEstimate.gasPremium(nblocksincl, sender, gasLimit);
return ret as string;
}
/**
* estimate gas to succesufully send message, and have it included in the next 10 blocks
* @param message
*/
public async estimateMessageGas(message: Message): Promise<Message> {
const ret = await this.client.gasEstimate.messageGas(message);
return ret as Message;
}
/**
* prepare a message for signing, add defaults, and populate nonce and gas related parameters if not provided
* @param message
*/
public async createMessage(message: MessagePartial): Promise<Message> {
let msg: Message = {
To: message.To,
From: message.From,
Value: message.Value ? message.Value : new BigNumber(0),
GasLimit: message.GasLimit ? message.GasLimit : 0,
GasFeeCap: message.GasFeeCap ? message.GasFeeCap : new BigNumber(0),
GasPremium: message.GasPremium ? message.GasPremium : new BigNumber(0),
Method: message.Method ? message.Method : 0,
Params: message.Params ? message.Params : '',
Version: message.Version ? message.Version : 0,
Nonce: message.Nonce ? message.Nonce : await this.getNonce(message.From),
}
if (msg.GasLimit === 0) msg = await this.estimateMessageGas(msg);
return msg;
}
//Passtrough methods
//Chain methods
/**
* call back on chain head updates.
* @param cb
* @returns interval id
*/
public async chainNotify(cb: (headChange: HeadChange[]) => void) {
this.client.chain.chainNotify(cb);
}
/**
* returns the current head of the chain
*/
public async getHead(): Promise<TipSet> {
const ret = await this.client.chain.getHead();
return ret as TipSet;
}
/**
* returns the block specified by the given CID
* @param blockCid
*/
public async getBlock(blockCid: Cid): Promise<BlockHeader> {
const ret = await this.client.chain.getBlock(blockCid);
return ret as BlockHeader;
}
/**
* returns messages stored in the specified block.
* @param blockCid
*/
public async getBlockMessages(blockCid: Cid): Promise<BlockMessages> {
const ret = await this.client.chain.getBlockMessages(blockCid);
return ret as BlockMessages;
}
/**
* returns receipts for messages in parent tipset of the specified block
* @param blockCid
*/
public async getParentReceipts(blockCid: Cid): Promise<MessageReceipt[]> {
const ret = await this.client.chain.getParentReceipts(blockCid);
return ret as MessageReceipt[];
}
/**
* returns messages stored in parent tipset of the specified block.
* @param blockCid
*/
public async getParentMessages(blockCid: Cid): Promise<WrappedMessage[]> {
const ret = await this.client.chain.getParentMessages(blockCid);
return ret as WrappedMessage[];
}
/**
* looks back for a tipset at the specified epoch.
* @param epochNumber
*/
public async getTipSetByHeight(epochNumber: number): Promise<TipSet> {
const ret: TipSet = await this.client.chain.getTipSetByHeight(epochNumber);
return ret;
}
/**
* reads ipld nodes referenced by the specified CID from chain blockstore and returns raw bytes.
* @param cid
*/
public async readObj(cid: Cid): Promise<string> {
const ret = await this.client.chain.readObj(cid);
return ret as string;
}
/**
* checks if a given CID exists in the chain blockstore
* @param cid
*/
public async hasObj(cid: Cid): Promise<boolean> {
const ret = await this.client.chain.hasObj(cid);
return ret as boolean;
}
/**
* returns statistics about the graph referenced by 'obj'.
*
* @remarks
* If 'base' is also specified, then the returned stat will be a diff between the two objects.
*/
public async statObj(obj: Cid, base?: Cid): Promise<ObjStat> {
const stat: ObjStat = await this.client.chain.statObj(obj, base);
return stat;
}
/**
* Returns the genesis tipset.
* @param tipSet
*/
public async getGenesis(): Promise<TipSet> {
const genesis: TipSet = await this.client.chain.getGenesis();
return genesis;
}
// TODO: Go API method signature returns BigInt. Replace string with BN
/**
* Computes weight for the specified tipset.
* @param tipSetKey
*/
public async getTipSetWeight(tipSetKey?: TipSetKey): Promise<string> {
const weight: string = await this.client.chain.getTipSetWeight(tipSetKey);
return weight;
}
/**
* reads a message referenced by the specified CID from the chain blockstore
* @param messageCid
*/
public async getMessage(messageCid: Cid): Promise<Message> {
const ret = await this.client.chain.getMessage(messageCid);
return ret as Message;
}
/**
* Returns a set of revert/apply operations needed to get from
* @param from
* @param to
*/
public async getPath(from: TipSetKey, to: TipSetKey): Promise<HeadChange[]> {
const path: HeadChange[] = await this.client.chain.getPath(from, to);
return path;
}
//Sync methods
/**
* returns the current status of the lotus sync system.
*/
public async state(): Promise<SyncState> {
const state: SyncState = await this.client.sync.state();
return state;
}
/**
* returns a channel streaming incoming, potentially not yet synced block headers.
* @param cb
*/
public async incomingBlocks(cb: (blockHeader: BlockHeader) => void) {
await this.client.sync.incomingBlocks(cb);
}
//Mpool methods
/**
* get all mpool messages
* @param tipSetKey
*/
public async getMpoolPending(tipSetKey: TipSetKey): Promise<[SignedMessage]> {
const ret = await this.client.mpool.getMpoolPending(tipSetKey);
return ret;
}
/**
* returns a list of pending messages for inclusion in the next block
* @param tipSetKey
* @param ticketQuality
*/
public async sub(cb: (data: MpoolUpdate) => void) {
await this.client.mpool.sub(cb);
}
//Client methods
/**
* returns a signed StorageAsk from the specified miner.
* @param peerId
* @param miner
*/
public async queryAsk(peerId: PeerID, miner: Address): Promise<StorageAsk> {
const queryAsk: StorageAsk = await this.client.client.queryAsk(peerId, miner);
return queryAsk;
}
//State methods
/**
* returns the indicated actor's nonce and balance
* @param address
* @param tipSetKey
*/
public async getActor(address: string, tipSetKey?: TipSetKey): Promise<Actor> {
const data = await this.client.state.getActor(address, tipSetKey);
return data as Actor;
}
/**
* returns the indicated actor's state
* @param address
* @param tipSetKey
*/
public async readState(address: string, tipSetKey?: TipSetKey): Promise<ActorState> {
const data = await this.client.state.readState(address, tipSetKey);
return data as ActorState;
}
/**
* looks back and returns all messages with a matching to or from address, stopping at the given height.
* @param filter
* @param tipSetKey
* @param toHeight
*/
public async listMessages(filter: { To?: string, From?: string }, tipSetKey?: TipSetKey, toHeight?: number): Promise<Cid[]> {
const messages: Cid[] = await this.client.state.listMessages(filter, tipSetKey, toHeight);
return messages ? messages : [];
}
/**
* returns the name of the network the node is synced to
*/
public async networkName(): Promise<NetworkName> {
const network: string = await this.client.state.networkName();
return network;
}
/**
* returns info about the given miner's sectors
* @param address
* @param tipSetKey
*/
public async minerSectors(address: string, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo[]> {
const sectorsInfo: SectorOnChainInfo[] = await this.client.state.minerSectors(address, tipSetKey);
return sectorsInfo;
}
/**
* returns info about sectors that a given miner is actively proving.
* @param address
* @param tipSetKey
*/
public async minerActiveSectors(address: string, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo[]> {
const activeSectors: SectorOnChainInfo[] = await this.minerActiveSectors(address, tipSetKey);
return activeSectors;
}
/**
* calculates the deadline at some epoch for a proving period and returns the deadline-related calculations.
* @param address
* @param tipSetKey
*/
public async minerProvingDeadline(address: string, tipSetKey?: TipSetKey): Promise<DeadlineInfo> {
const provingDeadline: DeadlineInfo = await this.client.state.minerProvingDeadline(address, tipSetKey);
return provingDeadline;
}
/**
* returns the power of the indicated miner
* @param address
* @param tipSetKey
*/
public async minerPower(address: string, tipSetKey?: TipSetKey): Promise<MinerPower> {
const power: MinerPower = await this.client.state.minerPower(address, tipSetKey);
return power;
}
/**
* returns info about the indicated miner
* @param address
* @param tipSetKey
*/
public async minerInfo(address: string, tipSetKey?: TipSetKey): Promise<MinerInfo> {
const minerInfo: MinerInfo = await this.client.state.minerInfo(address, tipSetKey);
return minerInfo;
}
/**
* returns all the proving deadlines for the given miner
* @param address
* @param tipSetKey
*/
public async minerDeadlines(address: string, tipSetKey?: TipSetKey): Promise<Deadline[]> {
const minerDeadlines: Deadline[] = await this.client.state.minerDeadlines(address, tipSetKey);
return minerDeadlines;
}
/**
* Loads miner partitions for the specified miner and deadline
* @param address
* @param idx
* @param tipSetKey
*/
public async minerPartitions(address: string, idx?: number, tipSetKey?: TipSetKey): Promise<Partition[]> {
const minerPartitions: Partition[] = await this.client.state.minerPartitions(address, idx, tipSetKey);
return minerPartitions;
}
/**
* Returns a bitfield indicating the faulty sectors of the given miner
* @param address
* @param tipSetKey
*/
public async minerFaults(address: string, tipSetKey?: TipSetKey): Promise<BitField> {
const minerFaults: BitField = await this.client.state.minerFaults(address, tipSetKey);
return minerFaults;
}
// TODO: This method is not working on Lotus. See issue here: https://github.com/filecoin-project/lotus/issues/3063
/**
* returns all non-expired Faults that occur within lookback epochs of the given tipset
* @param epoch
* @param tipSetKey
*/
public async allMinerFaults(epoch: ChainEpoch, tipSetKey?: TipSetKey): Promise<Fault[]> {
const allFaults: Fault[] = await this.client.state.allMinerFaults(epoch, tipSetKey);
return allFaults;
}
/**
* returns a bitfield indicating the recovering sectors of the given miner
* @param address
* @param tipSetKey
*/
public async minerRecoveries(address: string, tipSetKey?: TipSetKey): Promise<BitField> {
const recoveries: BitField = await this.client.state.minerRecoveries(address, tipSetKey);
return recoveries;
}
// TODO: this should be BigNumber instead of string
/**
* returns the precommit deposit for the specified miner's sector
* @param address
* @param sectorPreCommitInfo
* @param tipSetKey
*/
public async minerPreCommitDepositForPower(address: string, sectorPreCommitInfo: SectorPreCommitInfo, tipSetKey?: TipSetKey): Promise<string> {
const deposit: string = await this.client.state.minerPreCommitDepositForPower(address, sectorPreCommitInfo, tipSetKey);
return deposit;
}
/**
* returns the initial pledge collateral for the specified miner's sector
* @param address
* @param sectorPreCommitInfo
* @param tipSetKey
*/
public async minerInitialPledgeCollateral(address: string, sectorPreCommitInfo: SectorPreCommitInfo, tipSetKey?: TipSetKey): Promise<string> {
const deposit: string = await this.client.state.minerInitialPledgeCollateral(address, sectorPreCommitInfo, tipSetKey);
return deposit;
}
/**
* returns the portion of a miner's balance that can be withdrawn or spent
* @param address
* @param tipSetKey
*/
public async minerAvailableBalance(address: string, tipSetKey?: TipSetKey): Promise<string> {
const balance: string = await this.client.state.minerAvailableBalance(address, tipSetKey);
return balance;
}
/**
* returns the PreCommit info for the specified miner's sector
* @param address
* @param sector
* @param tipSetKey
*/
public async sectorPreCommitInfo(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorPreCommitOnChainInfo> {
const preCommitInfo: SectorPreCommitOnChainInfo = await this.client.state.sectorPreCommitInfo(address, sector, tipSetKey);
return preCommitInfo;
}
/**
* StateSectorGetInfo returns the on-chain info for the specified miner's sector
* @param address
* @param sector
* @param tipSetKey
*
* @remarks
* NOTE: returned Expiration may not be accurate in some cases, use StateSectorExpiration to get accurate expiration epoch
*/
public async sectorGetInfo(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorOnChainInfo> {
const sectorInfo: SectorOnChainInfo = await this.client.state.sectorGetInfo(address, sector, tipSetKey);
return sectorInfo;
}
/**
* returns epoch at which given sector will expire
* @param address
* @param sector
* @param tipSetKey
*/
public async sectorExpiration(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorExpiration> {
const sectorExpiration: SectorExpiration = await this.client.state.sectorExpiration(address, sector, tipSetKey);
return sectorExpiration;
}
/**
* finds deadline/partition with the specified sector
* @param address
* @param sector
* @param tipSetKey
*/
public async sectorPartition(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise<SectorLocation> {
const sectorLocation: SectorLocation = await this.client.state.sectorPartition(address, sector, tipSetKey);
return sectorLocation;
}
/**
* searches for a message in the chain and returns its receipt and the tipset where it was executed
* @param cid
*/
public async searchMsg(cid: Cid): Promise<MsgLookup> {
const lookup: MsgLookup = await this.client.state.searchMsg(cid);
return lookup;
}
/**
* returns the addresses of every miner that has claimed power in the Power Actor
* @param tipSetKey
*/
public async listMiners(tipSetKey?: TipSetKey): Promise<Address[]> {
const miners: Address[] = await this.client.state.listMiners(tipSetKey);
return miners;
}
/**
* returns the addresses of every actor in the state
* @param tipSetKey
*/
public async listActors(tipSetKey?: TipSetKey): Promise<Address[]> {
const miners: Address[] = await this.client.state.listActors(tipSetKey);
return miners;
}
/**
* looks up the Escrow and Locked balances of the given address in the Storage Market
* @param address
* @param tipSetKey
*/
public async marketBalance(address: Address, tipSetKey?: TipSetKey): Promise<MarketBalance> {
const marketBalance: MarketBalance = await this.client.state.marketBalance(address, tipSetKey);
return marketBalance;
}
/**
* returns the Escrow and Locked balances of every participant in the Storage Market
* @param tipSetKey
*/
public async marketParticipants(tipSetKey?: TipSetKey): Promise<{ [k: string]: MarketBalance }> {
const marketBalanceMap = await this.client.state.marketParticipants(tipSetKey);
return marketBalanceMap;
}
/**
* returns information about every deal in the Storage Market
* @param tipSetKey
*/
public async marketDeals(tipSetKey?: TipSetKey): Promise<{ [k: string]: MarketDeal }> {
const marketDealsMap = await this.client.state.marketDeals(tipSetKey);
return marketDealsMap;
}
/**
* returns information about the indicated deal
* @param dealId
* @param tipSetKey
*/
public async marketStorageDeal(dealId: DealID, tipSetKey?: TipSetKey): Promise<MarketDeal> {
const marketDeal: MarketDeal = await this.client.state.marketStorageDeal(dealId, tipSetKey);
return marketDeal;
}
/**
* retrieves the ID address of the given address
* @param address
* @param tipSetKey
*/
public async lookupId(address: Address, tipSetKey?: TipSetKey): Promise<Address> {
const id: Address = await this.client.state.lookupId(address, tipSetKey);
return id;
}
/**
* returns the public key address of the given ID address
* @param address
* @param tipSetKey
*/
public async accountKey(address: Address, tipSetKey?: TipSetKey): Promise<Address> {
const key: Address = await this.client.state.accountKey(address, tipSetKey);
return key;
}
/**
* returns all the actors whose states change between the two given state CIDs
* @param cid1
* @param cid2
*/
public async changedActors(cid1?: Cid, cid2?: Cid): Promise<{ [k: string]: Actor }> {
const actors = await this.client.state.changedActors(cid1, cid2);
return actors;
}
/**
* returns the message receipt for the given message
* @param cid
* @param tipSetKey
*/
public async getReceipt(cid: Cid, tipSetKey?: TipSetKey): Promise<MessageReceipt> {
const receipt = await this.client.state.getReceipt(cid, tipSetKey);
return receipt;
}
/**
* returns the number of sectors in a miner's sector set and proving set
* @param address
* @param tipSetKey
*/
public async minerSectorCount(address: Address, tipSetKey?: TipSetKey): Promise<MinerSectors> {
const sectors = await this.client.state.minerSectorCount(address, tipSetKey);
return sectors;
}
//Multisig wallet methods
/**
* returns the vesting details of a given multisig.
* @param address
* @param tipSetKey
*/
public async msigGetVestingSchedule(
address: string,
tipSetKey: TipSetKey,
): Promise<MsigVesting> {
const schedule = await this.client.msig.getVestingSchedule(address, tipSetKey);
return schedule;
}
/**
* returns the portion of a multisig's balance that can be withdrawn or spent
* @param address
* @param tipSetKey
*/
public async msigGetAvailableBalance(address: string, tipSetKey: TipSetKey): Promise<string> {
const ret = await this.client.msig.getAvailableBalance(address, tipSetKey);
return ret;
}
/**
* returns the amount of FIL that vested in a multisig in a certain period.
* @param address
* @param startEpoch
* @param endEpoch
*/
public async msigGetVested(address: string, startEpoch: TipSetKey, endEpoch: TipSetKey): Promise<string> {
const ret = await this.client.msig.getVested(address, startEpoch, endEpoch);
return ret;
}
} | the_stack |
import {
useRef,
useMemo,
useLayoutEffect,
useEffect,
useState,
createElement,
cloneElement,
forwardRef,
} from 'react';
import { findDOMNode } from 'react-dom';
import TweenOne, { Ticker } from 'tween-one';
import {
toArrayChildren,
findChildInChildrenByKey,
windowIsUndefined,
mergeChildren,
transformArguments,
} from './utils';
import AnimTypes from './animTypes';
import type { IObject, IProps, IKeys, IQueueType } from './type';
const noop = () => {};
export default forwardRef((props: IProps, ref: any) => {
const {
component = 'div',
componentProps = {},
interval = 100,
duration = 450,
delay = 0,
type = 'right',
animConfig = null,
ease = 'easeOutQuart',
leaveReverse = false,
forcedReplay = false,
animatingClassName = ['queue-anim-entering', 'queue-anim-leaving'],
onEnd = noop,
appear = true,
...tagProps
} = props;
/**
* @param childrenShow;
* 记录 animation 里是否需要 startAnim;
* 当前元素是否处在显示状态
* enterBegin 到 leaveComplete 之前都处于显示状态
*/
const childrenShow = useRef<IObject>({});
/**
* @param keysToEnter;
* 记录进场的 key;
*/
const keysToEnter = useRef<IKeys>([]);
const recordKeysToEnter = useRef<IKeys>([]);
/**
* @param keysToLeave;
* 记录出场的 key;
*/
const keysToLeave = useRef<IKeys>([]);
const recordKeysToLeave = useRef<IKeys>([]);
/**
* @param placeholderTimeoutIds;
* 进场时 deley 的 timeout 记录;
*/
const placeholderTimeoutIds = useRef<IObject>({});
/**
* @param childRefs;
* 储存 children 的 ref;
*/
const childRefs = useRef<IObject>({});
/**
* @param recordAnimKeys;
* 记录启动动画 key
*/
const recordAnimKeys = useRef<IObject>({});
/**
* @param recordAnimKeys;
* 记录启动动画 key
*/
const recordTweenKeys = useRef<IObject>({});
/**
* @param oneEnterBool
* 记录第一次进入
*/
const oneEnterBool = useRef(false);
const originalChildren = useRef<any[]>([]);
const [child, setChild] = useState<any[]>();
const [childShow, setChildShow] = useState<IObject>({});
const getTweenSingleConfig = (data: any, num: number, enterOrLeave?: 0 | 1) => {
const obj: IObject = {};
Object.keys(data).forEach((key) => {
if (Array.isArray(data[key])) {
obj[key] = data[key][num];
} else if ((!enterOrLeave && !num) || (enterOrLeave && num)) {
obj[key] = data[key];
}
});
return obj;
};
const getTweenAnimConfig = (data: any, num: number, enterOrLeave?: 0 | 1) => {
if (Array.isArray(data)) {
return data.map((item) => {
return getTweenSingleConfig(item, num, enterOrLeave);
});
}
return getTweenSingleConfig(data, num, enterOrLeave);
};
const getTweenType = ($type: IQueueType, num: number) => {
const data = AnimTypes[$type];
return getTweenAnimConfig(data, num);
};
const getAnimData = (key: string | number, i: number, enterOrLeave: 0 | 1, startOrEnd: 0 | 1) =>
/**
* transformArguments 第一个为 enter, 第二个为 leave;
* getTweenAnimConfig or getTweenType 第一个为到达的位置, 第二个为开始的位置。
* 用 tween-one 的数组来实现老的动画逻辑。。。
*/
animConfig
? getTweenAnimConfig(
transformArguments(animConfig, key, i)[enterOrLeave],
startOrEnd,
enterOrLeave,
)
: getTweenType(transformArguments(type, key, i)[enterOrLeave], startOrEnd);
const getTweenData = (key: string | number, i: number, $type: string) => {
const enterOrLeave = $type === 'enter' ? 0 : 1;
const start = $type === 'enter' ? 1 : 0;
const end = $type === 'enter' ? 0 : 1;
const animate = getAnimData(key, i, enterOrLeave, end);
const startAnim =
$type === 'enter' && (forcedReplay || !childrenShow.current[key])
? getAnimData(key, i, enterOrLeave, start)
: null;
let $ease = transformArguments(ease, key, i)[enterOrLeave];
const $duration = transformArguments(duration, key, i)[enterOrLeave];
if (Array.isArray(ease) && (ease.length > 2 || Array.isArray(ease[0]))) {
$ease = $ease.map((num: number) => num * 100);
$ease = `M0,100C${$ease[0]},${100 - $ease[1]},${$ease[2]},${100 - $ease[3]},100,0`;
}
return {
startAnim,
animate,
ease: $ease,
duration: $duration,
};
};
const enterBegin = (key: string | number, e: any) => {
const elem = e.targets;
elem.className = elem.className.replace(animatingClassName[1], '');
if (elem.className.indexOf(animatingClassName[0]) === -1) {
elem.className = `${elem.className} ${animatingClassName[0]}`.trim();
}
if (keysToEnter.current.indexOf(key) >= 0) {
keysToEnter.current.splice(keysToEnter.current.indexOf(key), 1);
}
childrenShow.current[key] = true;
};
const enterComplete = (key: string | number, e: any) => {
if (keysToLeave.current.indexOf(key) >= 0) {
return;
}
const elem = e.targets;
elem.className = elem.className.replace(animatingClassName[0], '').trim();
delete recordTweenKeys.current[key];
onEnd({ key, type: 'enter', target: elem });
};
const leaveBegin = (key: string | number, e: any) => {
const elem = e.targets;
elem.className = elem.className.replace(animatingClassName[0], '');
if (elem.className.indexOf(animatingClassName[1]) === -1) {
elem.className = `${elem.className} ${animatingClassName[1]}`.trim();
}
};
const leaveComplete = (key: string | number, e: any) => {
// 切换时同时触发 onComplete。 手动跳出。。。
toArrayChildren(props.children).findIndex((c) => c && c.key === key);
if (toArrayChildren(props.children).findIndex((c) => c && c.key === key) >= 0) {
return;
}
delete childrenShow.current[key];
delete recordTweenKeys.current[key];
originalChildren.current = originalChildren.current.filter((c) => c.key !== key);
// 这里不用启动动画,,直接删;
if (keysToLeave.current.indexOf(key) >= 0) {
keysToLeave.current.splice(keysToLeave.current.indexOf(key), 1);
}
const needLeave = keysToLeave.current.some((c) => childShow[c]);
if (!needLeave) {
const currentChildren = toArrayChildren(props.children);
setChild(currentChildren);
setChildShow({ ...childrenShow.current });
recordKeysToLeave.current.forEach((k) => {
delete recordAnimKeys.current[k];
});
}
const elem = e.targets;
elem.className = elem.className.replace(animatingClassName[1], '').trim();
onEnd({ key, type: 'leave', target: elem });
};
const performEnterBegin = (key: string | number) => {
childShow[key] = true;
Ticker.clear(placeholderTimeoutIds.current[key]);
delete placeholderTimeoutIds.current[key];
setChildShow({ ...childShow });
};
const performEnter = (key: string | number, i: number) => {
const $interval = transformArguments(interval, key, i)[0];
const $delay = transformArguments(delay, key, i)[0];
placeholderTimeoutIds.current[key] = Ticker.timeout(() => {
performEnterBegin(key);
}, $interval * i + $delay);
};
const performLeave = (key: string | number) => {
Ticker.clear(placeholderTimeoutIds.current[key]);
delete placeholderTimeoutIds.current[key];
};
const getTweenOneEnterOrLeave = (
key: string | number,
i: number,
$delay: number,
$type: string,
) => {
const animateData = getTweenData(key, i, $type);
const onStart = (e: any) => {
($type === 'enter' ? enterBegin : leaveBegin)(key, e);
};
const onComplete = (e: any) => {
($type === 'enter' ? enterComplete : leaveComplete)(key, e);
};
if (Array.isArray(animateData.animate)) {
const length = animateData.animate.length - 1;
const animation = animateData.animate.map((item, ii) => {
return {
...item,
startAt: animateData.startAnim ? animateData.startAnim[ii] : undefined,
duration: animateData.duration / length,
delay: !ii && $type === 'leave' ? $delay : 0,
onStart: !ii ? onStart : undefined,
onComplete: ii === length ? onComplete : undefined,
};
});
return animation;
}
return {
...animateData.animate,
startAt: animateData.startAnim || undefined,
ease: animateData.ease,
duration: animateData.duration,
onStart,
onComplete,
delay: $delay,
};
};
useEffect(
() => () => {
Object.keys(recordTweenKeys.current).forEach((key) => {
const tween = recordTweenKeys.current[key];
if (!tween) {
return;
}
tween.kill();
});
},
[],
);
useEffect(() => {
const nextChildren = toArrayChildren(props.children).filter((c) => c);
const currentChildren = originalChildren.current.filter((item) => item);
const newChildren = mergeChildren(currentChildren, nextChildren);
const $keysToEnter: IKeys = [];
const $keysToLeave: IKeys = [];
if (!appear && !oneEnterBool.current) {
const $childShow: IObject = {};
newChildren.forEach((c: any) => {
if (!c || !c.key) {
return;
}
$childShow[c.key] = true;
});
originalChildren.current = newChildren;
childrenShow.current = { ...$childShow };
setChildShow($childShow);
} else {
// console.log(nextChildren, recordAnimKeys.current, keysToEnter.current, keysToLeave.current);
currentChildren.forEach((c) => {
if (!c) {
return;
}
const { key } = c;
const hasNext = findChildInChildrenByKey(nextChildren, key);
if (!hasNext && key) {
$keysToLeave.push(key);
Ticker.clear(placeholderTimeoutIds.current[key]);
delete placeholderTimeoutIds.current[key];
}
});
nextChildren.forEach((c: any) => {
if (!c) {
return;
}
const { key } = c;
const hasPrev = findChildInChildrenByKey(currentChildren, key);
// 如果 nextChildren 和当前的一致,且动画里是出场,改回进场;
if (
(!hasPrev && key) ||
((!recordAnimKeys.current[key] ||
recordAnimKeys.current[key] === 'leave' ||
keysToEnter.current.indexOf(key) >= 0) &&
$keysToLeave.indexOf(key) === -1)
) {
$keysToEnter.push(key);
}
});
}
// console.log('child update', $keysToEnter, $keysToLeave, newChildren);
keysToEnter.current = $keysToEnter;
// keysToEnter 在启动时就会删除;
recordKeysToEnter.current = [...$keysToEnter];
keysToLeave.current = $keysToLeave;
recordKeysToLeave.current = [...$keysToLeave];
// console.log($keysToEnter, $keysToLeave);
setChild(newChildren);
}, [props.children]);
useLayoutEffect(() => {
originalChildren.current = child || [];
if (appear || oneEnterBool.current) {
const $keysToEnter = [...keysToEnter.current];
const $keysToLeave = [...keysToLeave.current];
$keysToEnter.forEach(performEnter);
$keysToLeave.forEach(performLeave);
}
if (child) {
oneEnterBool.current = true;
}
}, [child]);
useLayoutEffect(() => {
if (child) {
child.forEach((item) => {
const { key } = item;
const dom = childRefs.current[key];
if (!dom) {
return;
}
let animation;
let index = keysToLeave.current.indexOf(key); // children.findIndex(c => c.key === key);
const $interval = transformArguments(interval, key, index);
const $delay = transformArguments(delay, key, index);
// 处理出场
if (index >= 0) {
if (recordAnimKeys.current[key] === 'leave') {
return;
}
const order = leaveReverse ? keysToLeave.current.length - index - 1 : index;
const d = $interval[1] * order + $delay[1];
animation = getTweenOneEnterOrLeave(key, index, d, 'leave');
recordAnimKeys.current[key] = 'leave';
} else {
if (recordAnimKeys.current[key] === 'enter' || keysToEnter.current.indexOf(key) === -1) {
return;
}
index = recordKeysToEnter.current.indexOf(key);
const d = $interval[0] * index + $delay[0];
// console.log(recordAnimKeys.current[key], dom);
animation = getTweenOneEnterOrLeave(
key,
index,
recordAnimKeys.current[key] === 'leave' ? d : 0,
'enter',
);
recordAnimKeys.current[key] = 'enter';
}
if (recordTweenKeys.current[key]) {
recordTweenKeys.current[key].kill();
}
if (forcedReplay) {
const anim = {
...(Array.isArray(animation) ? animation[0].startAt : animation.startAt),
type: 'set',
};
TweenOne(dom, { animation: anim });
}
recordTweenKeys.current[key] = TweenOne(dom, {
animation,
});
});
}
}, [childShow, child]);
return useMemo(() => {
// console.log('--------render--------', childShow);
if (windowIsUndefined) {
return createElement(component, { ...tagProps, ...componentProps, ref });
}
const childrenToRender = toArrayChildren(child).map((item) => {
if (!item || !item.key) {
return item;
}
return (
childShow[item.key] &&
cloneElement(item, {
ref: (c: any) => {
childRefs.current[item.key] = c instanceof Element ? c : findDOMNode(c);
if (!c) {
delete childRefs.current[item.key];
}
},
key: item.key,
})
);
});
const p = {
...tagProps,
...componentProps,
ref,
};
return createElement(component, p, childrenToRender);
}, [childShow, child]);
}); | the_stack |
import React from "react";
import quip from "quip-apps-api";
import quiptext from "quiptext";
import PropTypes from "prop-types";
import debounce from "lodash.debounce";
export const kDefaultColumnColors = [
quip.apps.ui.ColorMap.RED.KEY,
quip.apps.ui.ColorMap.YELLOW.KEY,
quip.apps.ui.ColorMap.BLUE.KEY,
quip.apps.ui.ColorMap.GREEN.KEY,
quip.apps.ui.ColorMap.ORANGE.KEY,
quip.apps.ui.ColorMap.VIOLET.KEY,
];
const ACTIVITY_LOG_MESSAGES = {
// TODO translate with quiptext if we reenable.
ADD_COLUMN: () => {
return "added a column.";
},
REMOVE_COLUMN: columnText => {
return `removed a column: "${columnText}".`;
},
ADD_CARD: () => {
return "added a card.";
},
REMOVE_CARD: cardText => {
return `removed a card: "${cardText}".`;
},
MOVE_CARD: (prevColumnName, nextColumnName) => {
return `moved a card from "${prevColumnName}" to "${nextColumnName}".`;
},
};
const newTitleText = quiptext("New Title");
const newCardText = quiptext("New Card");
export class BoardRecord extends quip.apps.RootRecord {
static getProperties() {
return {
columns: quip.apps.RecordList.Type(ColumnRecord),
// TODO(elsigh): why not just compute this?
nextColumnColor: "string",
};
}
static getDefaultProperties() {
return {columns: []};
}
static DATA_VERSION = 2;
initialize() {
this.get("columns").listen(() => this.notifyListeners());
this.listener = this.listen(this.setStatePayload_);
}
setStatePayload_ = debounce(() => {
if (typeof quip.apps.setPayload === "function") {
quip.apps.setPayload(this.getExportState());
}
}, 2000);
getColumns() {
return this.get("columns").getRecords();
}
addColumn(headerText) {
const color = this.getNextColumnColor_();
let index = this.get("columns").count();
let newColumn = this.get("columns").add({color}, index);
newColumn.addCard(true, headerText, 0);
newColumn.addCard(false, "", 1);
//quip.apps.sendMessage(ACTIVITY_LOG_MESSAGES.ADD_COLUMN());
quip.apps.recordQuipMetric("add_column");
return newColumn;
}
moveColumn(columnRecord, index) {
this.get("columns").move(columnRecord, index);
quip.apps.recordQuipMetric("move_column");
}
calculateHeight() {
let height = 0;
this.getColumns().forEach(column => {
height = Math.max(column.calculateHeight(), height);
});
return height;
}
getNextColumnColor_() {
const color = this.get("nextColumnColor") || kDefaultColumnColors[0];
const index = kDefaultColumnColors.indexOf(color);
const nextColor =
index === kDefaultColumnColors.length - 1
? kDefaultColumnColors[0]
: kDefaultColumnColors[index + 1];
this.set("nextColumnColor", nextColor);
return color;
}
getExportState(): String {
let columns = this.getColumns().map(column => {
return {
color: column.getColor(),
headerContent: column.getHeader().getTextContent(),
cards: column
.getCards()
.filter(card => !card.isHeader())
.map(card => {
return {
"color": card.getColor(),
"content": card.getTextContent(),
};
}),
};
});
return JSON.stringify({
columns,
});
}
populateColumns(columns: []): Array<ColumnRecord> {
columns.forEach(column => {
let newColumn = this.get("columns").add(
{color: column.color},
this.get("columns").count());
newColumn.addCard(true, column.headerContent, 0);
column.cards.forEach((card, index) => {
newColumn.addCard(false, card.content, index + 1, card.color);
});
});
quip.apps.recordQuipMetric("kanban_columns_populated");
return this.get("columns");
}
}
export class ColumnRecord extends quip.apps.Record {
static getProperties() {
return {
color: "string",
cards: quip.apps.RecordList.Type(CardRecord),
};
}
static getDefaultProperties() {
return {cards: []};
}
initialize() {
const listener = quip.apps
.getRootRecord()
.notifyListeners.bind(quip.apps.getRootRecord());
this.listen(listener);
this.get("cards").listen(listener);
}
getColor() {
return this.get("color");
}
setColor(color) {
quip.apps.recordQuipMetric("set_color");
this.set("color", color);
}
getCards() {
return this.get("cards").getRecords();
}
getHeader() {
const cards = this.getCards();
return cards.length > 0 ? cards[0] : null;
}
getFirstCard() {
const cards = this.getCards();
return cards.length ? cards[0] : null;
}
getLastCard() {
const cards = this.getCards();
return cards.length ? cards[cards.length - 1] : null;
}
addCard(isHeader, defaultText, index, color) {
let defaultPlaceholderText = isHeader ? newTitleText : newCardText;
quip.apps.recordQuipMetric("add_card");
return this.get("cards").add(
{
isHeader,
color,
RichText_defaultText: defaultText ? defaultText : null,
RichText_placeholderText: !defaultText
? defaultPlaceholderText
: null,
},
index);
}
insertCard(cardRecord, index) {
const prevColumnName = cardRecord
.getColumn()
.getHeader()
.getTextContent()
.trim();
this.get("cards").move(cardRecord, index);
const nextColumnName = cardRecord
.getColumn()
.getHeader()
.getTextContent()
.trim();
//quip.apps.sendMessage(
// ACTIVITY_LOG_MESSAGES.MOVE_CARD(prevColumnName, nextColumnName),
//);
quip.apps.recordQuipMetric("move_card");
}
moveCard(cardRecord, index) {
this.get("cards").move(cardRecord, index);
}
calculateHeight() {
let height = 0;
this.getCards().forEach(card => {
height += card.getHeight();
});
return height;
}
deleteColumn() {
/*quip.apps.sendMessage(
ACTIVITY_LOG_MESSAGES.REMOVE_COLUMN(
this.getHeader()
.getTextContent()
.trim(),
),
);*/
super.delete();
quip.apps.recordQuipMetric("delete_column");
}
getNextColumn() {
return this.getNextSibling();
}
getPreviousColumn() {
return this.getPreviousSibling();
}
}
ColumnRecord.CONSTRUCTOR_KEY = "kanban-column";
export class CardRecord extends quip.apps.RichTextRecord {
static getProperties() {
return {
isHeader: "boolean",
color: "string",
};
}
initialize() {
this.height = 0;
this.domNode = undefined;
this.commentsListener = this.listenToComments(this.notifyParent);
this.contentListener = this.listenToContent(this.notifyParent);
}
notifyParent = () => {
this.getParentRecord().notifyListeners();
};
getDom() {
return this.domNode;
}
supportsComments() {
return !this.isHeader();
}
isHeader() {
return this.get("isHeader");
}
getColor() {
return this.isHeader()
? undefined
: this.getIntrinsicColor() || this.getParentRecord().getColor();
}
getIntrinsicColor() {
return this.get("color");
}
setColor(color) {
if (!this.isHeader()) {
this.set("color", color);
}
}
clearColor() {
this.setColor(undefined);
}
getColumn() {
return this.getParentRecord();
}
getHeight() {
if (this.isHeader()) {
// All headers should match the height of the tallest header.
const headers = quip.apps
.getRootRecord()
.getColumns()
.map(column => column.getHeader());
return headers
.map(header => (header ? header.height : 0))
.reduce((height1, height2) => Math.max(height1, height2));
} else {
return this.height;
}
}
setHeight(height) {
this.height = height;
}
deleteCard() {
/*quip.apps.sendMessage(
ACTIVITY_LOG_MESSAGES.REMOVE_CARD(this.getTextContent().trim()),
);*/
if (this.commentsListener) {
this.unlistenToComments(this.notifyParent);
}
if (this.contentListener) {
this.unlistenToContent(this.notifyParent);
}
super.delete();
quip.apps.recordQuipMetric("delete_card");
}
getPreviousSibling() {
let prev = super.getPreviousSibling();
if (!prev) {
const previousColumn = this.getColumn().getPreviousSibling();
if (previousColumn) {
prev = previousColumn.getLastCard();
}
if (!prev) {
const cols = this.getColumn().getContainingList().getRecords();
prev = cols[cols.length - 1].getLastCard();
}
}
while (prev && prev.isHeader()) {
prev = prev.getPreviousSibling();
}
return prev;
}
getNextSibling() {
let next = super.getNextSibling();
if (!next) {
const nextColumn = this.getColumn().getNextSibling();
if (nextColumn) {
next = nextColumn.getHeader().getNextSibling();
}
if (!next) {
next = this.getColumn()
.getContainingList()
.getRecords()[0]
.getFirstCard();
}
}
while (next && next.isHeader()) {
next = next.getNextSibling();
}
return next;
}
}
CardRecord.CONSTRUCTOR_KEY = "kanban-card";
export function entityListener(WrappedComponent) {
return class RecordListenerComponent extends React.Component {
static propTypes = {
entity: PropTypes.instanceOf(quip.apps.Record),
};
componentDidMount() {
this.props.entity.listen(this.onRecordChange_);
}
componentWillUnmount() {
this.props.entity.unlisten(this.onRecordChange_);
}
render() {
return <WrappedComponent {...this.props}/>;
}
onRecordChange_ = () => {
this.forceUpdate();
};
};
} | the_stack |
import { BN } from "bn.js";
import * as testUtils from "./helper/testUtils";
import { RenExBrokerVerifierContract } from "./bindings/ren_ex_broker_verifier";
const {
RenExBrokerVerifier,
} = testUtils.contracts;
contract("RenExBalances", function (accounts: string[]) {
let renExBrokerVerifier: RenExBrokerVerifierContract;
before(async function () {
renExBrokerVerifier = await RenExBrokerVerifier.deployed();
});
it("can register and deregister brokers", async () => {
const broker1 = accounts[8];
const broker2 = accounts[9];
(await renExBrokerVerifier.brokerRegistered(broker1)).should.be.false;
(await renExBrokerVerifier.brokerRegistered(broker2)).should.be.false;
// Register first broker
await renExBrokerVerifier.registerBroker(broker1);
await renExBrokerVerifier.registerBroker(broker1)
.should.be.rejectedWith(null, /already registered/);
(await renExBrokerVerifier.brokerRegistered(broker1)).should.be.true;
(await renExBrokerVerifier.brokerRegistered(broker2)).should.be.false;
// Register second broker
await renExBrokerVerifier.registerBroker(broker2);
(await renExBrokerVerifier.brokerRegistered(broker1)).should.be.true;
(await renExBrokerVerifier.brokerRegistered(broker2)).should.be.true;
// Deregister first broker
await renExBrokerVerifier.deregisterBroker(broker1);
await renExBrokerVerifier.deregisterBroker(broker1)
.should.be.rejectedWith(null, /not registered/);
(await renExBrokerVerifier.brokerRegistered(broker1)).should.be.false;
(await renExBrokerVerifier.brokerRegistered(broker2)).should.be.true;
// Deregister second broker
await renExBrokerVerifier.deregisterBroker(broker2);
(await renExBrokerVerifier.brokerRegistered(broker1)).should.be.false;
(await renExBrokerVerifier.brokerRegistered(broker2)).should.be.false;
});
// Gets return value of transaction by doing a .call first
const callAndSend = async (
fn: { (...params: any[]): Promise<testUtils.Transaction>, call: (...params: any[]) => any },
params: any[]
): Promise<any> => {
const ret = (fn as any).call(...params);
await fn(...params);
return ret;
};
context("can verify withdraw signatures", async () => {
const trader1 = accounts[0];
const trader2 = accounts[3];
const trader3 = accounts[4];
const trader4 = accounts[5];
const notBalances = accounts[1]; // Not authorized to call `verifyWithdrawSignature`
const broker = accounts[8];
const notBroker = accounts[9];
let previousBalancesContract: string;
const token1 = testUtils.randomAddress();
const token2 = testUtils.randomAddress();
before(async () => {
previousBalancesContract = await renExBrokerVerifier.balancesContract();
await renExBrokerVerifier.updateBalancesContract(accounts[0]);
await renExBrokerVerifier.registerBroker(broker);
// Nonces should all be 0
(await renExBrokerVerifier.traderTokenNonce(trader1, token1)).should.bignumber.equal(0);
(await renExBrokerVerifier.traderTokenNonce(trader1, token2)).should.bignumber.equal(0);
(await renExBrokerVerifier.traderTokenNonce(trader2, token1)).should.bignumber.equal(0);
(await renExBrokerVerifier.traderTokenNonce(trader2, token2)).should.bignumber.equal(0);
});
after(async () => {
await renExBrokerVerifier.deregisterBroker(broker);
await renExBrokerVerifier.updateBalancesContract(previousBalancesContract);
});
it("can update RenEx Balances address", async () => {
const previousBalancesAddress = await renExBrokerVerifier.balancesContract();
// [CHECK] The function validates the new balances contract
await renExBrokerVerifier.updateBalancesContract(testUtils.NULL)
.should.be.rejectedWith(null, /revert/);
// [ACTION] Update the balances contract to another address
await renExBrokerVerifier.updateBalancesContract(renExBrokerVerifier.address);
// [CHECK] Verify the balances contract address has been updated
(await renExBrokerVerifier.balancesContract()).should.equal(renExBrokerVerifier.address);
// [CHECK] Only the owner can update the balances contract
await renExBrokerVerifier.updateBalancesContract(previousBalancesAddress, { from: accounts[1] })
.should.be.rejectedWith(null, /revert/); // not owner
// [RESET] Reset the balances contract to the previous address
await renExBrokerVerifier.updateBalancesContract(previousBalancesAddress);
(await renExBrokerVerifier.balancesContract()).should.equal(previousBalancesAddress);
});
it("only the balances contract can update the nonce", async () => {
const previousNonce = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token1));
// [ACTION] Attempt to verify signature
let signature = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader1, token1);
await renExBrokerVerifier.verifyWithdrawSignature(trader1, token1, signature, { from: notBalances })
.should.be.rejectedWith(null, /not authorized/);
// [CHECK] Nonce should not have increased
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce);
});
it("returns false for an invalid signature", async () => {
const previousNonce = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token1));
// [ACTION] Verify signature
let badSignature = await testUtils.signWithdrawal(renExBrokerVerifier, notBroker, trader1, token1);
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader1, token1, badSignature]))
.should.be.false;
// [CHECK] Nonce should not have increased
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce);
});
it("returns true and increments the nonce for a valid signature", async () => {
const previousNonce = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token1));
const previousNonceOtherToken = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token2));
const previousNonceOtherTrader = new BN(await renExBrokerVerifier.traderTokenNonce(trader2, token1));
// [ACTION] Verify signature
const fistSignature = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader1, token1);
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader1, token1, fistSignature]))
.should.be.true;
// [CHECK] trader1's nonce for token1 should have been incremented
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce.add(new BN(1)));
// [ACTION] Verify signature again
const secondSignature = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader1, token1);
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader1, token1, secondSignature]))
.should.be.true;
// [CHECK] trader1's nonce for token1 should have been incremented
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce.add(new BN(2)));
// [CHECK] Other nonces should not have changed
(await renExBrokerVerifier.traderTokenNonce(trader1, token2))
.should.bignumber.equal(previousNonceOtherToken);
(await renExBrokerVerifier.traderTokenNonce(trader2, token1))
.should.bignumber.equal(previousNonceOtherTrader);
});
it("returns false for an already-used signature", async () => {
// [SETUP] Create and use a signature
const signature = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader1, token1);
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader1, token1, signature]))
.should.be.true;
const previousNonce = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token1));
// [ACTION] Attempt to verify with already-used signature
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader1, token1, signature]))
.should.be.false;
// [CHECK] Nonce should be 1
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce);
});
it("can verify a second token", async () => {
const previousNonce = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token1));
const previousNonceOtherToken = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token2));
// [ACTION] Verify signature
let signature = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader1, token2);
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader1, token2, signature]))
.should.be.true;
// [CHECK] Nonce for first token should not have changed
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce);
// [CHECK] Nonce for the other token should have been incremented
(await renExBrokerVerifier.traderTokenNonce(trader1, token2))
.should.bignumber.equal(previousNonceOtherToken.add(new BN(1)));
});
it("can verify a second trader", async () => {
const previousNonce = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token1));
const previousNonceOtherTrader = new BN(await renExBrokerVerifier.traderTokenNonce(trader2, token1));
// [ACTION] Verify signature
let signature = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader2, token1);
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader2, token1, signature]))
.should.be.true;
// [CHECK] Nonce for first token should not have changed
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce);
// [CHECK] Nonce for the other token should have been incremented
(await renExBrokerVerifier.traderTokenNonce(trader2, token1))
.should.bignumber.equal(previousNonceOtherTrader.add(new BN(1)));
});
it("rejects a another trader's signature", async () => {
const previousNonce = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token1));
const previousNonceOtherTrader = new BN(await renExBrokerVerifier.traderTokenNonce(trader4, token1));
// [ACTION] Attempt to verify signature
let signature = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader4, token1);
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader3, token1, signature]))
.should.be.false;
// [CHECK] Neither nonce should have changed
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce);
(await renExBrokerVerifier.traderTokenNonce(trader4, token1))
.should.bignumber.equal(previousNonceOtherTrader);
});
it("rejects a another token's signature", async () => {
const previousNonce = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token1));
const previousNonceOtherToken = new BN(await renExBrokerVerifier.traderTokenNonce(trader1, token2));
// [ACTION] Attempt to verify signature
let signature = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader1, token1);
(await callAndSend(renExBrokerVerifier.verifyWithdrawSignature, [trader1, token2, signature]))
.should.be.false;
// [CHECK] Neither nonce should have changed
(await renExBrokerVerifier.traderTokenNonce(trader1, token1))
.should.bignumber.equal(previousNonce);
(await renExBrokerVerifier.traderTokenNonce(trader1, token2))
.should.bignumber.equal(previousNonceOtherToken);
});
});
}); | the_stack |
import {AptosClient, AptosAccount, FaucetClient, Types, HexString} from 'aptos';
import * as fs from 'fs';
import * as path from 'path';
import {Buffer} from 'buffer';
import {execSync} from "child_process";
import {chdir, cwd} from 'process';
const NODE_URL = "https://fullnode.devnet.aptoslabs.com";
const FAUCET_URL = "https://faucet.devnet.aptoslabs.com";
enum BoardType {
ACL = "ACLBasedMB",
CAP = "CapBasedMB"
}
class MessageboardUtil {
// generate txn payload for any script function
static getScriptFunctionTxnPayload(funcName: string, args: Types.MoveValue[]): Types.TransactionPayload {
const payload = {
type: "script_function_payload",
function: `${funcName}`,
type_arguments: [],
arguments: args
};
return payload;
}
// exec a transaction
static async executeTransaction(
client: AptosClient,
account: AptosAccount,
payload: Types.TransactionPayload
): Promise<Types.HexEncodedBytes> {
var txnRequest = await client.generateTransaction(account.address(), payload);
var signedTxn = await client.signTransaction(account, txnRequest);
var transactionRes = await client.submitTransaction(signedTxn);
await client.waitForTransaction(transactionRes.hash);
return transactionRes.hash;
}
// read the compiled mv move modules from specified path
static getCompiledModuleTxnPayload(dirPath: string, names: Set<string>): Types.TransactionPayload {
let files = [];
function visit_dir(d: string) {
fs.readdirSync(d).forEach(f => {
const a = path.join(d, f);
if (fs.statSync(a).isDirectory()) return visit_dir(a);
else {
if (names.has(path.basename(a))) {
files.push(a);
}
return;
}
});
}
visit_dir(dirPath);
console.log(files);
let modules = files.map(function (e) {
const moduleHex = fs.readFileSync(e).toString("hex");
return {"bytecode": `0x${moduleHex}`}
});
const payload: Types.TransactionPayload = {
type: "module_bundle_payload",
modules: modules,
};
return payload;
}
// publish the compiled modules to aptos devnet
static async installMessageboard(client: AptosClient, account: AptosAccount, modulePath: string) {
console.log("Install messageboard");
// publish the messageboard modules
var boardModules = new Set<string>();
boardModules.add("ACLBasedMB.mv");
boardModules.add("CapBasedMB.mv");
const boardModulePayload = MessageboardUtil.getCompiledModuleTxnPayload(modulePath, boardModules);
const hash = await MessageboardUtil.executeTransaction(client, account, boardModulePayload);
console.log(await client.getTransaction(hash));
}
}
class Messageboard {
boardType: BoardType;
client: AptosClient;
role: string;
adminAddr: HexString;
admin: AptosAccount;
contractAddr: HexString;
participants: Set<string>;
latestEvent: number;
claimedMessageCap: boolean; // this is only need for CAPMessageBoard
constructor(client: AptosClient, boardType: BoardType, admin: AptosAccount, contractAddr: HexString) {
this.boardType = boardType;
this.client = client;
this.admin = admin;
this.adminAddr = admin.address();
this.participants = new Set<string>();
this.contractAddr = contractAddr;
this.latestEvent = 0;
this.claimedMessageCap = false;
}
async createMessageboard(account: AptosAccount) {
console.log("creating message board");
var fname = `${this.contractAddr.toString()}::${this.boardType}::message_board_init`;
var args = [];
const initPayload = MessageboardUtil.getScriptFunctionTxnPayload(fname, args);
await MessageboardUtil.executeTransaction(this.client, account, initPayload);
}
async sendMessage(account: AptosAccount, message: string) {
var hexstring = Buffer.from(message).toString('hex');
console.log(`${account.address().toString()} sends message ${message} in the format of hex ${hexstring}`);
var args = [this.adminAddr.toString(), hexstring];
var fname = `${this.contractAddr.toString()}::${this.boardType}::send_message_to`;
await MessageboardUtil.executeTransaction(this.client,
account,
MessageboardUtil.getScriptFunctionTxnPayload(fname, args)
);
}
// different from sendMessage. this modify a pinned message resource stored on chain
async sendPinnedMessage(account: AptosAccount, message: string) {
var hexstring = Buffer.from(message).toString('hex');
console.log(`${account.address().toString()} sends pinned message ${message} in the format of hex ${hexstring}`);
var args = [this.adminAddr.toString(), hexstring];
var fname = `${this.contractAddr.toString()}::${this.boardType}::send_pinned_message`;
// verified if participant has capability to post message
if (this.boardType == BoardType.CAP && !this.claimedMessageCap) {
var cap_args = [this.adminAddr.toString()];
var cap_fname = `${this.contractAddr.toString()}::${this.boardType}::claim_notice_cap`;
await MessageboardUtil.executeTransaction(this.client,
account,
MessageboardUtil.getScriptFunctionTxnPayload(cap_fname, cap_args)
);
const res = await this.client.getAccountResources(account.address());
console.log(res);
const cap = res.find(
(r) =>
r.type === `${this.contractAddr.toString()}::${this.boardType}::MessageChangeCapability` &&
"board" in r.data
);
if (cap !== null && cap.data['board'] === this.adminAddr.toString()) {
this.claimedMessageCap = true;
}
}
await MessageboardUtil.executeTransaction(this.client,
account,
MessageboardUtil.getScriptFunctionTxnPayload(fname, args)
);
}
async viewMessageboardResource(): Promise<Types.AccountResource> {
const res = await this.client.getAccountResources(this.adminAddr)
console.log(res);
const accountResource = res.find(
(r) =>
r.type === `${this.contractAddr.toString()}::${this.boardType}::${this.boardType}`
);
return accountResource;
}
async getLatestBoardEvents(): Promise<Types.Event[]> {
console.log("getting latest events from messageboard");
var eventHandle = `${this.contractAddr.toString()}::${this.boardType}::MessageChangeEventHandle`;
// get the latest page of events
const params = {"start": this.latestEvent};
const resp = await this.client.getEventsByEventHandle(
this.adminAddr.toString(), eventHandle, 'change_events', params);
// record the last event seen
this.latestEvent = +resp[resp.length - 1].sequence_number;
return resp
}
async addParticipant(admin: AptosAccount, participant_addr: string) {
console.log("add participants to messageboard");
let args = [participant_addr];
let fname = `${this.contractAddr.toString()}::${this.boardType}::add_participant`;
const addParticipantPayload = MessageboardUtil.getScriptFunctionTxnPayload(fname, args);
await MessageboardUtil.executeTransaction(this.client, admin, addParticipantPayload);
this.participants.add(participant_addr);
}
async removeParticipant(admin: AptosAccount, participant_addr: string) {
console.log("remove participant from messageboard");
let args = [participant_addr];
let fname = `${this.contractAddr.toString()}::${this.boardType}::remove_participant`;
const removeParticipantPayload = MessageboardUtil.getScriptFunctionTxnPayload(fname, args);
await MessageboardUtil.executeTransaction(this.client, admin, removeParticipantPayload);
this.participants.delete(participant_addr);
}
}
(async () => {
const client = new AptosClient(NODE_URL);
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL, null);
// A smart contract developer compile and publish the modules
var fakeKey = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2];
var messageboardDev = new AptosAccount(new Uint8Array(fakeKey));
await faucetClient.fundAccount(messageboardDev.address(), 5000);
console.log("publishing the messageboard constract to ", messageboardDev.address().hex());
// compile the modules with the admin's address
chdir('../../../../aptos-move/move-examples/messageboard');
execSync(
`aptos move compile --package-dir . --named-addresses MessageBoard=${messageboardDev.address().toString()}`
);
console.log("current directory: ", cwd());
var module_path = "build/MessageBoard";
MessageboardUtil.installMessageboard(client, messageboardDev, module_path)
// The admin uses published contract to create their own messageboards
var fakeKey1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3];
var boardAdmin = new AptosAccount(new Uint8Array(fakeKey1));
var participant = new AptosAccount();
await faucetClient.fundAccount(boardAdmin.address(), 5000);
await faucetClient.fundAccount(participant.address(), 5000);
var board = new Messageboard(client, BoardType.CAP, boardAdmin, messageboardDev.address());
await board.createMessageboard(boardAdmin);
await board.sendMessage(boardAdmin, "Hello World");
console.log(await board.getLatestBoardEvents());
// board admin can add participants to the board
await board.addParticipant(boardAdmin, participant.address().toString());
// participant of the board can send messages
await board.sendMessage(participant, `Hey, I am ${participant.address().toString()}`);
console.log(await board.getLatestBoardEvents());
// participant with the authorization can modify the pinned message resource
await board.sendPinnedMessage(participant, `Group Notice: Have a good day`);
console.log(await board.getLatestBoardEvents());
// anyone can view the resource under an account
const aclboard = await board.viewMessageboardResource();
console.log(aclboard);
})(); | the_stack |
import * as React from 'react';
import * as ReactDom from 'react-dom';
import * as d3 from 'd3';
import * as math from 'mathjs';
import { OverViewProps, PathRegion, Helpable } from './Utils';
import * as FontAwesome from 'react-fontawesome';
import Selector from './ChromosomeSelector';
interface CircosViewState {
initialize: boolean;
chroms: any;
selector: boolean;
}
const MAXITEMS = 1500;
class CircosView extends React.Component<OverViewProps, CircosViewState>
implements Helpable {
constructor(props: OverViewProps) {
super(props);
this.state = { initialize: false, chroms: props.chroms, selector: false };
this._scaleLeft = this._scaleLeft.bind(this);
this._scaleRight = this._scaleRight.bind(this);
this._selectChrom = this._selectChrom.bind(this);
this._toggleSelector = this._toggleSelector.bind(this);
}
help() {
return (
<div>
<h3>Circos-plot</h3>
<p>
Twenty four arcs mean human chromosomes. The relation between the
chromosomes is expressed.
</p>
<p>Click on the arc to select the entire chromosome.</p>
<p>Click on the line between the arcs to select the feature.</p>
<p>Shown items are limited {MAXITEMS} at maximum.</p>
</div>
);
}
link() {
return 'circos-plot';
}
_toggleSelector() {
this.setState({ selector: !this.state.selector });
}
tooltip(feature: any) {
let tips = [
'Start: ' +
new PathRegion(feature.source_id, feature.source_breakpoint).toString(),
'End: ' +
new PathRegion(feature.target_id, feature.target_breakpoint).toString(),
'Priority: ' + feature.priority
];
if (feature.svtype !== undefined) {
tips.push('SVtype: ' + feature.svtype);
}
return tips;
}
drawCircos(features: any, chroms: any) {
// Initialize Informations
var chromsLen = chroms.map(function(k: any) {
return k.len;
});
var chromsName = chroms.map(function(k: any) {
return k.id;
});
var colors = chroms.map(function(k: any) {
return k.color;
});
var chordMatrix = math.diag(chromsLen);
var maxLen = Math.max.apply(null, chromsLen) / 10;
var ticks = maxLen.toExponential(0);
var groupTicks = function(d: any, step: any) {
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, step).map(function(value: number) {
return { value: value, angle: value * k + d.startAngle };
});
};
var svg = d3.select('#circos'),
width = +svg.attr('width'),
height = +svg.attr('height'),
outerRadius = Math.min(width, height) * 0.35,
innerRadius = outerRadius * 0.85;
var formatValue = d3.formatPrefix(',.0', Number(ticks));
var chord = d3
.chord()
.padAngle(0.025)
.sortSubgroups(d3.descending);
var arc = d3
.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var ribbon = d3.ribbon().radius(innerRadius);
var color = d3
.scaleOrdinal()
.domain(d3.range(colors.length).map(a => String(a)))
.range(colors);
var chordDatum = chord(chordMatrix);
svg.selectAll('g').remove();
var g = svg
.append('g')
.attr('transform', 'translate(' + width * 0.5 + ',' + height * 0.5 + ')')
.datum(chordDatum);
var group = g
.append('g')
.attr('class', 'groups')
.selectAll('g')
.data(function(chords: d3.Chords) {
return chords.groups;
})
.enter()
.append('g');
var fade = function(opacity: number) {
return function(d: any, i: number) {
d3.select(d3.event.currentTarget).style('fill-opacity', 1 - opacity);
ribbons
.filter(function(d2: any) {
return (
chromsName.indexOf(d2.source_id) !== i &&
chromsName.indexOf(d2.target_id) !== i
);
})
.style('opacity', opacity);
};
};
group
.append('path')
.style('stroke', function(d: d3.ChordGroup) {
return String(d3.rgb(String(color(String(d.index)))).darker());
})
.style('fill-opacity', function(d: any) {
return 0.5;
})
.style('fill', function(d: d3.ChordGroup) {
return String(d3.rgb(String(color(String(d.index)))));
})
.attr('d', arc as any)
.on('click', function(d: d3.ChordGroup, i: any) {
// Click a chromosome arc
_this.props.posUpdate(
[new PathRegion(chromsName[d.index], 0, chromsLen[d.index])],
null
);
})
.on(
'mouseover',
fade(0.1)
)
.on(
'mouseout',
fade(
0.5
)
);
group
.selectAll('.name')
.data(function(d: d3.ChordGroup) {
return [
{
index: chromsName[d.index],
angle: (d.startAngle + d.endAngle) / 2 - 0.05
}
];
})
.enter()
.append('g')
.attr('transform', function(d: any) {
return (
'rotate(' +
(d.angle * 180 / Math.PI - 90) +
') translate(' +
(outerRadius + 40) +
',0)'
);
})
.attr('x', 8)
.attr('dy', '.35em')
.append('text')
.text(function(d: any) {
return d.index;
})
.style('font-size', '11px')
.attr('transform', function(d: any) {
return 'rotate(' + 90 + ')';
});
var groupTick = group
.selectAll('.group-tick')
.data(function(d: d3.ChordGroup) {
return groupTicks(d, ticks);
})
.enter()
.append('g')
.attr('class', 'group-tick')
.attr('transform', function(d: any) {
return (
'rotate(' +
(d.angle * 180 / Math.PI - 90) +
') translate(' +
outerRadius +
',0)'
);
});
groupTick.append('line').attr('x2', 6);
groupTick
.filter(function(d: any) {
return d.value % (Number(ticks) * 5) === 0;
})
.append('text')
.attr('x', 8)
.attr('dy', '.35em')
.attr('transform', function(d: any) {
return d.angle > Math.PI ? 'rotate(180) translate(-16)' : null;
})
.style('text-anchor', function(d: any) {
return d.angle > Math.PI ? 'end' : null;
})
.style('font-size', '8px')
.text(function(d: any) {
return formatValue(d.value);
});
var connectionPointRadius = innerRadius;
var genomeToAngle = function(chromosome: number, position: number) {
var chrom = chromsName.indexOf(chromosome);
if (chrom !== -1) {
var chromPos = position / chordDatum.groups[chrom].value;
return (
(chordDatum.groups[chrom].endAngle -
chordDatum.groups[chrom].startAngle) *
chromPos +
chordDatum.groups[chrom].startAngle
);
}
};
var genomeToCircosX = function(chromosome: number, position: number) {
return Math.cos(genomeToAngle(chromosome, position) - Math.PI / 2);
};
var genomeToCircosY = function(chromosome: number, position: number) {
return Math.sin(genomeToAngle(chromosome, position) - Math.PI / 2);
};
var circosConnectionPathGenerator = function(d: any) {
var x1 =
connectionPointRadius *
genomeToCircosX(d.source_id, d.source_breakpoint),
y1 =
connectionPointRadius *
genomeToCircosY(d.source_id, d.source_breakpoint),
x2 =
connectionPointRadius *
genomeToCircosX(d.target_id, d.target_breakpoint),
y2 =
connectionPointRadius *
genomeToCircosY(d.target_id, d.target_breakpoint);
var xmid = (x1 + x2) / 3.5,
ymid = (y1 + y2) / 3.5; // The 2/3.5 of (O, the cener of (x1, x2))
return (
'M ' + x1 + ' ' + y1 + ' S ' + xmid + ' ' + ymid + ' ' + x2 + ' ' + y2
);
};
var tooltip = d3.select('#tooltip');
const filteredData = features
.filter(function(d2: any) {
return (
chromsName.indexOf(d2.source_id) !== -1 &&
chromsName.indexOf(d2.target_id) !== -1
);
})
.slice(0, MAXITEMS);
const _this = this;
var ribbons = g
.append('g')
.attr('class', 'path')
.selectAll('path.circos_connection')
.data(filteredData)
.enter()
.append('path')
.attr('class', 'circos_connection')
.attr('d', circosConnectionPathGenerator as any)
.style('opacity', 0.5)
.style('stroke-width', 2)
.style('stroke', function(d: any) {
var chromId = chromsName.indexOf(d.source_id);
return colors[chromId];
})
.style('fill', 'none')
.on('mouseover', function(d: any) {
return (tooltip
.style('visibility', 'visible')
.selectAll('tspan')
.data((() => _this.tooltip(d))())
.enter()
.append('tspan')
.text(function(d2: string) {
return d2;
}) );
})
.on('mousemove', function(d: any) {
return tooltip
.style('top', d3.event.pageY - 20 + 'px')
.style('left', d3.event.pageX + 10 + 'px');
})
.on('mouseout', function(d: any) {
return tooltip
.style('visibility', 'hidden')
.selectAll('tspan')
.remove();
})
.on('click', function(d: any, i: number) {
// Click a chromosome arc
const _false = false;
if (_false && d.hasOwnProperty('id')) {
_this.props.posUpdate(
[new PathRegion(d.id, null, null, false, [d.svtype, d.priority])],
i
);
} else {
if (d.source_id !== d.target_id) {
_this.props.posUpdate(
[
new PathRegion(
d.source_id,
d.source_breakpoint,
d.source_breakpoint,
true,
[d.svtype, d.priority]
),
new PathRegion(
d.target_id,
d.target_breakpoint,
d.target_breakpoint,
true,
[d.svtype, d.priority]
)
],
i
);
} else {
_this.props.posUpdate(
[
new PathRegion(
d.source_id,
d.source_breakpoint,
d.target_breakpoint,
true,
[d.svtype, d.priority]
)
],
i
);
}
}
});
}
componentDidMount() {
if (this.props.features && this.props.chroms) {
this.drawCircos(this.props.features, this.props.chroms);
this.setState({ initialize: true, chroms: this.props.chroms });
}
}
_scaleRight() {
if (this.props.features) {
let chroms = this.state.chroms;
const tail = chroms.pop();
chroms.unshift(tail);
this.setState({ chroms: chroms });
this.drawCircos(this.props.features, chroms);
}
}
_scaleLeft() {
if (this.props.features) {
let chroms = this.state.chroms;
const head = chroms.shift();
chroms.push(head);
this.setState({ chroms: chroms });
this.drawCircos(this.props.features, chroms);
}
}
_selectChrom(chromsLabel: string[]) {
if (chromsLabel.filter(a => a.length > 0).length > 0 && this.props.features) {
/*const chroms = chromsLabel.map(
a => this.props.chroms.find(b => b.label === a)
).filter(a => a !== null);*/
const chroms = this.props.chroms.filter(
a => chromsLabel.indexOf(a.label) !== -1
);
this.setState({
chroms: chroms
});
this.drawCircos(this.props.features, chroms);
}
}
componentWillReceiveProps(newProps: OverViewProps) {
if (
newProps.features &&
newProps.chroms &&
(this.props.features === undefined ||
newProps.features.length !== this.props.features.length)
) {
this.drawCircos(newProps.features, newProps.chroms);
this.setState({ initialize: true, chroms: newProps.chroms });
}
}
render() {
return (
<div id="circosWrapper">
<svg
width={this.props.width > 640 ? 640 : this.props.width}
height={this.props.width > 640 ? 640 : this.props.width}
id="circos"
/>
<div
className="form-group"
style={{
justifyContent: 'space-between',
display: 'flex'
}}>
<button
className="btn btn-outline-primary"
onClick={this._scaleLeft}
title="Turn clockwise">
{'<-'}
</button>
<button
className="btn btn-outline-secondary"
onClick={this._toggleSelector}
title="Select chromosomes to be shown">
{'Select Chromosomes'}
</button>
<button
className="btn btn-outline-primary"
onClick={this._scaleRight}
title="Turn counterclockwise">
{'->'}
</button>
</div>
{(() => {
if (this.state.selector) {
return (
<Selector
allChroms={this.props.chroms}
selectChrom={this._selectChrom}
/>
);
}
})()}
</div>
);
}
}
export default CircosView; | the_stack |
import { BotBehaviorConfig, BotConfig } from './models/config';
import { HttpService } from './services/http.service';
import { StorageService } from './services/storage.service';
import { Utils } from './modules/utils/utils';
import { MediaPost } from './models/post';
import { UserAccount } from './models/user-account';
import { IResult } from './models/http-result';
export class Instabot {
public apiService: HttpService;
public storageService: StorageService;
//region Config
/*username of the current logged in user*/
public username: string;
/*password of the current logged in user*/
public password: string;
/*userId of the current logged in user*/
public user_id: string;
/*actual bot configuration*/
public config: BotBehaviorConfig;
/*Default bot configuration*/
private defaultConfig: BotBehaviorConfig = {
botModes: 'like-classic-mode',
maxLikesPerDay: 1000,
maxDislikesPerDay: 0,
maxFollowsPerDay: 300,
maxUnfollowsPerDay: 300,
minUnfollowWaitTime: 1440, // minutes... -> 72 hours
minDislikeWaitTime: 1440, // minutes... -> 24 hours
maxFollowsPerHashtag: 20,
hashtags: ['follow4follow', 'f4f', 'beer', 'l4l', 'like4like'],
maxLikesPerHashtag: 50,
sleepStart: '0:00',
sleepEnd: '7:00',
waitTimeBeforeDelete: 10080, // minutes... -> 1 week
followerOptions: {
unwantedUsernames: [],
followFakeUsers: false,
followSelebgramUsers: false,
followPassiveUsers: false,
},
postOptions: {
maxLikesToLikeMedia: 600,
minLikesToLikeMedia: 5,
},
isTesting: false,
};
/*minimum sleeptime for the bot if an failed request response comes in*/
public readonly failedRequestSleepTime = 120; // in seconds
/*Maximum count of ban request responses*/
public banCountToBeBanned: number = 3;
/*Time to sleep in seconds when ban is active*/
public banSleepTime: number = 2 * 60 * 60;
//endregion
//region Internal Variables
/*If the bot has been logged in successfully*/
public isLoggedIn: boolean = false;
/*Count of the followed users in the current running day*/
public followCountCurrentDay: number = 0;
/*Count of the unfollowed users in the current running day*/
public unfollowCountCurrentDay: number = 0;
/*likes made in the current running day*/
public likesCountCurrentDay: number = 0;
/*dislikes made in the current running day*/
private dislikesCountCurrentDay: number = 0;
/*if initialisation was successful*/
private readonly canStart;
/*Count of possible ban request responses*/
private banCount: number = 0;
/*Tells if the bot has been banned*/
private isBanned: boolean = false;
//endregion
constructor(options: BotConfig) {
if (
options == null ||
options['username'] == null ||
options['password'] == null
) {
// incorrect config, required properties are probably missing
this.canStart = false;
return;
}
// required params exists
this.canStart = true;
this.username = options.username;
this.password = options.password;
this.config = {
...this.defaultConfig,
...options.config,
};
// only for testing purposes
if (this.config.isTesting === true) {
this.isLoggedIn = true;
}
this.apiService = new HttpService({
followerOptions: this.config.followerOptions,
postOptions: this.config.postOptions,
});
this.storageService = new StorageService({
waitTimeBeforeDeleteData: this.config.waitTimeBeforeDelete,
unfollowWaitTime: this.config.minUnfollowWaitTime,
});
Utils.writeLog(
'----------------------- INSTABOT JS -----------------------',
'START',
);
Utils.writeLog('Started the bot');
}
/**
* first method to call after constructor
* Tries to login the user and initializes everything to start to like and follow some stuff on insta (lol)
* */
public async initBot(): Promise<any> {
if (this.canStart !== true) {
return this.shutDown(
Utils.getShutdownMessage(
'Username or/and Password are missing. You need to provide your credentials inside the bot-config.json file!',
),
);
}
try {
this.collectPreviousData();
process.on('SIGINT', () => {
console.log('Trying to log out the bot, please wait...');
if (this.isLoggedIn === true) {
this.logout()
.then(() => {
Utils.writeLog('Logged out the bot successfully');
this.updateMessage(true);
this.shutDown();
})
.catch(err => {
Utils.writeLog(err);
this.updateMessage(true);
this.shutDown();
});
} else {
Utils.writeLog('Logged out the bot successfully');
this.updateMessage(true);
this.shutDown();
}
});
await this.login();
// register botsleep
await this.startSelectedMode();
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
}
public async startSelectedMode() {
const strategies = require('./modules/modes/strategies');
const modes = this.config.botModes.split(',');
await modes.forEach(modeName => {
const mode = strategies[modeName.trim()];
if (mode == null) {
Utils.writeLog(`startSelectedMode: mode ${modeName} does not exist`);
} else {
//start mode
new mode(this).start();
}
});
}
/**
* looking up all the stuff the bot already did today, then setting those values accordingly
* */
private collectPreviousData() {
const followers = this.storageService.getFollowers();
const likes = this.storageService.getLikes();
const dislikes = this.storageService.getDisLikes();
const unfollows = this.storageService.getUnfollowed();
const todayFollowers = Object.keys(followers).filter(key => {
try {
return (
new Date(followers[key]).setHours(0, 0, 0, 0) ==
new Date(Date.now()).setHours(0, 0, 0, 0)
);
} catch (e) {
return false;
}
});
const todayLikes = Object.keys(likes).filter(key => {
try {
return (
new Date(likes[key]).setHours(0, 0, 0, 0) ==
new Date(Date.now()).setHours(0, 0, 0, 0)
);
} catch (e) {
return false;
}
});
const todayDisLikes = Object.keys(dislikes).filter(key => {
try {
return (
new Date(dislikes[key]).setHours(0, 0, 0, 0) ==
new Date(Date.now()).setHours(0, 0, 0, 0)
);
} catch (e) {
return false;
}
});
const todayUnfollows = Object.keys(unfollows).filter(key => {
try {
return (
new Date(unfollows[key]).setHours(0, 0, 0, 0) ==
new Date(Date.now()).setHours(0, 0, 0, 0)
);
} catch (e) {
return false;
}
});
this.followCountCurrentDay = todayFollowers.length;
this.likesCountCurrentDay = todayLikes.length;
this.unfollowCountCurrentDay = todayUnfollows.length;
this.dislikesCountCurrentDay = todayDisLikes.length;
console.log(
'Already did today:',
'Follows:',
this.followCountCurrentDay,
'Likes:',
this.likesCountCurrentDay,
'Unfollows:',
this.unfollowCountCurrentDay,
'Dislikes:',
this.dislikesCountCurrentDay,
);
}
/**
* logs in the current user
* */
private login(): Promise<boolean> {
if (this.isLoggedIn === true) return Promise.resolve(true);
return new Promise((resolve, reject) => {
Utils.writeLog('trying to login as ' + this.username + '...', 'Login');
this.apiService
.getCsrfToken()
.then(result => {
this.isSuccess(result).then(success => {
if (success === false) {
return reject(
'Could not get CSRF-Token from Instagram... Is your IP blocked by Instagram ?',
);
}
Utils.writeLog('Successfully got the CSRF-Token', 'Login');
// successful request, got csrf
Utils.quickSleep().then(() => {
this.apiService
.login({
username: this.username,
password: this.password,
})
.then(result => {
this.isSuccess(result).then(success => {
if (success === false) {
return reject(
`Could not login with the provided credentials... Username: ${
this.username
} , Password: ${this.password}`,
);
}
Utils.writeLog('Only one step left...', 'Login');
// logged in successfully
Utils.quickSleep().then(() => {
this.apiService
.getUserInfo(this.username)
.then(result => {
// own user_id
this.isSuccess(result).then(success => {
if (success === false) {
return reject(
'Failed to get your profile information...',
);
} else {
this.user_id = result.data.user_id;
this.isLoggedIn = true;
Utils.writeLog('Login was successful', 'Login');
return resolve(true);
}
});
})
.catch(() => {
return reject(
'Could not get user info, couldnt login...',
);
});
}); // no catch needed for sleep
}); // no catch needed for isSuccess
})
.catch(err => {
return reject(err);
});
}); // no catch needed for sleep
});
})
.catch(err => {
return reject(err);
});
});
}
/**
* logs out the current user
* */
private logout(): Promise<boolean> {
if (this.isLoggedIn === false) {
return Promise.resolve(true);
}
return new Promise<boolean>((resolve, reject) => {
this.apiService
.logout()
.then(result => {
this.isSuccess(result).then(success => {
if (success === false) {
return reject('Could not logout of Instagram... ');
}
// success
this.isLoggedIn = false;
return resolve(true);
});
})
.catch(() => {
return reject('Could not logout of Instagram...');
});
});
}
/**
* Puts the bot into an bansleep mode
* */
private async startBanSleep(): Promise<any> {
if (this.banCount >= this.banCountToBeBanned) {
Utils.writeLog(
'Bot is probably getting banned, sleeping now for ' +
this.banSleepTime / 3600 +
'h',
'Ban',
);
this.isBanned = true;
this.banCount = 0;
await Utils.sleepSecs(this.banSleepTime);
this.isBanned = false;
return Promise.resolve();
} else {
return Promise.resolve();
}
}
/**
* private method to evaluate response result coming from the ApiService
* @param result, result coming from ApiService
* @returns Promise<boolean>
* */
public async isSuccess(result: IResult<any>): Promise<boolean> {
if (result.success !== true) {
// request wasnt successful
if (result.status >= 400 && result.status <= 403) {
this.banCount++;
Utils.writeLog(
'Request ended with status: ' +
result.status +
', Ban-Count is now on: ' +
this.banCount +
' of total: ' +
this.banCountToBeBanned +
', when reached, then bot will sleep for ' +
this.banSleepTime / 3600 +
' hours',
);
await this.startBanSleep();
return Promise.resolve(false);
} else {
await Utils.sleep();
return Promise.resolve(false);
}
} else {
// successful request
return Promise.resolve(true);
}
}
/**
* function to call when new post has been liked
* stores postid into storageApi
* */
public likedNewMedia(post: MediaPost, prefix: string) {
// save as liked
Utils.writeLog(
`Liked new post: https://www.instagram.com/p/${post.shortcode}`,
prefix,
);
this.likesCountCurrentDay++;
this.storageService.addLike(post.id);
this.updateMessage();
}
/**
* function to call when new user has been followed
* stores userId into storageApi
* */
public followedNewUser(user: UserAccount, prefix: string) {
// save as followed
Utils.writeLog(`Followed new user: ${user.username}`, prefix);
this.followCountCurrentDay++;
this.storageService.addFollower(user.user_id);
this.updateMessage();
}
/**
* function to call when new user has been unfollowed
* stores userId into storageApi
* */
public unfollowedNewUser(user: UserAccount, prefix: string) {
// save as unfollowed
Utils.writeLog(`Unfollowed user: username: ${user.user_id}`, prefix);
this.unfollowCountCurrentDay++;
this.storageService.unFollowed(user.user_id);
this.updateMessage();
}
/**
* function to call when new post has been disliked
* stores userId into storageApi
* */
private dislikedNewMedia(postId: string, prefix: string): void {
// save as disliked
Utils.writeLog(`Disliked new media: ID: ${postId}`, prefix);
this.dislikesCountCurrentDay++;
this.storageService.disLiked(postId);
this.updateMessage();
}
/**
* updates the message in the console
* */
private updateMessage(newLine: boolean = false) {
if (newLine === true) {
Utils.writeLog(
`Likes: ${this.storageService.getLikesLength()} / ${this.storageService.getDisLikesLength()}; Follows: ${this.storageService.getFollowersLength()} / ${this.storageService.getUnFollowsLength()};`,
);
} else {
Utils.writeProgress(
`Likes: ${this.storageService.getLikesLength()} / ${this.storageService.getDisLikesLength()}; Follows: ${this.storageService.getFollowersLength()} / ${this.storageService.getUnFollowsLength()};`,
);
}
}
/**
* selects an random hashtag of the hashtag-array of the config
* @returns hashtag as string
* */
public getRandomHashtag(): string {
return this.config.hashtags[
Utils.getRandomInt(0, this.config.hashtags.length - 1)
];
}
/**
* function to be called when a 'new day' starts for the bot
* */
private startNewDay() {
this.followCountCurrentDay = 0;
this.unfollowCountCurrentDay = 0;
this.likesCountCurrentDay = 0;
this.dislikesCountCurrentDay = 0;
this.storageService.cleanUp();
}
/**
* method to shutdown the bot (kills the node process)
* */
private async shutDown(message?: string) {
// sleeps just so all console logs on the end can be written,
// before the process gets killed
if (message) {
Utils.writeLog(message);
}
await Utils.sleepSecs(1);
process.exit();
}
public shouldBotSleep(now: Date): boolean {
const { nowHour, nowMinutes } = {
nowHour: Number(now.getHours()),
nowMinutes: Number(now.getMinutes()),
};
const { startHour, startMinutes } = {
startHour: Number(this.config.sleepStart.split(':')[0]),
startMinutes: Number(this.config.sleepStart.split(':')[1]),
};
const { endHour, endMinutes } = {
endHour: Number(this.config.sleepEnd.split(':')[0]),
endMinutes: Number(this.config.sleepEnd.split(':')[1]),
};
const shouldBotSleep =
nowHour >= startHour &&
nowHour * 60 + nowMinutes >= startHour * 60 + startMinutes &&
nowHour <= endHour &&
nowHour * 60 + nowMinutes <= endHour * 60 + endMinutes;
if (shouldBotSleep === true) {
// start new day bcs all functions are in the sleep mode
this.startNewDay();
}
// only merge them here so the day gets reset right
return shouldBotSleep || this.isBanned;
}
} | the_stack |
import { expect } from "chai";
import { BasicTests } from "test/helper/Basic";
import { connectTo } from "test/helper/Connect";
import { Offline } from "test/helper/Offline";
import { Envelope, EnvelopeCurve } from "./Envelope";
describe("Envelope", () => {
BasicTests(Envelope);
context("Envelope", () => {
it("has an output connections", () => {
const env = new Envelope();
env.connect(connectTo());
env.dispose();
});
it("can get and set values an Objects", () => {
const env = new Envelope();
const values = {
attack: 0,
decay: 0.5,
release: "4n",
sustain: 1,
};
env.set(values);
expect(env.get()).to.contain.keys(Object.keys(values));
env.dispose();
});
it("passes no signal before being triggered", () => {
return Offline(() => {
new Envelope().toDestination();
}).then((buffer) => {
expect(buffer.isSilent()).to.equal(true);
});
});
it("passes signal once triggered", () => {
return Offline(() => {
const env = new Envelope().toDestination();
env.triggerAttack(0.05);
}, 0.1).then((buffer) => {
expect(buffer.getTimeOfFirstSound()).to.be.closeTo(0.05, 0.001);
});
});
it("can take parameters as both an object and as arguments", () => {
const env0 = new Envelope({
attack: 0,
decay: 0.5,
sustain: 1,
});
expect(env0.attack).to.equal(0);
expect(env0.decay).to.equal(0.5);
expect(env0.sustain).to.equal(1);
env0.dispose();
const env1 = new Envelope(0.1, 0.2, 0.3);
expect(env1.attack).to.equal(0.1);
expect(env1.decay).to.equal(0.2);
expect(env1.sustain).to.equal(0.3);
env1.dispose();
});
it("ensures that none of the values go below 0", () => {
const env = new Envelope();
expect(() => {
env.attack = -1;
}).to.throw(RangeError);
expect(() => {
env.decay = -1;
}).to.throw(RangeError);
expect(() => {
env.sustain = 2;
}).to.throw(RangeError);
expect(() => {
env.release = -1;
}).to.throw(RangeError);
env.dispose();
});
it("can set attack to exponential or linear", () => {
const env = new Envelope(0.01, 0.01, 0.5, 0.3);
env.attackCurve = "exponential";
expect(env.attackCurve).to.equal("exponential");
env.triggerAttack();
env.dispose();
// and can be linear
const env2 = new Envelope(0.01, 0.01, 0.5, 0.3);
env2.attackCurve = "linear";
expect(env2.attackCurve).to.equal("linear");
env2.triggerAttack();
// and test a non-curve
expect(() => {
// @ts-ignore
env2.attackCurve = "other";
}).to.throw(Error);
env2.dispose();
});
it("can set decay to exponential or linear", () => {
const env = new Envelope(0.01, 0.01, 0.5, 0.3);
env.decayCurve = "exponential";
expect(env.decayCurve).to.equal("exponential");
env.triggerAttack();
env.dispose();
// and can be linear
const env2 = new Envelope(0.01, 0.01, 0.5, 0.3);
env2.decayCurve = "linear";
expect(env2.decayCurve).to.equal("linear");
env2.triggerAttack();
// and test a non-curve
expect(() => {
// @ts-ignore
env2.decayCurve = "other";
}).to.throw(Error);
env2.dispose();
});
it("can set release to exponential or linear", () => {
const env = new Envelope(0.01, 0.01, 0.5, 0.3);
env.releaseCurve = "exponential";
expect(env.releaseCurve).to.equal("exponential");
env.triggerRelease();
env.dispose();
// and can be linear
const env2 = new Envelope(0.01, 0.01, 0.5, 0.3);
env2.releaseCurve = "linear";
expect(env2.releaseCurve).to.equal("linear");
env2.triggerRelease();
// and test a non-curve
expect(() => {
// @ts-ignore
env2.releaseCurve = "other";
}).to.throw(Error);
env2.dispose();
});
it("can set release to exponential or linear", () => {
return Offline(() => {
const env = new Envelope({
release: 0
});
env.toDestination();
env.triggerAttackRelease(0.4, 0);
}, 0.7).then((buffer) => {
expect(buffer.getValueAtTime(0.3)).to.be.above(0);
expect(buffer.getValueAtTime(0.401)).to.equal(0);
});
});
it("schedule a release at the moment when the attack portion is done", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.5,
decay: 0.0,
sustain: 1,
release: 0.5
}).toDestination();
env.triggerAttackRelease(0.5);
}, 0.7).then((buffer) => {
// make sure that it's got the rising edge
expect(buffer.getValueAtTime(0.1)).to.be.closeTo(0.2, 0.01);
expect(buffer.getValueAtTime(0.2)).to.be.closeTo(0.4, 0.01);
expect(buffer.getValueAtTime(0.3)).to.be.closeTo(0.6, 0.01);
expect(buffer.getValueAtTime(0.4)).to.be.closeTo(0.8, 0.01);
expect(buffer.getValueAtTime(0.5)).to.be.be.closeTo(1, 0.001);
});
});
it("correctly schedules an exponential attack", () => {
const e = {
attack: 0.01,
decay: 0.4,
release: 0.1,
sustain: 0.5,
};
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.attackCurve = "exponential";
env.toDestination();
env.triggerAttack(0);
}, 0.7).then((buffer) => {
buffer.forEachBetween((sample) => {
expect(sample).to.be.within(0, 1);
}, 0, e.attack);
buffer.forEachBetween((sample) => {
expect(sample).to.be.within(e.sustain - 0.001, 1);
}, e.attack, e.attack + e.decay);
buffer.forEachBetween((sample) => {
expect(sample).to.be.closeTo(e.sustain, 0.01);
}, e.attack + e.decay);
});
});
it("correctly schedules a linear release", () => {
const e = {
attack: 0.01,
decay: 0.4,
release: 0.1,
sustain: 0.5,
};
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.attackCurve = "exponential";
env.toDestination();
env.triggerAttack(0);
}, 0.7).then((buffer) => {
buffer.forEachBetween((sample, time) => {
const target = 1 - (time - 0.2) * 10;
expect(sample).to.be.closeTo(target, 0.01);
}, 0.2, 0.2);
});
});
it("correctly schedules a linear decay", () => {
const e = {
attack: 0.1,
decay: 0.5,
release: 0.1,
sustain: 0,
};
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.decayCurve = "linear";
env.toDestination();
env.triggerAttack(0);
}, 0.7).then((buffer) => {
expect(buffer.getValueAtTime(0.05)).to.be.closeTo(0.5, 0.01);
expect(buffer.getValueAtTime(0.1)).to.be.closeTo(1, 0.01);
expect(buffer.getValueAtTime(0.2)).to.be.closeTo(0.8, 0.01);
expect(buffer.getValueAtTime(0.3)).to.be.closeTo(0.6, 0.01);
expect(buffer.getValueAtTime(0.4)).to.be.closeTo(0.4, 0.01);
expect(buffer.getValueAtTime(0.5)).to.be.closeTo(0.2, 0.01);
expect(buffer.getValueAtTime(0.6)).to.be.closeTo(0, 0.01);
});
});
it("correctly schedules an exponential decay", () => {
const e = {
attack: 0.1,
decay: 0.5,
release: 0.1,
sustain: 0,
};
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.decayCurve = "exponential";
env.toDestination();
env.triggerAttack(0);
}, 0.7).then((buffer) => {
expect(buffer.getValueAtTime(0.1)).to.be.closeTo(1, 0.01);
expect(buffer.getValueAtTime(0.2)).to.be.closeTo(0.27, 0.01);
expect(buffer.getValueAtTime(0.3)).to.be.closeTo(0.07, 0.01);
expect(buffer.getValueAtTime(0.4)).to.be.closeTo(0.02, 0.01);
expect(buffer.getValueAtTime(0.5)).to.be.closeTo(0.005, 0.01);
expect(buffer.getValueAtTime(0.6)).to.be.closeTo(0, 0.01);
});
});
it("can schedule a very short attack", () => {
const e = {
attack: 0.001,
decay: 0.01,
release: 0.1,
sustain: 0.1,
};
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.attackCurve = "exponential";
env.toDestination();
env.triggerAttack(0);
}, 0.2).then((buffer) => {
buffer.forEachBetween((sample) => {
expect(sample).to.be.within(0, 1);
}, 0, e.attack);
buffer.forEachBetween((sample) => {
expect(sample).to.be.within(e.sustain - 0.001, 1);
}, e.attack, e.attack + e.decay);
buffer.forEachBetween((sample) => {
expect(sample).to.be.closeTo(e.sustain, 0.01);
}, e.attack + e.decay);
});
});
it("can schedule an attack of time 0", () => {
return Offline(() => {
const env = new Envelope(0, 0.1);
env.toDestination();
env.triggerAttack(0.1);
}, 0.2).then((buffer) => {
expect(buffer.getValueAtTime(0)).to.be.closeTo(0, 0.001);
expect(buffer.getValueAtTime(0.0999)).to.be.closeTo(0, 0.001);
expect(buffer.getValueAtTime(0.1)).to.be.closeTo(1, 0.001);
});
});
it("correctly schedule a release", () => {
const e = {
attack: 0.001,
decay: 0.01,
release: 0.3,
sustain: 0.5,
};
const releaseTime = 0.2;
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.attackCurve = "exponential";
env.toDestination();
env.triggerAttackRelease(releaseTime);
}, 0.6).then((buffer) => {
const sustainStart = e.attack + e.decay;
const sustainEnd = sustainStart + releaseTime;
buffer.forEachBetween((sample) => {
expect(sample).to.be.below(e.sustain + 0.01);
}, sustainStart, sustainEnd);
buffer.forEachBetween((sample) => {
expect(sample).to.be.closeTo(0, 0.01);
}, releaseTime + e.release);
});
});
it("can retrigger a short attack at the same time as previous release", () => {
return Offline(() => {
const env = new Envelope(0.001, 0.1, 0.5);
env.attackCurve = "linear";
env.toDestination();
env.triggerAttack(0);
env.triggerRelease(0.4);
env.triggerAttack(0.4);
}, 0.6).then(buffer => {
expect(buffer.getValueAtTime(0.4)).be.closeTo(0.5, 0.01);
expect(buffer.getValueAtTime(0.40025)).be.closeTo(0.75, 0.01);
expect(buffer.getValueAtTime(0.4005)).be.closeTo(1, 0.01);
});
});
it("is silent before and after triggering", () => {
const e = {
attack: 0.001,
decay: 0.01,
release: 0.3,
sustain: 0.5,
};
const releaseTime = 0.2;
const attackTime = 0.1;
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.attackCurve = "exponential";
env.toDestination();
env.triggerAttack(attackTime);
env.triggerRelease(releaseTime);
}, 0.6).then((buffer) => {
expect(buffer.getValueAtTime(attackTime - 0.001)).to.equal(0);
expect(buffer.getValueAtTime(e.attack + e.decay + releaseTime + e.release)).to.be.below(0.01);
});
});
it("is silent after decay if sustain is 0", () => {
const e = {
attack: 0.01,
decay: 0.04,
sustain: 0,
};
const attackTime = 0.1;
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain);
env.toDestination();
env.triggerAttack(attackTime);
}, 0.4).then((buffer) => {
buffer.forEach((sample, time) => {
expect(buffer.getValueAtTime(attackTime - 0.001)).to.equal(0);
expect(buffer.getValueAtTime(attackTime + e.attack + e.decay)).to.be.below(0.01);
});
});
});
it("correctly schedule an attack release envelope", () => {
const e = {
attack: 0.08,
decay: 0.2,
release: 0.2,
sustain: 0.1,
};
const releaseTime = 0.4;
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.toDestination();
env.triggerAttack(0);
env.triggerRelease(releaseTime);
}).then((buffer) => {
buffer.forEach((sample, time) => {
if (time < e.attack) {
expect(sample).to.be.within(0, 1);
} else if (time < e.attack + e.decay) {
expect(sample).to.be.within(e.sustain, 1);
} else if (time < releaseTime) {
expect(sample).to.be.closeTo(e.sustain, 0.1);
} else if (time < releaseTime + e.release) {
expect(sample).to.be.within(0, e.sustain + 0.01);
} else {
expect(sample).to.be.below(0.0001);
}
});
});
});
it("can schedule a combined AttackRelease", () => {
const e = {
attack: 0.1,
decay: 0.2,
release: 0.1,
sustain: 0.35,
};
const releaseTime = 0.4;
const duration = 0.4;
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.toDestination();
env.triggerAttack(0);
env.triggerRelease(releaseTime);
}, 0.7).then((buffer) => {
buffer.forEach((sample, time) => {
if (time < e.attack) {
expect(sample).to.be.within(0, 1);
} else if (time < e.attack + e.decay) {
expect(sample).to.be.within(e.sustain - 0.001, 1);
} else if (time < duration) {
expect(sample).to.be.closeTo(e.sustain, 0.1);
} else if (time < duration + e.release) {
expect(sample).to.be.within(0, e.sustain + 0.01);
} else {
expect(sample).to.be.below(0.0015);
}
});
});
});
it("can schedule a combined AttackRelease with velocity", () => {
const e = {
attack: 0.1,
decay: 0.2,
release: 0.1,
sustain: 0.35,
};
const releaseTime = 0.4;
const duration = 0.4;
const velocity = 0.4;
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.toDestination();
env.triggerAttack(0, velocity);
env.triggerRelease(releaseTime);
}, 0.7).then((buffer) => {
buffer.forEach((sample, time) => {
if (time < e.attack) {
expect(sample).to.be.within(0, velocity + 0.01);
} else if (time < e.attack + e.decay) {
expect(sample).to.be.within(e.sustain * velocity - 0.01, velocity + 0.01);
} else if (time < duration) {
expect(sample).to.be.closeTo(e.sustain * velocity, 0.1);
} else if (time < duration + e.release) {
expect(sample).to.be.within(0, e.sustain * velocity + 0.01);
} else {
expect(sample).to.be.below(0.01);
}
});
});
});
it("can schedule multiple envelopes", () => {
const e = {
attack: 0.1,
decay: 0.2,
release: 0.1,
sustain: 0.0,
};
return Offline(() => {
const env = new Envelope(e.attack, e.decay, e.sustain, e.release);
env.toDestination();
env.triggerAttack(0);
env.triggerAttack(0.5);
}, 0.85).then((buffer) => {
// first trigger
expect(buffer.getValueAtTime(0)).to.be.closeTo(0, 0.01);
expect(buffer.getValueAtTime(0.1)).to.be.closeTo(1, 0.01);
expect(buffer.getValueAtTime(0.3)).to.be.closeTo(0, 0.01);
// second trigger
expect(buffer.getValueAtTime(0.5)).to.be.closeTo(0, 0.01);
expect(buffer.getValueAtTime(0.6)).to.be.closeTo(1, 0.01);
expect(buffer.getValueAtTime(0.8)).to.be.closeTo(0, 0.01);
});
});
it("can schedule multiple attack/releases with no discontinuities", () => {
return Offline(() => {
const env = new Envelope(0.1, 0.2, 0.2, 0.4).toDestination();
env.triggerAttackRelease(0, 0.4);
env.triggerAttackRelease(0.4, 0.11);
env.triggerAttackRelease(0.45, 0.1);
env.triggerAttackRelease(1.1, 0.09);
env.triggerAttackRelease(1.5, 0.3);
env.triggerAttackRelease(1.8, 0.29);
}, 2).then((buffer) => {
// test for discontinuities
let lastSample = 0;
buffer.forEach((sample, time) => {
expect(sample).to.be.at.most(1);
const diff = Math.abs(lastSample - sample);
expect(diff).to.be.lessThan(0.001);
lastSample = sample;
});
});
});
it("can schedule multiple 'linear' attack/releases with no discontinuities", () => {
return Offline(() => {
const env = new Envelope(0.1, 0.2, 0.2, 0.4).toDestination();
env.attackCurve = "linear";
env.releaseCurve = "linear";
env.triggerAttackRelease(0, 0.4);
env.triggerAttackRelease(0.4, 0.11);
env.triggerAttackRelease(0.45, 0.1);
env.triggerAttackRelease(1.1, 0.09);
env.triggerAttackRelease(1.5, 0.3);
env.triggerAttackRelease(1.8, 0.29);
}, 2).then((buffer) => {
// test for discontinuities
let lastSample = 0;
buffer.forEach((sample, time) => {
expect(sample).to.be.at.most(1);
const diff = Math.abs(lastSample - sample);
expect(diff).to.be.lessThan(0.001);
lastSample = sample;
});
});
});
it("can schedule multiple 'exponential' attack/releases with no discontinuities", () => {
return Offline(() => {
const env = new Envelope(0.1, 0.2, 0.2, 0.4).toDestination();
env.attackCurve = "exponential";
env.releaseCurve = "exponential";
env.triggerAttackRelease(0, 0.4);
env.triggerAttackRelease(0.4, 0.11);
env.triggerAttackRelease(0.45, 0.1);
env.triggerAttackRelease(1.1, 0.09);
env.triggerAttackRelease(1.5, 0.3);
env.triggerAttackRelease(1.8, 0.29);
}, 2).then((buffer) => {
// test for discontinuities
let lastSample = 0;
buffer.forEach((sample, time) => {
expect(sample).to.be.at.most(1);
const diff = Math.abs(lastSample - sample);
expect(diff).to.be.lessThan(0.0035);
lastSample = sample;
});
});
});
it("can schedule multiple 'sine' attack/releases with no discontinuities", () => {
return Offline(() => {
const env = new Envelope(0.1, 0.2, 0.2, 0.4).toDestination();
env.attackCurve = "sine";
env.releaseCurve = "sine";
env.triggerAttackRelease(0, 0.4);
env.triggerAttackRelease(0.4, 0.11);
env.triggerAttackRelease(0.45, 0.1);
env.triggerAttackRelease(1.1, 0.09);
env.triggerAttackRelease(1.5, 0.3);
env.triggerAttackRelease(1.8, 0.29);
}, 2).then((buffer) => {
// test for discontinuities
let lastSample = 0;
buffer.forEach((sample, time) => {
expect(sample).to.be.at.most(1);
const diff = Math.abs(lastSample - sample);
expect(diff).to.be.lessThan(0.0035);
lastSample = sample;
});
});
});
it("can schedule multiple 'cosine' attack/releases with no discontinuities", () => {
return Offline(() => {
const env = new Envelope(0.1, 0.2, 0.2, 0.4).toDestination();
env.attackCurve = "cosine";
env.releaseCurve = "cosine";
env.triggerAttackRelease(0, 0.4);
env.triggerAttackRelease(0.4, 0.11);
env.triggerAttackRelease(0.45, 0.1);
env.triggerAttackRelease(1.1, 0.09);
env.triggerAttackRelease(1.5, 0.3);
env.triggerAttackRelease(1.8, 0.29);
}, 2).then((buffer) => {
// test for discontinuities
let lastSample = 0;
buffer.forEach((sample, time) => {
expect(sample).to.be.at.most(1);
const diff = Math.abs(lastSample - sample);
expect(diff).to.be.lessThan(0.002);
lastSample = sample;
});
});
});
it("reports its current envelope value (.value)", () => {
return Offline(() => {
const env = new Envelope(1, 0.2, 1).toDestination();
expect(env.value).to.be.closeTo(0, 0.01);
env.triggerAttack();
return (time) => {
expect(env.value).to.be.closeTo(time, 0.01);
};
}, 0.5);
});
it("can cancel a schedule envelope", () => {
return Offline(() => {
const env = new Envelope(0.1, 0.2, 1).toDestination();
env.triggerAttack(0.2);
env.cancel(0.2);
}, 0.3).then((buffer) => {
expect(buffer.isSilent()).to.be.true;
});
});
});
context("Attack/Release Curves", () => {
const envelopeCurves: EnvelopeCurve[] = ["linear", "exponential", "bounce", "cosine", "ripple", "sine", "step"];
it("can get set all of the types as the attackCurve", () => {
const env = new Envelope();
envelopeCurves.forEach(type => {
env.attackCurve = type;
expect(env.attackCurve).to.equal(type);
});
env.dispose();
});
it("can get set all of the types as the releaseCurve", () => {
const env = new Envelope();
envelopeCurves.forEach(type => {
env.releaseCurve = type;
expect(env.releaseCurve).to.equal(type);
});
env.dispose();
});
it("outputs a signal when the attack/release curves are set to 'bounce'", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.3,
attackCurve: "bounce",
decay: 0,
release: 0.3,
releaseCurve: "bounce",
sustain: 1,
}).toDestination();
env.triggerAttackRelease(0.3, 0.1);
}, 0.8).then((buffer) => {
buffer.forEachBetween((sample) => {
expect(sample).to.be.above(0);
}, 0.101, 0.7);
});
});
it("outputs a signal when the attack/release curves are set to 'ripple'", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.3,
attackCurve: "ripple",
decay: 0,
release: 0.3,
releaseCurve: "ripple",
sustain: 1,
}).toDestination();
env.triggerAttackRelease(0.3, 0.1);
}, 0.8).then((buffer) => {
buffer.forEachBetween((sample) => {
expect(sample).to.be.above(0);
}, 0.101, 0.7);
});
});
it("outputs a signal when the attack/release curves are set to 'sine'", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.3,
attackCurve: "sine",
decay: 0,
release: 0.3,
releaseCurve: "sine",
sustain: 1,
}).toDestination();
env.triggerAttackRelease(0.3, 0.1);
}, 0.8).then((buffer) => {
buffer.forEachBetween((sample) => {
expect(sample).to.be.above(0);
}, 0.101, 0.7);
});
});
it("outputs a signal when the attack/release curves are set to 'cosine'", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.3,
attackCurve: "cosine",
decay: 0,
release: 0.3,
releaseCurve: "cosine",
sustain: 1,
}).toDestination();
env.triggerAttackRelease(0.3, 0.1);
}, 0.8).then((buffer) => {
buffer.forEachBetween((sample) => {
expect(sample).to.be.above(0);
}, 0.101, 0.7);
});
});
it("outputs a signal when the attack/release curves are set to 'step'", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.3,
attackCurve: "step",
decay: 0,
release: 0.3,
releaseCurve: "step",
sustain: 1,
}).toDestination();
env.triggerAttackRelease(0.3, 0.1);
}, 0.8).then((buffer) => {
buffer.forEach((sample, time) => {
if (time > 0.3 && time < 0.5) {
expect(sample).to.be.above(0);
} else if (time < 0.1) {
expect(sample).to.equal(0);
}
});
});
});
it("outputs a signal when the attack/release curves are set to an array", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.3,
attackCurve: [0, 1, 0, 1],
decay: 0,
release: 0.3,
releaseCurve: [1, 0, 1, 0],
sustain: 1,
}).toDestination();
expect(env.attackCurve).to.deep.equal([0, 1, 0, 1]);
env.triggerAttackRelease(0.3, 0.1);
}, 0.8).then((buffer) => {
buffer.forEach((sample, time) => {
if (time > 0.4 && time < 0.5) {
expect(sample).to.be.above(0);
} else if (time < 0.1) {
expect(sample).to.equal(0);
}
});
});
});
it("can scale a velocity with a custom curve", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.3,
attackCurve: [0, 1, 0, 1],
decay: 0,
release: 0.3,
releaseCurve: [1, 0, 1, 0],
sustain: 1,
}).toDestination();
env.triggerAttackRelease(0.4, 0.1, 0.5);
}, 0.8).then((buffer) => {
buffer.forEach((sample) => {
expect(sample).to.be.at.most(0.51);
});
});
});
it("can render the envelope to a curve", async () => {
const env = new Envelope();
const curve = await env.asArray();
expect(curve.some(v => v > 0)).to.be.true;
curve.forEach(v => expect(v).to.be.within(0, 1));
env.dispose();
});
it("can render the envelope to an array with a given length", async () => {
const env = new Envelope();
const curve = await env.asArray(256);
expect(curve.length).to.equal(256);
env.dispose();
});
it("can retrigger partial envelope with custom type", () => {
return Offline(() => {
const env = new Envelope({
attack: 0.5,
attackCurve: "cosine",
decay: 0,
release: 0.5,
releaseCurve: "sine",
sustain: 1,
}).toDestination();
env.triggerAttack(0);
env.triggerRelease(0.2);
env.triggerAttack(0.5);
}, 1).then((buffer) => {
expect(buffer.getValueAtTime(0)).to.equal(0);
expect(buffer.getValueAtTime(0.1)).to.be.closeTo(0.32, 0.01);
expect(buffer.getValueAtTime(0.2)).to.be.closeTo(0.6, 0.01);
expect(buffer.getValueAtTime(0.3)).to.be.closeTo(0.53, 0.01);
expect(buffer.getValueAtTime(0.4)).to.be.closeTo(0.38, 0.01);
expect(buffer.getValueAtTime(0.5)).to.be.closeTo(0.2, 0.01);
expect(buffer.getValueAtTime(0.6)).to.be.closeTo(0.52, 0.01);
expect(buffer.getValueAtTime(0.7)).to.be.closeTo(0.78, 0.01);
expect(buffer.getValueAtTime(0.8)).to.be.closeTo(0.95, 0.01);
expect(buffer.getValueAtTime(0.9)).to.be.closeTo(1, 0.01);
});
});
});
}); | the_stack |
import { Bits } from "@siteimprove/alfa-bits";
import { Equatable } from "@siteimprove/alfa-equatable";
import { Functor } from "@siteimprove/alfa-functor";
import { Iterable } from "@siteimprove/alfa-iterable";
import { Mapper } from "@siteimprove/alfa-mapper";
import { None, Option } from "@siteimprove/alfa-option";
import { Status } from "./status";
const { bit, take, skip, test, set, clear, popCount } = Bits;
/**
* Maps are stored as an hash-table of keys.
* The hash-table is stored as a tree where each internal node is a partial
* match of the hashes of its subtree.
*
* Nodes in the tree can be:
* * empty;
* * a Leaf, containing one single key;
* * a Collision, containing several keys with the same hash, this is
* effectively a leaf of the tree, even though it actually has several Leaf
* children (but no other kind);
* * a Sparse, which is an internal node. Sparses have masks and all hashes in
* this subtree share the same mask (partial hash collision). The matching of
* masks is done with a shift, which essentially take slices of n (=5) bits
* of the hash. The shift is automatically increased when looking down the
* tree, hence the same mask cannot be used at another level of a tree.
*/
/**
* @internal
*/
export interface Node<K, V> extends Functor<V>, Iterable<[K, V]>, Equatable {
isEmpty(): this is Empty;
isLeaf(): this is Leaf<K, V>;
get(key: K, hash: number, shift: number): Option<V>;
set(key: K, value: V, hash: number, shift: number): Status<Node<K, V>>;
delete(key: K, hash: number, shift: number): Status<Node<K, V>>;
map<U>(mapper: Mapper<V, U, [K]>): Node<K, U>;
}
/**
* @internal
*/
export namespace Node {
export const Bits = 5;
export function fragment(hash: number, shift: number): number {
return take(skip(hash, shift), Bits);
}
export function index(fragment: number, mask: number): number {
return popCount(take(mask, fragment));
}
}
/**
* @internal
*/
export interface Empty extends Node<never, never> {}
/**
* @internal
*/
export const Empty: Empty = new (class Empty {
public isEmpty(): this is Empty {
return true;
}
public isLeaf(): this is Leaf<never, never> {
return false;
}
public get(): None {
return None;
}
public set<K, V>(key: K, value: V, hash: number): Status<Node<K, V>> {
return Status.created(Leaf.of(hash, key, value));
}
public delete<K, V>(): Status<Node<K, V>> {
return Status.unchanged(this);
}
public map(): Empty {
return this;
}
public equals(value: unknown): value is this {
return value instanceof Empty;
}
public *[Symbol.iterator](): Iterator<never> {}
})();
/**
* @internal
*/
export class Leaf<K, V> implements Node<K, V> {
public static of<K, V>(hash: number, key: K, value: V): Leaf<K, V> {
return new Leaf(hash, key, value);
}
private readonly _hash: number;
private readonly _key: K;
private readonly _value: V;
private constructor(hash: number, key: K, value: V) {
this._hash = hash;
this._key = key;
this._value = value;
}
public get key(): K {
return this._key;
}
public get value(): V {
return this._value;
}
public isEmpty(): this is Empty {
return false;
}
public isLeaf(): this is Leaf<K, V> {
return true;
}
public get(key: K, hash: number, shift: number): Option<V> {
return hash === this._hash && Equatable.equals(key, this._key)
? Option.of(this._value)
: None;
}
public set(
key: K,
value: V,
hash: number,
shift: number
): Status<Node<K, V>> {
if (hash === this._hash) {
if (Equatable.equals(key, this._key)) {
if (Equatable.equals(value, this._value)) {
return Status.unchanged(this);
}
return Status.updated(Leaf.of(hash, key, value));
}
return Status.created(
Collision.of(hash, [this, Leaf.of(hash, key, value)])
);
}
const fragment = Node.fragment(this._hash, shift);
return Sparse.of(bit(fragment), [this]).set(key, value, hash, shift);
}
public delete(key: K, hash: number): Status<Node<K, V>> {
return hash === this._hash && Equatable.equals(key, this._key)
? Status.deleted(Empty)
: Status.unchanged(this);
}
public map<U>(mapper: Mapper<V, U, [K]>): Leaf<K, U> {
return Leaf.of(this._hash, this._key, mapper(this._value, this._key));
}
public equals(value: unknown): value is this {
return (
value instanceof Leaf &&
value._hash === this._hash &&
Equatable.equals(value._key, this._key) &&
Equatable.equals(value._value, this._value)
);
}
public *[Symbol.iterator](): Iterator<[K, V]> {
yield [this._key, this._value];
}
}
/**
* @internal
*/
export class Collision<K, V> implements Node<K, V> {
public static of<K, V>(
hash: number,
nodes: Array<Leaf<K, V>>
): Collision<K, V> {
return new Collision(hash, nodes);
}
private readonly _hash: number;
private readonly _nodes: Array<Leaf<K, V>>;
private constructor(hash: number, nodes: Array<Leaf<K, V>>) {
this._hash = hash;
this._nodes = nodes;
}
public isEmpty(): this is Empty {
return false;
}
public isLeaf(): this is Leaf<K, V> {
return false;
}
public get(key: K, hash: number, shift: number): Option<V> {
if (hash === this._hash) {
for (const node of this._nodes) {
const value = node.get(key, hash, shift);
if (value.isSome()) {
return value;
}
}
}
return None;
}
public set(
key: K,
value: V,
hash: number,
shift: number
): Status<Node<K, V>> {
if (hash === this._hash) {
for (let i = 0, n = this._nodes.length; i < n; i++) {
const node = this._nodes[i];
if (Equatable.equals(key, node.key)) {
if (Equatable.equals(value, node.value)) {
return Status.unchanged(this);
}
return Status.updated(
Collision.of(
this._hash,
replace(this._nodes, i, Leaf.of(hash, key, value))
)
);
}
}
return Status.created(
Collision.of(this._hash, this._nodes.concat(Leaf.of(hash, key, value)))
);
}
const fragment = Node.fragment(this._hash, shift);
return Sparse.of(bit(fragment), [this]).set(key, value, hash, shift);
}
public delete(key: K, hash: number): Status<Node<K, V>> {
if (hash === this._hash) {
for (let i = 0, n = this._nodes.length; i < n; i++) {
const node = this._nodes[i];
if (Equatable.equals(key, node.key)) {
const nodes = remove(this._nodes, i);
if (nodes.length === 1) {
// We just deleted the penultimate Leaf of the Collision, so we can
// remove the Collision and only keep the remaining Leaf.
return Status.deleted(nodes[0]);
}
return Status.deleted(Collision.of(this._hash, nodes));
}
}
}
return Status.unchanged(this);
}
public map<U>(mapper: Mapper<V, U, [K]>): Collision<K, U> {
return Collision.of(
this._hash,
this._nodes.map((node) => node.map(mapper))
);
}
public equals(value: unknown): value is this {
return (
value instanceof Collision &&
value._hash === this._hash &&
value._nodes.length === this._nodes.length &&
value._nodes.every((node, i) => node.equals(this._nodes[i]))
);
}
public *[Symbol.iterator](): Iterator<[K, V]> {
for (const node of this._nodes) {
yield* node;
}
}
}
/**
* @internal
*/
export class Sparse<K, V> implements Node<K, V> {
public static of<K, V>(mask: number, nodes: Array<Node<K, V>>): Sparse<K, V> {
return new Sparse(mask, nodes);
}
private readonly _mask: number;
private readonly _nodes: Array<Node<K, V>>;
private constructor(mask: number, nodes: Array<Node<K, V>>) {
this._mask = mask;
this._nodes = nodes;
}
public isEmpty(): this is Empty {
return false;
}
public isLeaf(): this is Leaf<K, V> {
return false;
}
public get(key: K, hash: number, shift: number): Option<V> {
const fragment = Node.fragment(hash, shift);
if (test(this._mask, fragment)) {
const index = Node.index(fragment, this._mask);
return this._nodes[index].get(key, hash, shift + Node.Bits);
}
return None;
}
public set(
key: K,
value: V,
hash: number,
shift: number
): Status<Node<K, V>> {
const fragment = Node.fragment(hash, shift);
const index = Node.index(fragment, this._mask);
if (test(this._mask, fragment)) {
const { result: node, status } = this._nodes[index].set(
key,
value,
hash,
shift + Node.Bits
);
if (status === "unchanged") {
return Status.unchanged(this);
}
const sparse = Sparse.of(this._mask, replace(this._nodes, index, node));
switch (status) {
case "created":
return Status.created(sparse);
case "updated":
default:
return Status.updated(sparse);
}
}
return Status.created(
Sparse.of(
set(this._mask, fragment),
insert(this._nodes, index, Leaf.of(hash, key, value))
)
);
}
public delete(key: K, hash: number, shift: number): Status<Node<K, V>> {
const fragment = Node.fragment(hash, shift);
if (test(this._mask, fragment)) {
const index = Node.index(fragment, this._mask);
const { result: node, status } = this._nodes[index].delete(
key,
hash,
shift + Node.Bits
);
if (status === "unchanged") {
return Status.unchanged(this);
}
if (node.isEmpty()) {
const nodes = remove(this._nodes, index);
if (nodes.length === 1) {
// We deleted the penultimate child of the Sparse, we may be able to
// simplify the tree.
if (nodes[0].isLeaf() || nodes[0] instanceof Collision) {
// The last child is leaf-like, hence hashes will be fully matched
// against its key(s) and we can remove the current Sparse
return Status.deleted(nodes[0]);
}
// Otherwise, the last child is a Sparse. We can't simply collapse the
// tree by removing the current Sparse, since it will cause the child
// mask to be tested with the wrong shift (its depth in the tree would
// be different).
// We could do some further optimisations (e.g., if the child's
// children are all leaf-like, we could instead delete the lone child
// and connect directly to the grandchildren). This is, however,
// getting hairy to make all cases working fine, and we assume this
// kind of situation is not too frequent. So we pay the price of
// keeping a non-branching Sparse until we need to optimise that.
}
return Status.deleted(Sparse.of(clear(this._mask, fragment), nodes));
}
return Status.deleted(
Sparse.of(this._mask, replace(this._nodes, index, node))
);
}
return Status.unchanged(this);
}
public map<U>(mapper: Mapper<V, U, [K]>): Sparse<K, U> {
return Sparse.of(
this._mask,
this._nodes.map((node) => node.map(mapper))
);
}
public equals(value: unknown): value is this {
return (
value instanceof Sparse &&
value._mask === this._mask &&
value._nodes.length === this._nodes.length &&
value._nodes.every((node, i) => node.equals(this._nodes[i]))
);
}
public *[Symbol.iterator](): Iterator<[K, V]> {
for (const node of this._nodes) {
yield* node;
}
}
}
function insert<T>(
array: Readonly<Array<T>>,
index: number,
value: T
): Array<T> {
const result = new Array(array.length + 1);
result[index] = value;
for (let i = 0, n = index; i < n; i++) {
result[i] = array[i];
}
for (let i = index, n = array.length; i < n; i++) {
result[i + 1] = array[i];
}
return result;
}
function remove<T>(array: Readonly<Array<T>>, index: number): Array<T> {
const result = new Array(array.length - 1);
for (let i = 0, n = index; i < n; i++) {
result[i] = array[i];
}
for (let i = index, n = result.length; i < n; i++) {
result[i] = array[i + 1];
}
return result;
}
function replace<T>(
array: Readonly<Array<T>>,
index: number,
value: T
): Array<T> {
const result = array.slice(0);
result[index] = value;
return result;
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
export const TableServiceError: msRest.CompositeMapper = {
serializedName: "TableServiceError",
type: {
name: "Composite",
className: "TableServiceError",
modelProperties: {
message: {
xmlName: "Message",
serializedName: "Message",
type: {
name: "String"
}
}
}
}
};
export const RetentionPolicy: msRest.CompositeMapper = {
serializedName: "RetentionPolicy",
type: {
name: "Composite",
className: "RetentionPolicy",
modelProperties: {
enabled: {
xmlName: "Enabled",
required: true,
serializedName: "Enabled",
type: {
name: "Boolean"
}
},
days: {
xmlName: "Days",
serializedName: "Days",
constraints: {
InclusiveMinimum: 1
},
type: {
name: "Number"
}
}
}
}
};
export const Logging: msRest.CompositeMapper = {
serializedName: "Logging",
type: {
name: "Composite",
className: "Logging",
modelProperties: {
version: {
xmlName: "Version",
required: true,
serializedName: "Version",
type: {
name: "String"
}
},
deleteProperty: {
xmlName: "Delete",
required: true,
serializedName: "Delete",
type: {
name: "Boolean"
}
},
read: {
xmlName: "Read",
required: true,
serializedName: "Read",
type: {
name: "Boolean"
}
},
write: {
xmlName: "Write",
required: true,
serializedName: "Write",
type: {
name: "Boolean"
}
},
retentionPolicy: {
xmlName: "RetentionPolicy",
required: true,
serializedName: "RetentionPolicy",
type: {
name: "Composite",
className: "RetentionPolicy"
}
}
}
}
};
export const Metrics: msRest.CompositeMapper = {
serializedName: "Metrics",
type: {
name: "Composite",
className: "Metrics",
modelProperties: {
version: {
xmlName: "Version",
serializedName: "Version",
type: {
name: "String"
}
},
enabled: {
xmlName: "Enabled",
required: true,
serializedName: "Enabled",
type: {
name: "Boolean"
}
},
includeAPIs: {
xmlName: "IncludeAPIs",
serializedName: "IncludeAPIs",
type: {
name: "Boolean"
}
},
retentionPolicy: {
xmlName: "RetentionPolicy",
serializedName: "RetentionPolicy",
type: {
name: "Composite",
className: "RetentionPolicy"
}
}
}
}
};
export const CorsRule: msRest.CompositeMapper = {
serializedName: "CorsRule",
type: {
name: "Composite",
className: "CorsRule",
modelProperties: {
allowedOrigins: {
xmlName: "AllowedOrigins",
required: true,
serializedName: "AllowedOrigins",
type: {
name: "String"
}
},
allowedMethods: {
xmlName: "AllowedMethods",
required: true,
serializedName: "AllowedMethods",
type: {
name: "String"
}
},
allowedHeaders: {
xmlName: "AllowedHeaders",
required: true,
serializedName: "AllowedHeaders",
type: {
name: "String"
}
},
exposedHeaders: {
xmlName: "ExposedHeaders",
required: true,
serializedName: "ExposedHeaders",
type: {
name: "String"
}
},
maxAgeInSeconds: {
xmlName: "MaxAgeInSeconds",
required: true,
serializedName: "MaxAgeInSeconds",
constraints: {
InclusiveMinimum: 0
},
type: {
name: "Number"
}
}
}
}
};
export const TableServiceProperties: msRest.CompositeMapper = {
xmlName: "StorageServiceProperties",
serializedName: "TableServiceProperties",
type: {
name: "Composite",
className: "TableServiceProperties",
modelProperties: {
logging: {
xmlName: "Logging",
serializedName: "Logging",
type: {
name: "Composite",
className: "Logging"
}
},
hourMetrics: {
xmlName: "HourMetrics",
serializedName: "HourMetrics",
type: {
name: "Composite",
className: "Metrics"
}
},
minuteMetrics: {
xmlName: "MinuteMetrics",
serializedName: "MinuteMetrics",
type: {
name: "Composite",
className: "Metrics"
}
},
cors: {
xmlIsWrapped: true,
xmlName: "Cors",
xmlElementName: "CorsRule",
serializedName: "Cors",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "CorsRule"
}
}
}
}
}
}
};
export const GeoReplication: msRest.CompositeMapper = {
serializedName: "GeoReplication",
type: {
name: "Composite",
className: "GeoReplication",
modelProperties: {
status: {
xmlName: "Status",
required: true,
serializedName: "Status",
type: {
name: "String"
}
},
lastSyncTime: {
xmlName: "LastSyncTime",
required: true,
serializedName: "LastSyncTime",
type: {
name: "DateTimeRfc1123"
}
}
}
}
};
export const TableServiceStats: msRest.CompositeMapper = {
xmlName: "StorageServiceStats",
serializedName: "TableServiceStats",
type: {
name: "Composite",
className: "TableServiceStats",
modelProperties: {
geoReplication: {
xmlName: "GeoReplication",
serializedName: "GeoReplication",
type: {
name: "Composite",
className: "GeoReplication"
}
}
}
}
};
export const TableProperties: msRest.CompositeMapper = {
serializedName: "TableProperties",
type: {
name: "Composite",
className: "TableProperties",
modelProperties: {
tableName: {
xmlName: "TableName",
serializedName: "TableName",
type: {
name: "String"
}
}
}
}
};
export const TableResponse: msRest.CompositeMapper = {
serializedName: "TableResponse",
type: {
name: "Composite",
className: "TableResponse",
modelProperties: {
odatametadata: {
xmlName: "odata.metadata",
serializedName: "odata\\.metadata",
type: {
name: "String"
}
},
tableName: {
xmlName: "TableName",
serializedName: "TableName",
type: {
name: "String"
}
},
odatatype: {
xmlName: "odata.type",
serializedName: "odata\\.type",
type: {
name: "String"
}
},
odataid: {
xmlName: "odata.id",
serializedName: "odata\\.id",
type: {
name: "String"
}
},
odataeditLink: {
xmlName: "odata.editLink",
serializedName: "odata\\.editLink",
type: {
name: "String"
}
}
}
}
};
export const TableResponseProperties: msRest.CompositeMapper = {
serializedName: "TableResponseProperties",
type: {
name: "Composite",
className: "TableResponseProperties",
modelProperties: {
tableName: {
xmlName: "TableName",
serializedName: "TableName",
type: {
name: "String"
}
},
odatatype: {
xmlName: "odata.type",
serializedName: "odata\\.type",
type: {
name: "String"
}
},
odataid: {
xmlName: "odata.id",
serializedName: "odata\\.id",
type: {
name: "String"
}
},
odataeditLink: {
xmlName: "odata.editLink",
serializedName: "odata\\.editLink",
type: {
name: "String"
}
}
}
}
};
export const TableQueryResponse: msRest.CompositeMapper = {
serializedName: "TableQueryResponse",
type: {
name: "Composite",
className: "TableQueryResponse",
modelProperties: {
odatametadata: {
xmlName: "odata.metadata",
serializedName: "odata\\.metadata",
type: {
name: "String"
}
},
value: {
xmlName: "value",
xmlElementName: "TableResponseProperties",
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "TableResponseProperties"
}
}
}
}
}
}
};
export const AccessPolicy: msRest.CompositeMapper = {
serializedName: "AccessPolicy",
type: {
name: "Composite",
className: "AccessPolicy",
modelProperties: {
start: {
xmlName: "Start",
required: true,
serializedName: "Start",
type: {
name: "String"
}
},
expiry: {
xmlName: "Expiry",
required: true,
serializedName: "Expiry",
type: {
name: "String"
}
},
permission: {
xmlName: "Permission",
required: true,
serializedName: "Permission",
type: {
name: "String"
}
}
}
}
};
export const SignedIdentifier: msRest.CompositeMapper = {
serializedName: "SignedIdentifier",
type: {
name: "Composite",
className: "SignedIdentifier",
modelProperties: {
id: {
xmlName: "Id",
required: true,
serializedName: "Id",
type: {
name: "String"
}
},
accessPolicy: {
xmlName: "AccessPolicy",
required: true,
serializedName: "AccessPolicy",
type: {
name: "Composite",
className: "AccessPolicy"
}
}
}
}
};
export const TableEntityQueryResponse: msRest.CompositeMapper = {
serializedName: "TableEntityQueryResponse",
type: {
name: "Composite",
className: "TableEntityQueryResponse",
modelProperties: {
odatametadata: {
xmlName: "odata.metadata",
serializedName: "odata\\.metadata",
type: {
name: "String"
}
},
value: {
xmlName: "value",
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
}
}
}
}
}
};
export const QueryOptions: msRest.CompositeMapper = {
xmlName: "QueryOptions",
type: {
name: "Composite",
className: "QueryOptions",
modelProperties: {
format: {
xmlName: "format",
type: {
name: "String"
}
},
top: {
xmlName: "top",
type: {
name: "Number"
}
},
select: {
xmlName: "select",
type: {
name: "String"
}
},
filter: {
xmlName: "filter",
type: {
name: "String"
}
}
}
}
};
export const TableQueryHeaders: msRest.CompositeMapper = {
serializedName: "table-query-headers",
type: {
name: "Composite",
className: "TableQueryHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
xMsContinuationNextTableName: {
serializedName: "x-ms-continuation-nexttablename",
type: {
name: "String"
}
}
}
}
};
export const TableCreateHeaders: msRest.CompositeMapper = {
serializedName: "table-create-headers",
type: {
name: "Composite",
className: "TableCreateHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
preferenceApplied: {
serializedName: "preference-applied",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableBatchHeaders: msRest.CompositeMapper = {
serializedName: "table-batch-headers",
type: {
name: "Composite",
className: "TableBatchHeaders",
modelProperties: {
contentType: {
serializedName: "content-type",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableDeleteHeaders: msRest.CompositeMapper = {
serializedName: "table-delete-headers",
type: {
name: "Composite",
className: "TableDeleteHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableQueryEntitiesHeaders: msRest.CompositeMapper = {
serializedName: "table-queryentities-headers",
type: {
name: "Composite",
className: "TableQueryEntitiesHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
xMsContinuationNextPartitionKey: {
serializedName: "x-ms-continuation-nextpartitionkey",
type: {
name: "String"
}
},
xMsContinuationNextRowKey: {
serializedName: "x-ms-continuation-nextrowkey",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableQueryEntitiesWithPartitionAndRowKeyHeaders: msRest.CompositeMapper = {
serializedName: "table-queryentitieswithpartitionandrowkey-headers",
type: {
name: "Composite",
className: "TableQueryEntitiesWithPartitionAndRowKeyHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
eTag: {
serializedName: "etag",
type: {
name: "String"
}
},
xMsContinuationNextPartitionKey: {
serializedName: "x-ms-continuation-nextpartitionkey",
type: {
name: "String"
}
},
xMsContinuationNextRowKey: {
serializedName: "x-ms-continuation-nextrowkey",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableUpdateEntityHeaders: msRest.CompositeMapper = {
serializedName: "table-updateentity-headers",
type: {
name: "Composite",
className: "TableUpdateEntityHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
eTag: {
serializedName: "etag",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableMergeEntityHeaders: msRest.CompositeMapper = {
serializedName: "table-mergeentity-headers",
type: {
name: "Composite",
className: "TableMergeEntityHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
eTag: {
serializedName: "etag",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableDeleteEntityHeaders: msRest.CompositeMapper = {
serializedName: "table-deleteentity-headers",
type: {
name: "Composite",
className: "TableDeleteEntityHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableMergeEntityWithMergeHeaders: msRest.CompositeMapper = {
serializedName: "table-mergeentitywithmerge-headers",
type: {
name: "Composite",
className: "TableMergeEntityWithMergeHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
eTag: {
serializedName: "etag",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableInsertEntityHeaders: msRest.CompositeMapper = {
serializedName: "table-insertentity-headers",
type: {
name: "Composite",
className: "TableInsertEntityHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
eTag: {
serializedName: "etag",
type: {
name: "String"
}
},
preferenceApplied: {
serializedName: "preference-applied",
type: {
name: "String"
}
},
contentType: {
serializedName: "content-type",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableGetAccessPolicyHeaders: msRest.CompositeMapper = {
serializedName: "table-getaccesspolicy-headers",
type: {
name: "Composite",
className: "TableGetAccessPolicyHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const TableSetAccessPolicyHeaders: msRest.CompositeMapper = {
serializedName: "table-setaccesspolicy-headers",
type: {
name: "Composite",
className: "TableSetAccessPolicyHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const ServiceSetPropertiesHeaders: msRest.CompositeMapper = {
serializedName: "service-setproperties-headers",
type: {
name: "Composite",
className: "ServiceSetPropertiesHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const ServiceGetPropertiesHeaders: msRest.CompositeMapper = {
serializedName: "service-getproperties-headers",
type: {
name: "Composite",
className: "ServiceGetPropertiesHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
};
export const ServiceGetStatisticsHeaders: msRest.CompositeMapper = {
serializedName: "service-getstatistics-headers",
type: {
name: "Composite",
className: "ServiceGetStatisticsHeaders",
modelProperties: {
clientRequestId: {
serializedName: "x-ms-client-request-id",
type: {
name: "String"
}
},
requestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
},
version: {
serializedName: "x-ms-version",
type: {
name: "String"
}
},
date: {
serializedName: "date",
type: {
name: "DateTimeRfc1123"
}
},
errorCode: {
serializedName: "x-ms-error-code",
type: {
name: "String"
}
}
}
}
}; | the_stack |
import React, {
ComponentType,
CSSProperties,
useCallback,
useRef,
useState,
MutableRefObject,
useMemo,
Ref,
} from 'react';
import { ResizeablePluginConfig, ResizeablePluginStore, BlockProps } from '.';
interface DecoratorProps {
config: ResizeablePluginConfig;
store: ResizeablePluginStore;
}
export interface WrappedComponentProps {
blockProps: BlockProps;
clicked: boolean;
width: number;
height: number;
style?: CSSProperties;
ref?: Ref<HTMLElement>;
}
interface BlockResizeableDecoratorProps extends WrappedComponentProps {
isResizable?: boolean;
resizeSteps?: number;
}
type WrappedComponentType = ComponentType<WrappedComponentProps> & {
WrappedComponent?: ComponentType<WrappedComponentProps>;
};
const getDisplayName = (WrappedComponent: WrappedComponentType): string => {
const component = WrappedComponent.WrappedComponent || WrappedComponent;
return component.displayName || component.name || 'Component';
};
const round = (x: number, steps: number): number =>
Math.ceil(x / steps) * steps;
export default ({ config, store }: DecoratorProps) =>
(
WrappedComponent: WrappedComponentType
): ComponentType<WrappedComponentProps> => {
const BlockResizeableDecorator = React.forwardRef<
HTMLElement,
BlockResizeableDecoratorProps
>(
(
{
blockProps,
isResizable = true,
resizeSteps = 1,
...elementProps
}: BlockResizeableDecoratorProps,
ref
) => {
const {
vertical = false,
horizontal = 'relative',
initialWidth,
initialHeight,
} = config;
const [clicked, setClicked] = useState(false);
const [width, setWidth] = useState<number>(0);
const [height, setHeight] = useState<number>(0);
const [hoverPosition, setHoverPosition] = useState<
Record<string, boolean>
>({});
const wrapper = useRef<HTMLElement | null>();
const mouseLeave = useCallback(() => {
if (!clicked) {
setHoverPosition({});
}
}, [clicked]);
const mouseMove = useCallback(
(evt: MouseEvent) => {
const tolerance = 6;
const b = wrapper.current!.getBoundingClientRect();
const x = evt.clientX - b.left;
const y = evt.clientY - b.top;
const isTop =
vertical && vertical !== 'auto' ? y < tolerance : false;
const isLeft = horizontal ? x < tolerance : false;
const isRight = horizontal ? x >= b.width - tolerance : false;
const isBottom =
vertical && vertical !== 'auto'
? y >= b.height - tolerance && y < b.height
: false;
const canResize =
(isTop || isLeft || isRight || isBottom) && isResizable;
const newHoverPosition: Record<string, boolean> = {
isTop,
isLeft,
isRight,
isBottom,
canResize,
};
setHoverPosition((oldHoverPosition) => {
const hasNewHoverPositions = Object.keys(newHoverPosition).filter(
(key) => oldHoverPosition[key] !== newHoverPosition[key]
);
if (hasNewHoverPositions.length) {
return newHoverPosition;
}
return oldHoverPosition;
});
},
[vertical, horizontal, isResizable]
);
const mouseDown = useCallback(
(event: MouseEvent) => {
// No mouse-hover-position data? Nothing to resize!
if (!hoverPosition.canResize) {
return;
}
event.preventDefault();
const { isTop, isLeft, isRight, isBottom } = hoverPosition;
const pane = wrapper.current!;
const startX = event.clientX;
const startY = event.clientY;
const startWidth = parseInt(
document.defaultView!.getComputedStyle(pane).width,
10
);
const startHeight = parseInt(
document.defaultView!.getComputedStyle(pane).height,
10
);
let newWidth = width;
let newHeight = height;
// Do the actual drag operation
const doDrag = (dragEvent: MouseEvent): void => {
let _width =
startWidth +
(isLeft
? startX - dragEvent.clientX
: dragEvent.clientX - startX);
let _height = startHeight + dragEvent.clientY - startY;
const editorComp = store.getEditorRef!();
// this keeps backwards-compatibility with react 15
const editorNode =
editorComp.refs && editorComp.refs.editor
? editorComp.refs.editor
: editorComp.editor;
_width = Math.min(editorNode.clientWidth, _width);
_height = Math.min(editorNode.clientHeight, _height);
const widthPerc = (100 / editorNode.clientWidth) * _width;
const heightPerc = (100 / editorNode.clientHeight) * _height;
if ((isLeft || isRight) && horizontal === 'relative') {
newWidth = resizeSteps
? round(widthPerc, resizeSteps)
: widthPerc;
setWidth(newWidth);
} else if ((isLeft || isRight) && horizontal === 'absolute') {
newWidth = resizeSteps ? round(_width, resizeSteps) : _width;
setWidth(newWidth);
}
if ((isTop || isBottom) && vertical === 'relative') {
newHeight = resizeSteps
? round(heightPerc, resizeSteps)
: heightPerc;
setHeight(newHeight);
} else if ((isTop || isBottom) && vertical === 'absolute') {
newHeight = resizeSteps ? round(_height, resizeSteps) : _height;
setHeight(newHeight);
}
dragEvent.preventDefault();
};
// Finished dragging
const stopDrag = (): void => {
// TODO clean up event listeners
document.removeEventListener('mousemove', doDrag, false);
document.removeEventListener('mouseup', stopDrag, false);
setClicked(false);
blockProps.setResizeData({ width: newWidth, height: newHeight });
};
// TODO clean up event listeners
document.addEventListener('mousemove', doDrag, false);
document.addEventListener('mouseup', stopDrag, false);
setClicked(true);
},
[hoverPosition, width, height, blockProps]
);
const styles: CSSProperties = useMemo(() => {
const _styles: CSSProperties = { position: 'relative' };
const { isTop, isLeft, isRight, isBottom } = hoverPosition;
if (horizontal === 'auto') {
_styles.width = 'auto';
} else if (horizontal === 'relative') {
const value = width || blockProps.resizeData.width;
if (!value && initialWidth) {
_styles.width = initialWidth;
} else {
_styles.width = `${value || 40}%`;
}
} else if (horizontal === 'absolute') {
const value = width || blockProps.resizeData.width;
if (!value && initialWidth) {
_styles.width = initialWidth;
} else {
_styles.width = `${value || 40}px`;
}
}
if (vertical === 'auto') {
_styles.height = 'auto';
} else if (vertical === 'relative') {
const value = height || blockProps.resizeData.height;
if (!value && initialHeight) {
_styles.height = initialHeight;
} else {
_styles.height = `${value || 40}%`;
}
} else if (vertical === 'absolute') {
const value = height || blockProps.resizeData.height;
if (!value && initialHeight) {
_styles.height = initialHeight;
} else {
_styles.height = `${value || 40}%`;
}
}
// Handle cursor
if (!isResizable) {
_styles.cursor = 'default';
} else if ((isRight && isBottom) || (isLeft && isTop)) {
_styles.cursor = 'nwse-resize';
} else if ((isRight && isTop) || (isBottom && isLeft)) {
_styles.cursor = 'nesw-resize';
} else if (isRight || isLeft) {
_styles.cursor = 'ew-resize';
} else if (isBottom || isTop) {
_styles.cursor = 'ns-resize';
} else {
_styles.cursor = 'default';
}
return _styles;
}, [hoverPosition, height, width]);
const interactionProps =
!store.getReadOnly || store.getReadOnly()
? {}
: {
onMouseDown: mouseDown,
onMouseMove: mouseMove,
onMouseLeave: mouseLeave,
};
return (
<WrappedComponent
{...elementProps}
{...interactionProps}
blockProps={blockProps}
ref={(node) => {
wrapper.current = node;
if (typeof ref === 'function') {
ref(node);
} else if (ref) {
// eslint-disable-next-line no-param-reassign
(ref as MutableRefObject<HTMLElement | null>).current = node;
}
}}
style={styles}
/>
);
}
);
BlockResizeableDecorator.displayName = `BlockResizeable(${getDisplayName(
WrappedComponent
)})`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(BlockResizeableDecorator as any).WrappedComponent =
WrappedComponent.WrappedComponent || WrappedComponent;
return BlockResizeableDecorator;
}; | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type OrderUpdate_Test_QueryVariables = {
conversationID: string;
};
export type OrderUpdate_Test_QueryResponse = {
readonly me: {
readonly conversation: {
readonly orderConnection: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly orderHistory: ReadonlyArray<{
readonly __typename: string;
readonly " $fragmentRefs": FragmentRefs<"OrderUpdate_event">;
}>;
} | null;
} | null> | null;
} | null;
} | null;
} | null;
};
export type OrderUpdate_Test_Query = {
readonly response: OrderUpdate_Test_QueryResponse;
readonly variables: OrderUpdate_Test_QueryVariables;
};
/*
query OrderUpdate_Test_Query(
$conversationID: String!
) {
me {
conversation(id: $conversationID) {
orderConnection(first: 10, participantType: BUYER) {
edges {
node {
__typename
orderHistory {
__typename
...OrderUpdate_event
}
id
}
}
}
id
}
id
}
}
fragment OrderUpdate_event on CommerceOrderEventUnion {
__typename
... on CommerceOrderStateChangedEvent {
createdAt
stateReason
state
}
... on CommerceOfferSubmittedEvent {
createdAt
offer {
amount
fromParticipant
definesTotal
offerAmountChanged
respondsTo {
fromParticipant
id
}
id
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "conversationID",
"type": "String!"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "conversationID"
}
],
v2 = [
{
"kind": "Literal",
"name": "first",
"value": 10
},
{
"kind": "Literal",
"name": "participantType",
"value": "BUYER"
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "createdAt",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "fromParticipant",
"storageKey": null
},
v6 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "OrderUpdate_Test_Query",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orderConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "orderHistory",
"plural": true,
"selections": [
(v3/*: any*/),
{
"args": null,
"kind": "FragmentSpread",
"name": "OrderUpdate_event"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "orderConnection(first:10,participantType:\"BUYER\")"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"type": "Query"
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "OrderUpdate_Test_Query",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orderConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v3/*: any*/),
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "orderHistory",
"plural": true,
"selections": [
(v3/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "stateReason",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "state",
"storageKey": null
}
],
"type": "CommerceOrderStateChangedEvent"
},
{
"kind": "InlineFragment",
"selections": [
(v4/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "CommerceOffer",
"kind": "LinkedField",
"name": "offer",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "amount",
"storageKey": null
},
(v5/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "definesTotal",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "offerAmountChanged",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "CommerceOffer",
"kind": "LinkedField",
"name": "respondsTo",
"plural": false,
"selections": [
(v5/*: any*/),
(v6/*: any*/)
],
"storageKey": null
},
(v6/*: any*/)
],
"storageKey": null
}
],
"type": "CommerceOfferSubmittedEvent"
}
],
"storageKey": null
},
(v6/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "orderConnection(first:10,participantType:\"BUYER\")"
},
(v6/*: any*/)
],
"storageKey": null
},
(v6/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": null,
"metadata": {},
"name": "OrderUpdate_Test_Query",
"operationKind": "query",
"text": "query OrderUpdate_Test_Query(\n $conversationID: String!\n) {\n me {\n conversation(id: $conversationID) {\n orderConnection(first: 10, participantType: BUYER) {\n edges {\n node {\n __typename\n orderHistory {\n __typename\n ...OrderUpdate_event\n }\n id\n }\n }\n }\n id\n }\n id\n }\n}\n\nfragment OrderUpdate_event on CommerceOrderEventUnion {\n __typename\n ... on CommerceOrderStateChangedEvent {\n createdAt\n stateReason\n state\n }\n ... on CommerceOfferSubmittedEvent {\n createdAt\n offer {\n amount\n fromParticipant\n definesTotal\n offerAmountChanged\n respondsTo {\n fromParticipant\n id\n }\n id\n }\n }\n}\n"
}
};
})();
(node as any).hash = '58dacc86944663a450d97795ff39b5d9';
export default node; | the_stack |
const parseXml = require('@rgrove/parse-xml');
const camelCaseLib = require('camelcase');
const isVarName = require("is-var-name");
const indentString = require('indent-string');
import { compile, JSONSchema } from 'json-schema-to-typescript'
const camelCase = (text: string) => {
const camelCased = camelCaseLib(text);
const UPPER_CASE = /([A-Z]{2,})/;
const match = text.match(UPPER_CASE);
if (match && match[1]) {
return camelCased.replace(new RegExp(match[1], "i"), match[1]);
}
return camelCased;
};
const pascalCase = (text: string) => {
const camelCased = camelCaseLib(text, { pascalCase: true });
const UPPER_CASE = /([A-Z]{2,})/;
const match = text.match(UPPER_CASE);
if (match && match[1]) {
return camelCased.replace(new RegExp(match[1], "i"), match[1]);
}
return camelCased;
};
interface Node {
type: string;
[index: string]: any;
}
interface RootNode extends Node {
attributes: any;
children: {
type: string,
children: RootNode;
[index: string]: any
}[];
}
const isCommand = (node: Node): node is Command => {
return node.name === "command";
};
const isRecord = (node: Node): node is Record => {
return node.name === "record-type";
};
const isClass = (node: Node): node is Class => {
return node.name === "class";
};
const isClassExtension = (node: Node): node is ClassExtension => {
return node.name === "class-extension";
};
interface Command extends RootNode {
name: "command";
}
interface Record extends RootNode {
name: "record";
}
interface ClassExtension extends RootNode {
name: "class-extension";
}
interface Class extends RootNode {
name: "class";
}
const convertJSONSchemaType = (type: string): string => {
switch (type) {
case "text":
return "string";
case "number":
case "integer":
return "integer";
case "boolean":
return "boolean";
case "Any":
case "type class":
return "any";
}
// TODO: can we support custom type?
return "any";
};
const convertType = (type: string, namespace: string, definedJSONSchemaList: JSONSchema[]): "number" | "string" | "boolean" | string => {
switch (type) {
case "text":
return "string";
case "number":
case "integer":
return "number";
case "boolean":
return "boolean";
case "Any":
case "type class":
return "any";
}
const otherType = pascalCase(type);
// avoid to use undefined type
const isTypeDefinedAsRecord = definedJSONSchemaList.some((schema) => {
return schema.title === otherType;
});
return isTypeDefinedAsRecord ? `${namespace}.${otherType}` : "any";
};
const createOptionalParameter = (name: string, parameters: Node[]): Promise<string | null> => {
if (parameters.length === 0) {
return Promise.resolve(null);
}
const propertyMap = parameters.map(param => {
return {
name: camelCase(param.attributes.name),
description: param.attributes.description,
type: convertJSONSchemaType(param.attributes.type)
}
});
const properties: { [index: string]: any } = {};
propertyMap.forEach(prop => {
properties[prop.name] = {
type: prop.type,
description: prop.description
}
});
const required = parameters.filter(param => {
return param.attributes.optional !== "yes"
}).map(param => {
return camelCase(param.attributes.name);
});
return compile({
"title": name,
"type": "object",
"properties": properties,
"additionalProperties": false,
"required": required
}, name)
};
const recordToJSONSchema = (command: Record | Class | ClassExtension): JSONSchema => {
// https://www.npmjs.com/package/json-schema-to-typescript
const pascalCaseName = isClassExtension(command) ? pascalCase(command.attributes.extends) : pascalCase(command.attributes.name);
const description = command.attributes.description;
const propertiesList = command.children.filter(node => {
return node.type === "element" && node.name === "property" && typeof node.attributes === "object";
});
const propertyMap = propertiesList.map(param => {
return {
name: camelCase(param.attributes.name),
description: param.attributes.description,
type: convertJSONSchemaType(param.attributes.type)
}
});
const properties: { [index: string]: any } = {};
propertyMap.forEach(prop => {
properties[prop.name] = {
type: prop.type,
description: prop.description
}
});
const required = propertiesList.filter(param => {
return param.attributes.optional !== "yes"
}).map(param => {
return camelCase(param.attributes.name);
});
return {
"title": pascalCaseName,
"description": description,
"type": "object",
"properties": properties,
"additionalProperties": false,
"required": required
}
};
const commandToDeclare = async (namespace: string, command: Command, recordSchema: JSONSchema[], optionalMap: Map<string, number>): Promise<{
header: string;
body: string;
}> => {
// https://www.npmjs.com/package/json-schema-to-typescript
const name = camelCase(command.attributes.name);
const pascalCaseName = camelCaseLib(command.attributes.name, { pascalCase: true });
const description = command.attributes.description;
const directParameters = command.children.filter(node => {
return node.type === "element" && node.name === "direct-parameter" && typeof node.attributes === "object";
});
const directParametersArgs = directParameters.map(param => {
const optionalMark = param.attributes.optional === "yes" ? "?" : "";
// TODO: support direct parameters as object
if (param.attributes.type === undefined) {
return `${camelCase(param.name)}${optionalMark}: {}`
}
const argType = convertType(param.attributes.type, namespace, recordSchema);
return `${camelCase(param.name)}${optionalMark}: ${argType}`;
});
const directParametersDocs = directParameters.map(param => {
return ` * @param ${camelCase(param.name)} ${param.attributes.description}`
});
const parameters = command.children.filter(node => {
return node.type === "element" && node.name === "parameter" && typeof node.attributes === "object";
});
let optionalParameterTypeName = `${pascalCaseName}OptionalParameter`;
const optionalParameterTypeNameCount = optionalMap.get(optionalParameterTypeName) || 0;
if (optionalParameterTypeNameCount > 0) {
optionalParameterTypeName += String(optionalParameterTypeNameCount);
}
optionalMap.set(optionalParameterTypeName, optionalParameterTypeNameCount + 1);
const optionalParameterType = await createOptionalParameter(optionalParameterTypeName, parameters);
const optionalParameters = optionalParameterType ? `option?: ${namespace}.${optionalParameterTypeName}` : "";
const optionalParameterDoc = optionalParameterType ? `* @param option` : "";
const result = command.children.filter(node => {
return node.type === "element" && node.name === "result";
});
const resultDescription = result.length === 0 ? "" : `@return ${result[0].attributes.description}`;
const createReturnType = (result: Node[]) => {
if (result.length === 0 || !result[0].attributes.type) {
return "void";
}
return convertType(result[0].attributes.type, namespace, recordSchema);
};
const returnType = createReturnType(result);
return {
header: optionalParameterType ? optionalParameterType : "",
body: `
/**
* ${description}
${directParametersDocs.join("\n")}${
optionalParameterDoc ? "\n " + optionalParameterDoc : ""
}
* ${resultDescription}
*/
${name}(${directParametersArgs.join(", ")}${directParametersArgs.length > 0 ? ", " : ""}${optionalParameters}): ${returnType};`
}
};
const schemaToInterfaces = async (schemas: JSONSchema[]): Promise<string> => {
const results = await Promise.all(schemas.map(schema => {
const title = schema.title!;
return compile(schema, title).then(definition => {
// TODO: prevent UIElement -> UiElement
// https://github.com/bcherny/json-schema-to-typescript/blob/fadb879a5373f20fd9d1f441168494003e825239/src/utils.ts#L56
return definition
.replace(new RegExp(`interface ${title}`, "i"), `interface ${title}`)
// Fix property to method: name -> name()
.replace(/(\w+):(.*;)/g, "$1():$2");
});
}));
return results.join("\n");
};
export const transform = async (namespace: string, sdefContent: string) => {
if (!isVarName(namespace)) {
throw new Error(`${namespace} can not to be used for namespace, because it includes invalid string.`);
}
const JSON = parseXml(sdefContent);
const dictionary: RootNode = JSON.children[0];
const suites = dictionary.children.filter(node => node.name === "suite");
const commands: Command[] = [];
const records: Record[] = [];
const classes: Class[] = [];
const classExtensions: ClassExtension[] = [];
// TODO: support enum
suites.forEach(suite => {
suite.children.forEach((node: Node) => {
if (isCommand(node)) {
commands.push(node);
} else if (isRecord(node)) {
records.push(node);
} else if (isClass(node)) {
classes.push(node)
} else if (isClassExtension(node)) {
classExtensions.push(node);
}
})
});
const recordSchemaList = records.map(record => {
return recordToJSONSchema(record);
});
const classSchemaList = classes.map(node => {
return recordToJSONSchema(node);
});
const classExtendSchemaList = classExtensions.map(node => {
return recordToJSONSchema(node);
});
const recordDefinitions = await schemaToInterfaces(recordSchemaList);
const classDefinitions = await schemaToInterfaces(classSchemaList);
const classExtensionDefinitions = await schemaToInterfaces(classExtendSchemaList);
const optionalBindingMap = new Map<string, number>();
const functionDefinitions = await Promise.all(commands.map(command => {
return commandToDeclare(namespace, command, recordSchemaList.concat(classSchemaList, classExtendSchemaList), optionalBindingMap);
}));
const functionDefinitionHeaders = functionDefinitions.map(def => def.header);
const functionDefinitionBodies = functionDefinitions.map(def => def.body);
return `
export namespace ${namespace} {
// Default Application
${indentString(`export interface Application {}`)}
// Class
${indentString(classDefinitions)}
// CLass Extension
${indentString(classExtensionDefinitions)}
// Records
${indentString(recordDefinitions)}
// Function options
${indentString(functionDefinitionHeaders.join("\n"), 4)}
}
export interface ${namespace} extends ${namespace}.Application {
// Functions
${indentString(functionDefinitionBodies.join("\n"), 4)}
}
`;
}; | the_stack |
import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output
} from '@angular/core';
import { interval, of, Subscription } from 'rxjs';
import { map, startWith, switchMap, take, tap } from 'rxjs/operators';
import { getColumnFields } from '~front/app/functions/get-column-fields';
import { getExtendedFilters } from '~front/app/functions/get-extended-filters';
import { getSelectValid } from '~front/app/functions/get-select-valid';
import { MemberQuery } from '~front/app/queries/member.query';
import { NavQuery } from '~front/app/queries/nav.query';
import { UiQuery } from '~front/app/queries/ui.query';
import { ApiService } from '~front/app/services/api.service';
import { MyDialogService } from '~front/app/services/my-dialog.service';
import { NavigateService } from '~front/app/services/navigate.service';
import { QueryService, RData } from '~front/app/services/query.service';
import { ModelStore } from '~front/app/stores/model.store';
import { MqStore } from '~front/app/stores/mq.store';
import { NavState } from '~front/app/stores/nav.store';
import { UiStore } from '~front/app/stores/ui.store';
import { apiToBackend } from '~front/barrels/api-to-backend';
import { common } from '~front/barrels/common';
import { interfaces } from '~front/barrels/interfaces';
@Component({
selector: 'm-chart-viz',
templateUrl: './chart-viz.component.html'
})
export class ChartVizComponent implements OnInit, OnDestroy {
chartTypeEnumTable = common.ChartTypeEnum.Table;
queryStatusEnum = common.QueryStatusEnum;
@Input()
report: common.Report;
@Input()
title: string;
@Input()
viz: common.Viz;
accessRolesString: string;
accessUsersString: string;
accessString: string;
author: string;
@Output() vizDeleted = new EventEmitter<string>();
sortedColumns: interfaces.ColumnField[];
qData: RData[];
query: common.Query;
mconfig: common.Mconfig;
model: common.Model;
menuId = common.makeId();
openedMenuId: string;
openedMenuId$ = this.uiQuery.openedMenuId$.pipe(
tap(x => (this.openedMenuId = x))
);
isVizOptionsMenuOpen = false;
checkRunning$: Subscription;
nav: NavState;
nav$ = this.navQuery.select().pipe(
tap(x => {
this.nav = x;
})
);
extendedFilters: interfaces.FilterExtended[];
canEditOrDeleteViz = false;
canAccessModel = false;
isSelectValid = false;
constructor(
private apiService: ApiService,
private navQuery: NavQuery,
private memberQuery: MemberQuery,
private queryService: QueryService,
private navigateService: NavigateService,
private cd: ChangeDetectorRef,
private myDialogService: MyDialogService,
public uiQuery: UiQuery,
public uiStore: UiStore,
private mqStore: MqStore,
private modelStore: ModelStore
) {}
async ngOnInit() {
this.accessRolesString = 'Roles - ' + this.viz.accessRoles.join(', ');
this.accessUsersString = 'Users - ' + this.viz.accessUsers.join(', ');
this.accessString =
this.viz.accessRoles.length > 0 && this.viz.accessUsers.length > 0
? this.accessRolesString + '; ' + this.accessUsersString
: this.viz.accessRoles.length > 0
? this.accessRolesString
: this.viz.accessUsers.length > 0
? this.accessUsersString
: '';
let vizFilePathArray = this.viz.filePath.split('/');
this.author =
vizFilePathArray.length > 1 &&
vizFilePathArray[1] === common.BLOCKML_USERS_FOLDER
? vizFilePathArray[2]
: undefined;
let member: common.Member;
this.memberQuery
.select()
.pipe(
tap(x => {
member = x;
})
)
.subscribe();
let nav: NavState;
this.navQuery
.select()
.pipe(
tap(x => {
nav = x;
}),
take(1)
)
.subscribe();
let payloadGetModel: apiToBackend.ToBackendGetModelRequestPayload = {
projectId: nav.projectId,
branchId: nav.branchId,
isRepoProd: nav.isRepoProd,
modelId: this.report.modelId
};
let model: common.Model = await this.apiService
.req(
apiToBackend.ToBackendRequestInfoNameEnum.ToBackendGetModel,
payloadGetModel
)
.pipe(
map(
(resp: apiToBackend.ToBackendGetModelResponse) => resp.payload.model
)
)
.toPromise();
let payloadGetMconfig: apiToBackend.ToBackendGetMconfigRequestPayload = {
mconfigId: this.report.mconfigId
};
let mconfig: common.Mconfig = await this.apiService
.req(
apiToBackend.ToBackendRequestInfoNameEnum.ToBackendGetMconfig,
payloadGetMconfig
)
.pipe(
map(
(resp: apiToBackend.ToBackendGetMconfigResponse) =>
resp.payload.mconfig
)
)
.toPromise();
this.extendedFilters = getExtendedFilters({
fields: model.fields,
mconfig: mconfig
});
let payloadGetQuery: apiToBackend.ToBackendGetQueryRequestPayload = {
mconfigId: this.report.mconfigId,
queryId: this.report.queryId,
vizId: this.viz.vizId
};
let query: common.Query = await this.apiService
.req(
apiToBackend.ToBackendRequestInfoNameEnum.ToBackendGetQuery,
payloadGetQuery
)
.pipe(
map(
(resp: apiToBackend.ToBackendGetQueryResponse) => resp.payload.query
)
)
.toPromise();
this.sortedColumns = getColumnFields({
mconfig: mconfig,
fields: model.fields
});
this.qData =
mconfig.queryId === query.queryId
? this.queryService.makeQData({
data: query.data,
columns: this.sortedColumns
})
: [];
this.query = query;
this.mconfig = mconfig;
this.model = model;
this.checkRunning$ = interval(3000)
.pipe(
startWith(0),
switchMap(() => {
if (this.query?.status === common.QueryStatusEnum.Running) {
let payload: apiToBackend.ToBackendGetQueryRequestPayload = {
mconfigId: this.mconfig.mconfigId,
queryId: this.query.queryId,
vizId: this.viz.vizId
};
return this.apiService
.req(
apiToBackend.ToBackendRequestInfoNameEnum.ToBackendGetQuery,
payload
)
.pipe(
tap((resp: apiToBackend.ToBackendGetQueryResponse) => {
this.query = resp.payload.query;
this.qData =
mconfig.queryId === this.query.queryId
? this.queryService.makeQData({
data: this.query.data,
columns: this.sortedColumns
})
: [];
this.cd.detectChanges();
})
);
} else {
return of(1);
}
})
)
.subscribe();
this.canEditOrDeleteViz =
member.isEditor || member.isAdmin || this.author === member.alias;
this.canAccessModel =
member.isExplorer === false
? false
: member.isAdmin === true || member.isEditor === true
? true
: model.accessRoles.length === 0 && model.accessUsers.length === 0
? true
: model.accessUsers.indexOf(member.alias) > -1 ||
model.accessRoles.some(x => member.roles.includes(x));
let checkSelectResult = getSelectValid({
chart: mconfig.chart,
sortedColumns: this.sortedColumns
});
this.isSelectValid = checkSelectResult.isSelectValid;
// this.errorMessage = checkSelectResult.errorMessage;
this.cd.detectChanges();
}
explore(event?: MouseEvent) {
event.stopPropagation();
// this.closeMenu();
this.modelStore.update(this.model);
this.mqStore.update(state =>
Object.assign({}, state, { mconfig: this.mconfig, query: this.query })
);
if (this.canAccessModel === true) {
this.navigateService.navigateMconfigQuery({
modelId: this.report.modelId,
mconfigId: this.report.mconfigId,
queryId: this.report.queryId
});
}
}
openMenu() {
this.isVizOptionsMenuOpen = true;
this.uiStore.update({ openedMenuId: this.menuId });
}
closeMenu(event?: MouseEvent) {
if (common.isDefined(event)) {
event.stopPropagation();
}
this.isVizOptionsMenuOpen = false;
this.uiStore.update({ openedMenuId: undefined });
}
toggleMenu(event?: MouseEvent) {
event.stopPropagation();
if (this.isVizOptionsMenuOpen === true) {
this.closeMenu();
} else {
this.openMenu();
}
}
run(event?: MouseEvent) {
event.stopPropagation();
this.closeMenu();
let payload: apiToBackend.ToBackendRunQueriesRequestPayload = {
queryIds: [this.query.queryId]
};
this.apiService
.req(
apiToBackend.ToBackendRequestInfoNameEnum.ToBackendRunQueries,
payload
)
.pipe(
map((resp: apiToBackend.ToBackendRunQueriesResponse) => {
let { runningQueries } = resp.payload;
this.query = runningQueries[0];
}),
take(1)
)
.subscribe();
}
deleteViz(event?: MouseEvent) {
event.stopPropagation();
this.closeMenu();
this.myDialogService.showDeleteViz({
viz: this.viz,
apiService: this.apiService,
vizDeleted: this.vizDeleted,
projectId: this.nav.projectId,
branchId: this.nav.branchId,
isRepoProd: this.nav.isRepoProd
});
}
showChart() {
this.myDialogService.showChart({
mconfig: this.mconfig,
query: this.query,
qData: this.qData,
sortedColumns: this.sortedColumns,
model: this.model,
canAccessModel: this.canAccessModel,
showNav: true,
isSelectValid: this.isSelectValid
});
}
stopClick(event?: MouseEvent) {
event.stopPropagation();
}
editVizInfo(event?: MouseEvent) {
event.stopPropagation();
this.closeMenu();
this.myDialogService.showEditVizInfo({
apiService: this.apiService,
projectId: this.nav.projectId,
branchId: this.nav.branchId,
isRepoProd: this.nav.isRepoProd,
viz: this.viz,
mconfig: this.mconfig
});
}
goToFile(event?: MouseEvent) {
event.stopPropagation();
let fileIdAr = this.viz.filePath.split('/');
fileIdAr.shift();
this.navigateService.navigateToFileLine({
underscoreFileId: fileIdAr.join(common.TRIPLE_UNDERSCORE)
});
}
ngOnDestroy() {
// console.log('ngOnDestroyChartViz')
if (common.isDefined(this.checkRunning$)) {
this.checkRunning$?.unsubscribe();
}
if (this.menuId === this.openedMenuId)
this.uiStore.update({ openedMenuId: undefined });
}
} | the_stack |
declare class GULAppDelegateSwizzler extends NSProxy {
static alloc(): GULAppDelegateSwizzler; // inherited from NSProxy
static isAppDelegateProxyEnabled(): boolean;
static proxyOriginalDelegate(): void;
static proxyOriginalDelegateIncludingAPNSMethods(): void;
static registerAppDelegateInterceptor(interceptor: UIApplicationDelegate): string;
static sharedApplication(): UIApplication;
static unregisterAppDelegateInterceptorWithID(interceptorID: string): void;
}
declare class GULAppEnvironmentUtil extends NSObject {
static alloc(): GULAppEnvironmentUtil; // inherited from NSObject
static applePlatform(): string;
static deploymentType(): string;
static deviceModel(): string;
static hasSwiftRuntime(): boolean;
static isAppExtension(): boolean;
static isAppStoreReceiptSandbox(): boolean;
static isFromAppStore(): boolean;
static isIOS7OrHigher(): boolean;
static isSimulator(): boolean;
static new(): GULAppEnvironmentUtil; // inherited from NSObject
static systemVersion(): string;
}
interface GULHeartbeatDateStorable extends NSObjectProtocol {
heartbeatDateForTag(tag: string): Date;
setHearbeatDateForTag(date: Date, tag: string): boolean;
}
declare var GULHeartbeatDateStorable: {
prototype: GULHeartbeatDateStorable;
};
declare class GULHeartbeatDateStorage extends NSObject implements GULHeartbeatDateStorable {
static alloc(): GULHeartbeatDateStorage; // inherited from NSObject
static new(): GULHeartbeatDateStorage; // inherited from NSObject
readonly fileURL: NSURL;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { fileName: string; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
heartbeatDateForTag(tag: string): Date;
initWithFileName(fileName: string): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
setHearbeatDateForTag(date: Date, tag: string): boolean;
}
declare class GULHeartbeatDateStorageUserDefaults extends NSObject implements GULHeartbeatDateStorable {
static alloc(): GULHeartbeatDateStorageUserDefaults; // inherited from NSObject
static new(): GULHeartbeatDateStorageUserDefaults; // inherited from NSObject
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { defaults: NSUserDefaults; key: string; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
heartbeatDateForTag(tag: string): Date;
initWithDefaultsKey(defaults: NSUserDefaults, key: string): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
setHearbeatDateForTag(date: Date, tag: string): boolean;
}
declare function GULIsLoggableLevel(loggerLevel: GULLoggerLevel): boolean;
declare class GULKeychainStorage extends NSObject {
static alloc(): GULKeychainStorage; // inherited from NSObject
static new(): GULKeychainStorage; // inherited from NSObject
constructor(o: { service: string; });
getObjectForKeyObjectClassAccessGroup(key: string, objectClass: typeof NSObject, accessGroup: string): FBLPromise<NSSecureCoding>;
initWithService(service: string): this;
removeObjectForKeyAccessGroup(key: string, accessGroup: string): FBLPromise<NSNull>;
setObjectForKeyAccessGroup(object: NSSecureCoding, key: string, accessGroup: string): FBLPromise<NSNull>;
}
declare class GULKeychainUtils extends NSObject {
static alloc(): GULKeychainUtils; // inherited from NSObject
static getItemWithQueryError(query: NSDictionary<any, any>): NSData;
static new(): GULKeychainUtils; // inherited from NSObject
static removeItemWithQueryError(query: NSDictionary<any, any>): boolean;
static setItemWithQueryError(item: NSData, query: NSDictionary<any, any>): boolean;
}
declare function GULLoggerEnableSTDERR(): void;
declare function GULLoggerForceDebug(): void;
declare function GULLoggerInitializeASL(): void;
declare const enum GULLoggerLevel {
Error = 3,
Warning = 4,
Notice = 5,
Info = 6,
Debug = 7,
Min = 3,
Max = 7
}
declare function GULLoggerRegisterVersion(version: string): void;
declare class GULLoggerWrapper extends NSObject {
static alloc(): GULLoggerWrapper; // inherited from NSObject
static new(): GULLoggerWrapper; // inherited from NSObject
}
declare class GULMutableDictionary extends NSObject {
static alloc(): GULMutableDictionary; // inherited from NSObject
static new(): GULMutableDictionary; // inherited from NSObject
count(): number;
dictionary(): NSDictionary<any, any>;
objectForKey(key: any): any;
objectForKeyedSubscript(key: any): any;
removeAllObjects(): void;
removeObjectForKey(key: any): void;
setObjectForKey(object: any, key: any): void;
setObjectForKeyedSubscript(obj: any, key: any): void;
}
declare const enum GULNSDataZlibError {
GreaterThan32BitsToCompress = 1024,
Internal = 1025,
DataRemaining = 1026
}
declare var GULNSDataZlibErrorDomain: string;
declare var GULNSDataZlibErrorKey: string;
declare var GULNSDataZlibRemainingBytesKey: string;
declare class GULNetwork extends NSObject {
static alloc(): GULNetwork; // inherited from NSObject
static handleEventsForBackgroundURLSessionIDCompletionHandler(sessionID: string, completionHandler: () => void): void;
static new(): GULNetwork; // inherited from NSObject
isDebugModeEnabled: boolean;
loggerDelegate: GULNetworkLoggerDelegate;
readonly networkConnected: boolean;
reachabilityDelegate: GULNetworkReachabilityDelegate;
timeoutInterval: number;
readonly uploadInProgress: boolean;
constructor(o: { reachabilityHost: string; });
getURLHeadersQueueUsingBackgroundSessionCompletionHandler(url: NSURL, headers: NSDictionary<any, any>, queue: NSObject, usingBackgroundSession: boolean, handler: (p1: NSHTTPURLResponse, p2: NSData, p3: NSError) => void): string;
initWithReachabilityHost(reachabilityHost: string): this;
postURLPayloadQueueUsingBackgroundSessionCompletionHandler(url: NSURL, payload: NSData, queue: NSObject, usingBackgroundSession: boolean, handler: (p1: NSHTTPURLResponse, p2: NSData, p3: NSError) => void): string;
}
declare const enum GULNetworkErrorCode {
NetworkErrorCodeUnknown = 0,
ErrorCodeNetworkInvalidURL = 1,
ErrorCodeNetworkRequestCreation = 2,
ErrorCodeNetworkPayloadCompression = 3,
ErrorCodeNetworkSessionTaskCreation = 4,
ErrorCodeNetworkInvalidResponse = 5
}
declare const enum GULNetworkLogLevel {
kGULNetworkLogLevelError = 3,
kGULNetworkLogLevelWarning = 4,
kGULNetworkLogLevelInfo = 6,
kGULNetworkLogLevelDebug = 7
}
interface GULNetworkLoggerDelegate extends NSObjectProtocol {
GULNetwork_logWithLevelMessageCodeMessage(logLevel: GULNetworkLogLevel, messageCode: GULNetworkMessageCode, message: string): void;
GULNetwork_logWithLevelMessageCodeMessageContext(logLevel: GULNetworkLogLevel, messageCode: GULNetworkMessageCode, message: string, context: any): void;
GULNetwork_logWithLevelMessageCodeMessageContexts(logLevel: GULNetworkLogLevel, messageCode: GULNetworkMessageCode, message: string, contexts: NSArray<any> | any[]): void;
}
declare var GULNetworkLoggerDelegate: {
prototype: GULNetworkLoggerDelegate;
};
declare const enum GULNetworkMessageCode {
kGULNetworkMessageCodeNetwork000 = 900000,
kGULNetworkMessageCodeNetwork001 = 900001,
kGULNetworkMessageCodeNetwork002 = 900002,
kGULNetworkMessageCodeNetwork003 = 900003,
kGULNetworkMessageCodeURLSession000 = 901000,
kGULNetworkMessageCodeURLSession001 = 901001,
kGULNetworkMessageCodeURLSession002 = 901002,
kGULNetworkMessageCodeURLSession003 = 901003,
kGULNetworkMessageCodeURLSession004 = 901004,
kGULNetworkMessageCodeURLSession005 = 901005,
kGULNetworkMessageCodeURLSession006 = 901006,
kGULNetworkMessageCodeURLSession007 = 901007,
kGULNetworkMessageCodeURLSession008 = 901008,
kGULNetworkMessageCodeURLSession009 = 901009,
kGULNetworkMessageCodeURLSession010 = 901010,
kGULNetworkMessageCodeURLSession011 = 901011,
kGULNetworkMessageCodeURLSession012 = 901012,
kGULNetworkMessageCodeURLSession013 = 901013,
kGULNetworkMessageCodeURLSession014 = 901014,
kGULNetworkMessageCodeURLSession015 = 901015,
kGULNetworkMessageCodeURLSession016 = 901016,
kGULNetworkMessageCodeURLSession017 = 901017,
kGULNetworkMessageCodeURLSession018 = 901018,
kGULNetworkMessageCodeURLSession019 = 901019
}
interface GULNetworkReachabilityDelegate {
reachabilityDidChange(): void;
}
declare var GULNetworkReachabilityDelegate: {
prototype: GULNetworkReachabilityDelegate;
};
declare class GULNetworkURLSession extends NSObject {
static alloc(): GULNetworkURLSession; // inherited from NSObject
static handleEventsForBackgroundURLSessionIDCompletionHandler(sessionID: string, completionHandler: () => void): void;
static new(): GULNetworkURLSession; // inherited from NSObject
backgroundNetworkEnabled: boolean;
loggerDelegate: GULNetworkLoggerDelegate;
constructor(o: { networkLoggerDelegate: GULNetworkLoggerDelegate; });
initWithNetworkLoggerDelegate(networkLoggerDelegate: GULNetworkLoggerDelegate): this;
sessionIDFromAsyncGETRequestCompletionHandler(request: NSURLRequest, handler: (p1: NSHTTPURLResponse, p2: NSData, p3: string, p4: NSError) => void): string;
sessionIDFromAsyncPOSTRequestCompletionHandler(request: NSURLRequest, handler: (p1: NSHTTPURLResponse, p2: NSData, p3: string, p4: NSError) => void): string;
}
declare class GULObjectSwizzler extends NSObject {
static alloc(): GULObjectSwizzler; // inherited from NSObject
static getAssociatedObjectKey(object: any, key: string): any;
static new(): GULObjectSwizzler; // inherited from NSObject
static setAssociatedObjectKeyValueAssociation(object: any, key: string, value: any, association: GUL_ASSOCIATION): void;
readonly generatedClass: typeof NSObject;
constructor(o: { object: any; });
copySelectorFromClassIsClassSelector(selector: string, aClass: typeof NSObject, isClassSelector: boolean): void;
getAssociatedObjectForKey(key: string): any;
initWithObject(object: any): this;
isSwizzlingProxyObject(): boolean;
setAssociatedObjectWithKeyValueAssociation(key: string, value: any, association: GUL_ASSOCIATION): void;
swizzle(): void;
}
declare class GULReachabilityChecker extends NSObject {
static alloc(): GULReachabilityChecker; // inherited from NSObject
static new(): GULReachabilityChecker; // inherited from NSObject
readonly host: string;
readonly isActive: boolean;
reachabilityDelegate: GULReachabilityDelegate;
readonly reachabilityStatus: GULReachabilityStatus;
constructor(o: { reachabilityDelegate: GULReachabilityDelegate; withHost: string; });
initWithReachabilityDelegateWithHost(reachabilityDelegate: GULReachabilityDelegate, host: string): this;
start(): boolean;
stop(): void;
}
interface GULReachabilityDelegate {
reachabilityStatusChanged(reachability: GULReachabilityChecker, status: GULReachabilityStatus): void;
}
declare var GULReachabilityDelegate: {
prototype: GULReachabilityDelegate;
};
declare const enum GULReachabilityStatus {
kGULReachabilityUnknown = 0,
kGULReachabilityNotReachable = 1,
kGULReachabilityViaWifi = 2,
kGULReachabilityViaCellular = 3
}
declare function GULReachabilityStatusString(status: GULReachabilityStatus): string;
declare class GULSceneDelegateSwizzler extends NSProxy {
static alloc(): GULSceneDelegateSwizzler; // inherited from NSProxy
static isSceneDelegateProxyEnabled(): boolean;
static proxyOriginalSceneDelegate(): void;
static registerSceneDelegateInterceptor(interceptor: UISceneDelegate): string;
static unregisterSceneDelegateInterceptorWithID(interceptorID: string): void;
}
declare class GULSecureCoding extends NSObject {
static alloc(): GULSecureCoding; // inherited from NSObject
static archivedDataWithRootObjectError(object: NSCoding): NSData;
static new(): GULSecureCoding; // inherited from NSObject
static unarchivedObjectOfClassFromDataError(aClass: typeof NSObject, data: NSData): any;
static unarchivedObjectOfClassesFromDataError(classes: NSSet<typeof NSObject>, data: NSData): any;
}
declare function GULSetLoggerLevel(loggerLevel: GULLoggerLevel): void;
declare class GULSwizzledObject extends NSObject {
static alloc(): GULSwizzledObject; // inherited from NSObject
static copyDonorSelectorsUsingObjectSwizzler(objectSwizzler: GULObjectSwizzler): void;
static new(): GULSwizzledObject; // inherited from NSObject
gul_class(): typeof NSObject;
gul_objectSwizzler(): GULObjectSwizzler;
}
declare class GULSwizzler extends NSObject {
static alloc(): GULSwizzler; // inherited from NSObject
static currentImplementationForClassSelectorIsClassSelector(aClass: typeof NSObject, selector: string, isClassSelector: boolean): interop.FunctionReference<() => void>;
static ivarObjectsForObject(object: any): NSArray<any>;
static new(): GULSwizzler; // inherited from NSObject
static selectorExistsInClassIsClassSelector(selector: string, aClass: typeof NSObject, isClassSelector: boolean): boolean;
static swizzleClassSelectorIsClassSelectorWithBlock(aClass: typeof NSObject, selector: string, isClassSelector: boolean, block: any): void;
}
declare class GULURLSessionDataResponse extends NSObject {
static alloc(): GULURLSessionDataResponse; // inherited from NSObject
static new(): GULURLSessionDataResponse; // inherited from NSObject
readonly HTTPBody: NSData;
readonly HTTPResponse: NSHTTPURLResponse;
constructor(o: { response: NSHTTPURLResponse; HTTPBody: NSData; });
initWithResponseHTTPBody(response: NSHTTPURLResponse, body: NSData): this;
}
declare class GULUserDefaults extends NSObject {
static alloc(): GULUserDefaults; // inherited from NSObject
static new(): GULUserDefaults; // inherited from NSObject
static standardUserDefaults(): GULUserDefaults;
constructor(o: { suiteName: string; });
arrayForKey(defaultName: string): NSArray<any>;
boolForKey(defaultName: string): boolean;
dictionaryForKey(defaultName: string): NSDictionary<string, any>;
doubleForKey(defaultName: string): number;
floatForKey(defaultName: string): number;
initWithSuiteName(suiteName: string): this;
integerForKey(defaultName: string): number;
objectForKey(defaultName: string): any;
removeObjectForKey(defaultName: string): void;
setBoolForKey(value: boolean, defaultName: string): void;
setDoubleForKey(value: number, defaultName: string): void;
setFloatForKey(value: number, defaultName: string): void;
setIntegerForKey(value: number, defaultName: string): void;
setObjectForKey(value: any, defaultName: string): void;
stringForKey(defaultName: string): string;
synchronize(): void;
}
declare const enum GUL_ASSOCIATION {
ASSIGN = 0,
RETAIN_NONATOMIC = 1,
COPY_NONATOMIC = 2,
RETAIN = 3,
COPY = 4
}
declare var GoogleUtilitiesVersionNumber: number;
declare var GoogleUtilitiesVersionString: interop.Reference<number>;
declare var kGULHeartbeatStorageDirectory: string;
declare var kGULKeychainUtilsErrorDomain: string;
declare var kGULNetworkApplicationSupportSubdirectory: string;
declare var kGULNetworkBackgroundSessionConfigIDPrefix: string;
declare var kGULNetworkErrorContext: string;
declare var kGULNetworkHTTPStatusCodeCannotAcceptTraffic: number;
declare var kGULNetworkHTTPStatusCodeFound: number;
declare var kGULNetworkHTTPStatusCodeMovedPermanently: number;
declare var kGULNetworkHTTPStatusCodeMovedTemporarily: number;
declare var kGULNetworkHTTPStatusCodeMultipleChoices: number;
declare var kGULNetworkHTTPStatusCodeNotFound: number;
declare var kGULNetworkHTTPStatusCodeNotModified: number;
declare var kGULNetworkHTTPStatusCodeUnavailable: number;
declare var kGULNetworkHTTPStatusNoContent: number;
declare var kGULNetworkHTTPStatusOK: number;
declare var kGULNetworkReachabilityHost: string;
declare var kGULNetworkTempDirectoryName: string;
declare var kGULNetworkTempFolderExpireTime: number;
declare var kGULNetworkTimeOutInterval: number; | the_stack |
import {BufferUtil} from "./buffer-util";
export class HTTPBuffer {
private _rawContent: Buffer = BufferUtil.fromString("");
private _complete: boolean = false;
// These values all start as undefined - their state is set as we parse the body
// That is because we set them as they are processed
// Each one may be received at different points, so want to be careful about managing state
// They all start as undefined, and then once we know what they, they can be a value or null
// Null is for the case they that they do not exist - such as a body for a GET request
// or queryParameters where there are none
private _chunks: Array<HTTPChunk>;
private _headers: { [id: string]: string };
private _method: string;
private _rawBody: Buffer; // The body of the HTTP message - separate from the headers
private _requestLine: string; // Only set for HTTP Requests
private _statusCode: number;
private _statusLine: string; // Only set for HTTP responses
private _uri: string;
public static errorResponse(message: string): HTTPBuffer {
const buffer = new HTTPBuffer();
const payload = "HTTP/1.1 500 Error\r\nContent-Type: text/plain\r\n"
+ "Content-Length: " + message.length + "\r\n\r\n"
+ message;
buffer.append(Buffer.from(payload));
return buffer;
}
public append(data: Buffer): void {
this._rawContent = Buffer.concat([this._rawContent, data]);
if (this._headers === undefined) {
// Scan for \r\n\r\n - indicates the end of the headers
const endIndex = BufferUtil.scan(this._rawContent, [13, 10, 13, 10]);
if (endIndex !== -1) {
const headerBuffer = this._rawContent.slice(0, endIndex);
this.parseHeaders(headerBuffer.toString());
if (endIndex + 4 < this._rawContent.length) {
const bodyPart = this._rawContent.slice((endIndex + 4));
this.appendBody(bodyPart);
}
}
} else {
this.appendBody(data);
}
}
/**
* Analyzes the payload to see if it has been completely received
* For fixed-length payloads, looks at the content-length and compares that to the body length
* For chunked payloads, looks at the buffer segments
* @returns {boolean}
*/
public complete(): boolean {
if (!this._complete) {
// If we have the headers, then check the body
if (this._headers !== undefined) {
const chunked = this.hasHeader("Transfer-Encoding") && this.header("Transfer-Encoding").toLowerCase() === "chunked";
if (chunked && this._rawBody !== undefined) {
const chunks = this.parseChunks();
// Only store the chunks if they are finalized
if (chunks !== null && chunks.length > 0 && chunks[chunks.length - 1].lastChunk()) {
this._chunks = chunks;
this._complete = true;
}
} else if (this._rawBody !== undefined) {
// If no Content-Length is specified, we default to just the length of this portion
// We do this because we are kind and forgiving
let length = this._rawBody.length;
if (this.hasHeader("Content-Length")) {
length = parseInt(this.header("Content-Length"));
}
this._complete = this._rawBody.length === length;
}
}
}
return this._complete;
}
public header(headerKey: string) {
let value: string = null;
if (this._headers !== undefined && this.hasHeader(headerKey)) {
value = this._headers[headerKey];
}
return value;
}
public hasHeader(headerKey: string) {
return headerKey in this._headers;
}
public method(): string {
return this._method;
}
public uri(): string {
return this._uri;
}
public statusCode(): number {
return this._statusCode;
}
public chunked() {
let chunked = false;
if (this.complete()) {
if (this._chunks !== undefined) {
chunked = true;
}
}
return chunked;
}
public raw(): Buffer {
return this._rawContent;
}
public isJSON(): boolean {
return this.hasHeader("Content-Type") && this.header("Content-Type") === "application/json";
}
// For non-chunked payloads, just returns the raw body
// For chunked payloads, this is the assembled contents of the chunk bodies
public body () {
let body: Buffer;
if (this.complete()) {
body = BufferUtil.fromString("");
if (this.chunked()) {
for (let chunk of this._chunks) {
body = Buffer.concat([body, chunk.body]);
}
} else {
body = this._rawBody;
}
}
return body;
}
// Convenience method to return body as JSON
public bodyAsJSON(): any {
let json: any;
if (this.body() !== undefined) {
json = JSON.parse(this.body().toString());
}
return json;
}
/**
* Parses out the chunks
* @returns {Array<HTTPChunk>}
*/
private parseChunks(): Array<HTTPChunk> {
let chunks: Array<HTTPChunk> = [];
// We will keep taking chunks out of the array with slice
// This is okay because Buffer.slice just changes start and end without duplicating underlying array
let body = this._rawBody;
// Keep looping until we either hit the final chunk (zero-length)
// Or we get an incomplete chunk
while (true) {
const chunk = HTTPChunk.parse(body);
if (chunk !== null) {
chunks.push(chunk);
} else {
// Stop if no chunk is found
break;
}
if (chunk.lastChunk()) {
// Stop if last chunk is found
break;
}
body = body.slice(chunk.lengthWithHeaderAndTrailer());
}
return chunks;
}
private appendBody(bodyPart: Buffer) {
if (this._rawBody === undefined) {
this._rawBody = BufferUtil.fromString("");
}
this._rawBody = Buffer.concat([this._rawBody, bodyPart]);
}
private parseHeaders(headersString: string): void {
this._headers = {};
const lines: Array<string> = headersString.split("\n");
// This is a response if it starts with HTTP
if (lines[0].startsWith("HTTP")) {
this._statusLine = lines[0];
const statusLineParts: Array<string> = this._statusLine.split(" ");
this._statusCode = parseInt(statusLineParts[1]);
} else {
this._requestLine = lines[0];
const requestLineParts: Array<string> = this._requestLine.split(" ");
this._method = requestLineParts[0];
this._uri = requestLineParts[1];
}
// Handle the headers
for (let i = 1; i < lines.length; i++) {
const headerLine: string = lines[i];
const headerParts: Array<string> = headerLine.split(":");
const key = headerParts[0];
this._headers[key] = headerParts[1].trim();
}
}
}
export class HTTPChunk {
public constructor (public body: Buffer, public lengthString: string) {}
public length(): number {
return parseInt(this.lengthString, 16);
}
public headerLength(): number {
return (this.lengthString).length + 2;
}
/**
* The complete chunk length - includes the upfront header + trailing \r\n
* @returns {number}
*/
public lengthWithHeaderAndTrailer(): number {
return this.length() + this.headerLength() + 2;
}
// The last chunk is the one that is zero-length
public lastChunk(): boolean {
return (this.length() === 0);
}
/**
* Tries to parse a chunk from the body
* Body may not be complete yet - returns null if that is the case
* @param httpBody
* @returns {HTTPChunk}
*/
public static parse (httpBody: Buffer): HTTPChunk {
let chunkLengthString = HTTPChunk.parseLength(httpBody);
// This means we don't even have a chunk header yet
if (chunkLengthString === null) {
return null;
}
let chunkLength = parseInt(chunkLengthString, 16);
let chunkStartIndex = chunkLengthString.length + 2; // Skip the chunk length number + /r/n to get the start of the chunk
let endIndex = chunkStartIndex + chunkLength;
// This will happen if not all of the chunk has arrived yet
// This can occur because the payload to the client may be broken up into pieces that do not align
// with chunk boundaries
if (httpBody.length < endIndex) {
return null;
}
let chunkBody = httpBody.slice(chunkStartIndex, chunkStartIndex + chunkLength);
return new HTTPChunk(chunkBody, chunkLengthString);
}
/**
* Finds the chunk length header in the chunk
* It's at the start followed by \r\n
* Example 45\r\n
* @param httpBody
* @returns {number} -1 if a valid chunk length is not found
*/
public static parseLength(httpBody: Buffer): string {
// Find /r/n - the delimiter for the chunk length
let index = BufferUtil.scan(httpBody, [13, 10]);
if (index === -1) {
return null;
}
let chunkLengthString = "";
for (let i = 0; i < index; i++) {
let char = String.fromCharCode(httpBody[i]);
// If one of the characters is not a number - something went wrong
if (isNaN(parseInt(char, 16))) {
throw new RangeError("Invalid character found in chunk length - something went wrong! " + char);
}
chunkLengthString += String.fromCharCode(httpBody[i]);
}
return chunkLengthString;
}
} | the_stack |
import * as td from 'testdouble'
import {pureObserver} from './useObserver'
test('it reacts to a change', () => {
const object = {test: 'abc'}
const obj1Callback = td.func() as () => void
pureObserver(object, obj1Callback)
expect(object.test).toEqual('abc')
td.verify(obj1Callback(), {times: 0})
object.test = 'def'
expect(object.test).toEqual('def')
td.verify(obj1Callback(), {times: 1})
object.test = 'there'
expect(object.test).toEqual('there')
td.verify(obj1Callback(), {times: 2})
})
test('that it can work with multiple objects, no react', () => {
const obj1 = {
foo: 'here',
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
mutateMe: () => {
obj1.foo = 'there'
},
}
const obj2 = {
bar: 'pete',
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
mutateMe: () => {
obj2.bar = 'paul'
},
}
const obj1Callback = td.func()
const obj2Callback = td.func()
pureObserver(obj1, obj1Callback)
pureObserver(obj2, obj2Callback)
expect(obj1.foo).toEqual('here')
expect(obj2.bar).toEqual('pete')
td.verify(obj1Callback(), {times: 0})
td.verify(obj2Callback(), {times: 0})
obj1.mutateMe()
expect(obj1.foo).toEqual('there')
expect(obj2.bar).toEqual('pete')
td.verify(obj1Callback(), {times: 1})
td.verify(obj2Callback(), {times: 0})
obj2.mutateMe()
expect(obj1.foo).toEqual('there')
expect(obj2.bar).toEqual('paul')
td.verify(obj1Callback(), {times: 1})
td.verify(obj2Callback(), {times: 1})
})
test('it should callback for changes in objects added to arrays', () => {
const object = {arr: []}
const obj1Callback = td.func()
pureObserver(object, obj1Callback)
expect(object.arr).toEqual([])
td.verify(obj1Callback(), {times: 0})
object.arr[0] = {hello: 'world'}
expect(object.arr[0].hello).toEqual('world')
td.verify(obj1Callback(), {times: 1})
object.arr[0].hello = 'there'
expect(object.arr[0].hello).toEqual('there')
td.verify(obj1Callback(), {times: 2})
})
test('it should callback for changes in objects added to arrays before observer is attached', () => {
const object = {arr: []}
const obj1Callback = td.func()
object.arr[0] = {hello: 'world'}
pureObserver(object, obj1Callback)
expect(object.arr[0]).toEqual({hello: 'world'})
td.verify(obj1Callback(), {times: 0})
object.arr[0].hello = 'there'
expect(object.arr[0].hello).toEqual('there')
td.verify(obj1Callback(), {times: 2})
})
test('it should callback for changes in objects added to arrays before observer is attached', () => {
const object = {arr: []}
const obj1Callback = td.func()
object.arr[0] = {hello: 'world'}
object.arr[1] = {yo: 'dude'}
pureObserver(object, obj1Callback)
expect(object.arr[0]).toEqual({hello: 'world'})
expect(object.arr[1].yo).toEqual('dude')
td.verify(obj1Callback(), {times: 0})
object.arr[1].yo = 'man'
expect(object.arr[0]).toEqual({hello: 'world'})
expect(object.arr[1].yo).toEqual('man')
td.verify(obj1Callback(), {times: 2})
})
test('overwrite array with something else', () => {
const obj1 = {innerObj: {}, arr: []}
const obj1Callback = td.func()
pureObserver(obj1, obj1Callback)
expect(obj1.innerObj).toEqual({})
expect(obj1.arr).toEqual([])
td.verify(obj1Callback(), {times: 0})
obj1.arr = ['sdg']
expect(obj1.innerObj).toEqual({})
expect(obj1.arr).toEqual(['sdg'])
td.verify(obj1Callback(), {times: 1})
})
test('changing the value of an inner object', () => {
const obj1 = {innerObj: {}}
const obj1Callback = td.func()
pureObserver(obj1, obj1Callback)
expect(obj1.innerObj).toEqual({})
td.verify(obj1Callback(), {times: 0})
// @ts-ignore
obj1.innerObj.test = 's'
// @ts-ignore
expect(obj1.innerObj.test).toEqual('s')
td.verify(obj1Callback(), {times: 1})
})
test('changing the assignment from array to a different array', () => {
const obj1 = {arr: []}
const obj1Callback = td.func()
pureObserver(obj1, obj1Callback)
expect(obj1.arr).toEqual([])
td.verify(obj1Callback(), {times: 0})
obj1.arr = ['sdg']
expect(obj1.arr).toEqual(['sdg'])
td.verify(obj1Callback(), {times: 1})
})
test('undefined array', () => {
const obj1 = {arr: undefined}
const obj1Callback = td.func()
pureObserver(obj1, obj1Callback)
expect(obj1.arr).toEqual(undefined)
td.verify(obj1Callback(), {times: 0})
obj1.arr = ['sdg']
expect(obj1.arr).toEqual(['sdg'])
td.verify(obj1Callback(), {times: 1})
})
test('it should observe provided objects that overwrite internal objects', () => {
const innerObj = {foo: 'something'}
// eslint-disable-next-line no-empty-pattern
const obj1 = {innerObj: {} = {}}
const obj1Callback = td.func()
obj1.innerObj = innerObj
pureObserver(obj1, obj1Callback)
// @ts-ignore
expect(obj1.innerObj.foo).toEqual('something')
td.verify(obj1Callback(), {times: 0})
innerObj.foo = 'bar'
// @ts-ignore
expect(obj1.innerObj.foo).toEqual('bar')
td.verify(obj1Callback(), {times: 1})
})
test('it should observe provided objects that create new internal objects', () => {
const innerObj = {foo: 'test'}
const obj1 = {}
// @ts-ignore
obj1.innerObj = innerObj
const obj1Callback = td.func()
pureObserver(obj1, obj1Callback)
// @ts-ignore
expect(obj1.innerObj.foo).toEqual('test')
td.verify(obj1Callback(), {times: 0})
innerObj.foo = 'bar'
// @ts-ignore
expect(obj1.innerObj.foo).toEqual('bar')
td.verify(obj1Callback(), {times: 1})
})
test('it should observe provided external arrays', () => {
const arr = []
const obj1 = {arr}
const obj1Callback = td.func()
pureObserver(obj1, obj1Callback)
expect(obj1.arr).toEqual([])
expect(obj1.arr).toHaveLength(0)
td.verify(obj1Callback(), {times: 0})
obj1.arr.push('boo')
expect(obj1.arr).toEqual(['boo'])
expect(obj1.arr).toHaveLength(1)
td.verify(obj1Callback(), {times: 1})
})
test('it should observe provided internal arrays', () => {
const obj1 = {arr: []}
const obj1Callback = td.func()
pureObserver(obj1, obj1Callback)
expect(obj1.arr).toEqual([])
expect(obj1.arr).toHaveLength(0)
td.verify(obj1Callback(), {times: 0})
obj1.arr.push('boo')
expect(obj1.arr).toEqual(['boo'])
expect(obj1.arr).toHaveLength(1)
td.verify(obj1Callback(), {times: 1})
})
test('multi-level depth fields are set to an object whose value changes', () => {
const object = {field: {nested: {}}}
const objectCallback = td.func()
pureObserver(object, objectCallback)
expect(object.field.nested).toEqual({})
td.verify(objectCallback(), {times: 0})
object.field.nested = {deep: {very: 'deeper'}}
// @ts-ignore
expect(object.field.nested.deep.very).toEqual('deeper')
td.verify(objectCallback(), {times: 2})
})
test('multi-level depth fields are set to an object whose value changes', () => {
const object = {field: {}}
const objectCallback = td.func()
pureObserver(object, objectCallback)
expect(object.field).toEqual({})
td.verify(objectCallback(), {times: 0})
object.field = {nested: {}}
// @ts-ignore
expect(object.field.nested).toEqual({})
td.verify(objectCallback(), {times: 1})
})
test('multi-level depth fields are set to an object whose value changes', () => {
const object = {field: {}}
const objectCallback = td.func()
pureObserver(object, objectCallback)
expect(object.field).toEqual({})
td.verify(objectCallback(), {times: 0})
object.field = {nested: {}}
// @ts-ignore
expect(object.field.nested).toEqual({})
td.verify(objectCallback(), {times: 1})
// @ts-ignore
object.field.nested = {deep: {very: 'deeper'}}
// @ts-ignore
expect(object.field.nested.deep.very).toEqual('deeper')
td.verify(objectCallback(), {times: 3})
})
test('multi-level depth fields are set to an object whose value changes', () => {
const object = {field: null}
const objectCallback = td.func()
pureObserver(object, objectCallback)
td.verify(objectCallback(), {times: 0})
object.field = {nested: {}}
expect(object.field.nested).toEqual({})
td.verify(objectCallback(), {times: 1})
object.field.nested.deep = {very: 'deeper'}
expect(object.field.nested.deep.very).toEqual('deeper')
td.verify(objectCallback(), {times: 2})
object.field.nested.deep.very = 'changed string'
expect(object.field.nested.deep.very).toEqual('changed string')
td.verify(objectCallback(), {times: 3})
})
test('multi-level depth fields are set to an object whose value changes - no proxy', () => {
const object = {field: {nested: {deep: 'old'}}}
const objectCallback = td.func()
pureObserver(object, objectCallback)
expect(object.field.nested.deep).toEqual('old')
td.verify(objectCallback(), {times: 0})
object.field = {nested: {deep: 'value'}}
expect(object.field.nested.deep).toEqual('value')
td.verify(objectCallback(), {times: 1})
// @ts-ignore
object.field.nested = {deep: {very: 'deeper'}}
// @ts-ignore
expect(object.field.nested.deep.very).toEqual('deeper')
td.verify(objectCallback(), {times: 3})
})
test('multi-level depth fields are set to an object whose value changes', () => {
const object = {field: null}
const objectCallback = td.func()
pureObserver(object, objectCallback)
expect(object.field).toBeNull()
td.verify(objectCallback(), {times: 0})
object.field = {nested: {deep: 'value'}}
expect(object.field.nested.deep).toEqual('value')
td.verify(objectCallback(), {times: 1})
object.field = {nested: {deep: 'newValue'}}
expect(object.field.nested.deep).toEqual('newValue')
td.verify(objectCallback(), {times: 2})
})
test('multi-level depth fields are set to an object whose value changes', () => {
const object = {field: null}
const objectCallback = td.func()
pureObserver(object, objectCallback)
expect(object.field).toBeNull()
td.verify(objectCallback(), {times: 0})
object.field = {nested: {deep: 'value'}}
expect(object.field.nested.deep).toEqual('value')
td.verify(objectCallback(), {times: 1})
object.field.nested.deep = 'newValue'
expect(object.field.nested.deep).toEqual('newValue')
td.verify(objectCallback(), {times: 3})
})
test('multi-level depth fields are set to an object whose value changes - no proxy', () => {
const object = {field: {nested: {deep: ''}}}
const objectCallback = td.func()
pureObserver(object, objectCallback)
expect(object.field.nested.deep).toEqual('')
td.verify(objectCallback(), {times: 0})
object.field.nested.deep = 'value'
expect(object.field.nested.deep).toEqual('value')
td.verify(objectCallback(), {times: 2})
})
test('Setting null to an already null value should not trigger a callback', () => {
const obj = {nullValue: null}
const objectCallback = td.func()
expect(obj.nullValue).toBeNull()
pureObserver(obj, objectCallback)
obj.nullValue = null
expect(obj.nullValue).toBeNull()
td.verify(objectCallback(), {times: 0})
})
test('Setting null to an already null value, then setting a real value should trigger a callback', () => {
const obj = {nullValue: null}
const objectCallback = td.func()
pureObserver(obj, objectCallback)
expect(obj.nullValue).toBeNull()
td.verify(objectCallback(), {times: 0})
obj.nullValue = null
expect(obj.nullValue).toBeNull()
td.verify(objectCallback(), {times: 0})
obj.nullValue = 'something'
expect(obj.nullValue).toEqual('something')
td.verify(objectCallback(), {times: 1})
})
test('Setting null to an assigned property should trigger a callback', () => {
const obj = {nullValue: 'anything'}
const objectCallback = td.func()
pureObserver(obj, objectCallback)
expect(obj.nullValue).toEqual('anything')
td.verify(objectCallback(), {times: 0})
obj.nullValue = null
expect(obj.nullValue).toBeNull()
td.verify(objectCallback(), {times: 1})
})
test('Setting null to an assigned property, then setting a real value should trigger a callback', () => {
const obj = {
nullValue: 'anything',
}
const objectCallback = td.func()
pureObserver(obj, objectCallback)
expect(obj.nullValue).toEqual('anything')
td.verify(objectCallback(), {times: 0})
obj.nullValue = null
expect(obj.nullValue).toBeNull()
td.verify(objectCallback(), {times: 1})
obj.nullValue = 'something'
expect(obj.nullValue).toEqual('something')
td.verify(objectCallback(), {times: 2})
})
test('Arrays pop', () => {
const obj = {arr: ['a']}
const obj1Callback = td.func()
pureObserver(obj, obj1Callback)
const p = obj.arr.pop()
expect(p).toEqual('a')
expect(obj.arr).toHaveLength(0)
td.verify(obj1Callback(), {times: 1})
})
test('Arrays splice', () => {
const obj = {arr: ['a', 'b', 'c', 'd']}
const obj1Callback = td.func()
pureObserver(obj, obj1Callback)
expect(obj.arr).toEqual(['a', 'b', 'c', 'd'])
td.verify(obj1Callback(), {times: 0})
obj.arr.splice(2, 2)
expect(obj.arr).toHaveLength(2)
expect(obj.arr).toEqual(['a', 'b'])
td.verify(obj1Callback(), {times: 1})
})
test('it should observe provided arrays that overwrite internal arrays', () => {
const arr = []
const obj1 = {arr: []}
const obj1Callback = td.func()
obj1.arr = arr
pureObserver(obj1, obj1Callback)
expect(obj1.arr).toEqual([])
td.verify(obj1Callback(), {times: 0})
obj1.arr.push('boo')
expect(obj1.arr).toEqual(['boo'])
expect(obj1.arr).toHaveLength(1)
td.verify(obj1Callback(), {times: 1})
})
test('obj with a prop that is an object, set prop to null, then set prop to a string. should trigger 2 callbacks', () => {
const obj = {prop: {}}
const objectCallback = td.func()
pureObserver(obj, objectCallback)
expect(obj.prop).toEqual({})
td.verify(objectCallback(), {times: 0})
obj.prop = null
expect(obj.prop).toBeNull()
td.verify(objectCallback(), {times: 1})
obj.prop = 'asd'
expect(obj.prop).toEqual('asd')
td.verify(objectCallback(), {times: 2})
})
test('obj with a prop that is an object, set prop to null, then set prop to an array. should trigger 2 callbacks', () => {
const obj = {prop: {}}
const objectCallback = td.func()
pureObserver(obj, objectCallback)
expect(obj.prop).toEqual({})
td.verify(objectCallback(), {times: 0})
obj.prop = null
expect(obj.prop).toBeNull()
td.verify(objectCallback(), {times: 1})
obj.prop = []
expect(obj.prop).toEqual([])
td.verify(objectCallback(), {times: 2})
})
test('Setting null to an existing property and observe, then setting a real value should trigger a callback', () => {
const obj = {prop: {}}
const objectCallback = td.func()
pureObserver(obj, objectCallback)
expect(obj.prop).toEqual({})
td.verify(objectCallback(), {times: 0})
obj.prop = null
expect(obj.prop).toBeNull()
td.verify(objectCallback(), {times: 1})
})
test('obj with a prop that is an object, set prop to null, then set prop to a object. should trigger 2 callbacks', () => {
const obj = {prop: {}}
const objectCallback = td.func()
pureObserver(obj, objectCallback)
expect(obj.prop).toEqual({})
td.verify(objectCallback(), {times: 0})
obj.prop = null
expect(obj.prop).toBeNull()
td.verify(objectCallback(), {times: 1})
obj.prop = {}
expect(obj.prop).toEqual({__proxyAttached: true})
td.verify(objectCallback(), {times: 2})
})
// - - OUTSTANDING BUGS - -
describe('fix callback', () => {
test('deep array', () => {
const obj = {
nestedObj: {
deepArray: [],
},
}
const objectCallback = td.func()
pureObserver(obj, objectCallback)
td.verify(objectCallback(), {times: 3})
})
})
// - - UNSUPPORTED - -
describe.skip('UNSUPPORTED', () => {
test('CAN THIS EVER WORK? - ARRAY IS CHANGED OUTSIDE OF OBSERVED OBJECT', () => {
const arr = []
const obj1 = {arr: []}
const obj1Callback = td.func()
obj1.arr = arr
pureObserver(obj1, obj1Callback)
td.verify(obj1Callback(), {times: 0})
arr.push('boo')
td.verify(obj1Callback(), {times: 1})
})
}) | the_stack |
import React, { useEffect, useState } from "react";
import format from "date-fns/format";
import { ThemeProvider } from "styled-components";
import "./styles.scss";
// Icons
import { ReactComponent as ChevronUpIcon } from "assets/svg/chevron_up.svg";
import { ReactComponent as ClearIcon } from "assets/svg/clear.svg";
import { ReactComponent as CloseIcon } from "assets/svg/close.svg";
import { ReactComponent as CopyIcon } from "assets/svg/copy.svg";
import { ReactComponent as SideBySideIcon } from "assets/svg/side_by_side.svg";
import { ReactComponent as UpDownIcon } from "assets/svg/up_down.svg";
import AppLoader from "components/appLoader";
import { GlobalStyles } from "globalStyles";
import {
generateUrl,
poll,
decryptAESKey,
processData,
copyDataToClipboard,
clearIntervals,
register,
} from "lib";
import { notifyTelegram, notifySlack, notifyDiscord } from "lib/notify";
import Data from "lib/types/data";
import { StoredData } from "lib/types/storedData";
import Tab from "lib/types/tab";
import View from "lib/types/view";
import { ThemeName, getTheme } from "theme";
import Header from "../../components/header";
import TabSwitcher from "../../components/tabSwitcher";
import { writeStoredData, getStoredData, defaultStoredData } from "../../lib/localStorage";
import RequestDetailsWrapper from "./requestDetailsWrapper";
import RequestsTableWrapper from "./requestsTableWrapper";
const HomePage = () => {
const [aboutPopupVisibility, setAboutPopupVisibility] = useState<boolean>(false);
const [filteredData, setFilteredData] = useState<Array<Data>>([]);
const [isNotesOpen, setIsNotesOpen] = useState<boolean>(false);
const [isRegistered, setIsRegistered] = useState<boolean>(false);
const [isResetPopupDialogVisible, setIsResetPopupDialogVisible] = useState<boolean>(false);
const [isNotificationsDialogVisible, setIsNotificationsDialogVisible] = useState<boolean>(false);
const [loaderAnimationMode, setLoaderAnimationMode] = useState<string>("loading");
const [selectedInteraction, setSelectedInteraction] = useState<string | null>(null);
const [selectedInteractionData, setSelectedInteractionData] = useState<Data | null>(null);
const [storedData, setStoredData] = useState<StoredData>(getStoredData());
const [isCustomHostDialogVisible, setIsCustomHostDialogVisible] = useState(false);
const handleResetPopupDialogVisibility = () => {
setIsResetPopupDialogVisible(!isResetPopupDialogVisible);
};
const handleNotificationsDialogVisibility = () => {
setIsNotificationsDialogVisible(!isNotificationsDialogVisible);
};
const handleCustomHostDialogVisibility = () => {
setIsCustomHostDialogVisible(!isCustomHostDialogVisible);
};
// "Switch theme" function
const handleThemeSelection = (value: ThemeName) => {
setStoredData({
...storedData,
theme: value,
});
};
// "Select a tab" function
const handleTabButtonClick = (tab: Tab) => {
setStoredData({
...storedData,
selectedTab: tab,
});
setSelectedInteraction(null);
};
// " Add new tab" function
const handleAddNewTab = () => {
const { increment, host, correlationId } = storedData;
const newIncrement = increment + 1;
const { url, uniqueId } = generateUrl(correlationId, newIncrement, host);
const tabData: Tab = {
"unique-id": uniqueId,
correlationId,
name: newIncrement.toString(),
url,
note: "",
};
setStoredData({
...storedData,
tabs: storedData.tabs.concat([tabData]),
selectedTab: tabData,
increment: newIncrement,
});
setSelectedInteraction(null);
};
// "Show or hide notes" function
const handleNotesVisibility = () => {
setTimeout(() => {
document.getElementById("notes_textarea")?.focus();
}, 200);
setIsNotesOpen(!isNotesOpen);
};
// "Notes input change handler" function
const handleNoteInputChange: React.ChangeEventHandler<HTMLTextAreaElement> = (e) => {
const { selectedTab, tabs } = storedData;
const index = tabs.findIndex((item) => Tab.eq.equals(item, selectedTab));
const currentTab = tabs[index];
const filteredTabList = tabs.filter((item) => !Tab.eq.equals(item, selectedTab));
filteredTabList.push({ ...currentTab, note: e.target.value });
setStoredData({
...storedData,
tabs: filteredTabList,
});
};
// "Selecting a specific interaction" function
const handleRowClick = (id: string) => {
setSelectedInteraction(id);
const reqDetails =
filteredData && filteredData[filteredData.findIndex((item) => item.id === id)];
setSelectedInteractionData(reqDetails);
};
// "Deleting a tab" function
const handleDeleteTab = (tab: Tab) => {
const { tabs } = storedData;
const index = tabs.findIndex((value) => Tab.eq.equals(value, tab));
const filteredTempTabsList = tabs.filter((value) => !Tab.eq.equals(value, tab));
const tempTabsData = storedData.data;
const filteredTempTabsData = tempTabsData.filter(
(value) => value["unique-id"] !== tab["unique-id"]
);
setStoredData({
...storedData,
tabs: [...filteredTempTabsList],
selectedTab: {
...filteredTempTabsList[filteredTempTabsList.length <= index ? index - 1 : index],
},
data: filteredTempTabsData,
});
};
// "Renaming a tab" function
const handleTabRename: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const tempTabsList = storedData.tabs;
const index = tempTabsList.findIndex((item) => Tab.eq.equals(item, storedData.selectedTab));
const filteredTabList = tempTabsList.filter(
(item) => !Tab.eq.equals(item, storedData.selectedTab)
);
const tempTab = { ...tempTabsList[index], name: e.target.value };
setStoredData({
...storedData,
tabs: filteredTabList.concat(tempTab),
});
};
// "View selector" function
const handleChangeView = (value: View) => {
setStoredData({
...storedData,
view: value,
});
};
// "Show or hide about popup" function
const handleAboutPopupVisibility = () => {
setAboutPopupVisibility(!aboutPopupVisibility);
};
// "Clear interactions of a tab" function
const clearInteractions = () => {
const { selectedTab, data } = storedData;
const tempData = data.filter((item) => item["unique-id"] !== selectedTab["unique-id"]);
setStoredData({
...storedData,
data: tempData,
});
setFilteredData([]);
};
const processPolledData = () => {
const dataFromLocalStorage = getStoredData();
const { privateKey, aesKey, host, token, data, correlationId, secretKey } =
dataFromLocalStorage;
let decryptedAESKey = aesKey;
poll(
correlationId,
secretKey,
host,
token,
handleResetPopupDialogVisibility,
handleCustomHostDialogVisibility
)
.then((pollData) => {
setIsRegistered(true);
if (pollData?.data?.length !== 0 && !pollData.error) {
if (aesKey === "" && pollData.aes_key) {
decryptedAESKey = decryptAESKey(privateKey, pollData.aes_key);
}
const processedData = processData(decryptedAESKey, pollData);
// eslint-disable-next-line array-callback-return
const formattedString = processedData.map((item: any) => {
const telegramMsg = `<i>[${item['full-id']}]</i> Received <i>${item.protocol.toUpperCase()}</i> interaction from <b><a href="https://ipinfo.io/${item['remote-address']}">${item['remote-address']}</a></b> at <i>${format(new Date(item.timestamp), "yyyy-mm-dd_hh:mm:ss")}</i>`
storedData.telegram.enabled && notifyTelegram(telegramMsg, storedData.telegram.botToken, storedData.telegram.chatId, 'HTML')
return {
slack: `[${item['full-id']}] Received ${item.protocol.toUpperCase()} interaction from \n <https://ipinfo.io/${item['remote-address']}|${item['remote-address']}> at ${format(new Date(item.timestamp), "yyyy-mm-dd_hh:mm:ss")}`,
discord: `[${item['full-id']}] Received ${item.protocol.toUpperCase()} interaction from \n [${item['remote-address']}](https://ipinfo.io/${item['remote-address']}) at ${format(new Date(item.timestamp), "yyyy-mm-dd_hh:mm:ss")}`,
}
})
storedData.slack.enabled && notifySlack(formattedString, storedData.slack.hookKey, storedData.slack.channel)
storedData.discord.enabled && notifyDiscord(formattedString, storedData.discord.webhook)
const combinedData: Data[] = data.concat(processedData);
setStoredData({
...dataFromLocalStorage,
data: combinedData,
aesKey: decryptedAESKey,
});
const newData = combinedData
.filter((item) => item["unique-id"] === dataFromLocalStorage.selectedTab["unique-id"])
.map((item) => item);
setFilteredData([...newData]);
}
})
.catch(() => {
setLoaderAnimationMode("server_error");
setIsRegistered(false);
});
};
useEffect(() => {
writeStoredData(storedData);
}, [storedData]);
useEffect(() => {
window.addEventListener("storage", () => {
setStoredData(getStoredData());
});
setIsRegistered(true);
if (storedData.correlationId === "") {
setLoaderAnimationMode("loading");
setIsRegistered(false);
setTimeout(() => {
register(storedData.host, "", false, false)
.then((data) => {
setStoredData(data);
window.setInterval(() => {
processPolledData();
}, 4000);
setIsRegistered(true);
})
.catch(() => {
localStorage.clear();
setStoredData(defaultStoredData);
setLoaderAnimationMode("server_error");
setIsRegistered(false);
});
}, 1500);
}
}, []);
// Recalculate data when a tab is selected
useEffect(() => {
if (storedData.tabs.length > 0) {
clearIntervals();
window.setInterval(() => {
processPolledData();
}, 4000);
const tempFilteredData = storedData.data
.filter((item) => item["unique-id"] === storedData.selectedTab["unique-id"])
.map((item) => item);
setFilteredData(tempFilteredData);
}
}, [storedData.selectedTab]);
const selectedTabsIndex = storedData.tabs.findIndex((item) =>
Tab.eq.equals(item, storedData.selectedTab)
);
return (
<ThemeProvider theme={getTheme(storedData.theme)}>
<GlobalStyles />
<div className="main">
<AppLoader isRegistered={isRegistered} mode={loaderAnimationMode} />
{aboutPopupVisibility && (
<div className="about_popup_wrapper">
<div className="about_popup">
<div className="about_popup_header">
<span>About</span>
<CloseIcon style={{ width: 14 }} onClick={handleAboutPopupVisibility} />
</div>
<div className="about_popup_body">
Interactsh is an Open-Source solution for Out of band Data Extraction, A tool
designed to detect bugs that cause external interactions, For example - Blind SQLi,
Blind CMDi, SSRF, etc.
<br />
<br />
If you find communications or exchanges with the Interactsh.com server in your logs, it
is possible that someone has been testing your applications using our hosted
service,
<a href="https://app.interactsh.com" target="__blank">
{` app.interactsh.com `}
</a>
You should review the time when these interactions were initiated to identify the
person responsible for this testing.
<br />
<br />
For further details about Interactsh.com,
<a href="https://github.com/projectdiscovery/interactsh" target="__blank">
{` checkout opensource code.`}
</a>
</div>
</div>
</div>
)}
<Header
handleAboutPopupVisibility={handleAboutPopupVisibility}
theme={storedData.theme}
host={storedData.host}
handleThemeSelection={handleThemeSelection}
isResetPopupDialogVisible={isResetPopupDialogVisible}
isNotificationsDialogVisible={isNotificationsDialogVisible}
handleResetPopupDialogVisibility={handleResetPopupDialogVisibility}
handleNotificationsDialogVisibility={handleNotificationsDialogVisibility}
isCustomHostDialogVisible={isCustomHostDialogVisible}
handleCustomHostDialogVisibility={handleCustomHostDialogVisibility}
/>
<TabSwitcher
handleTabButtonClick={handleTabButtonClick}
selectedTab={storedData.selectedTab}
data={[...storedData.tabs]}
handleAddNewTab={handleAddNewTab}
handleDeleteTab={handleDeleteTab}
handleTabRename={handleTabRename}
processPolledData={processPolledData}
/>
<div className="body">
<div className="left_section">
<div className="url_container secondary_bg">
<div title={storedData.selectedTab && storedData.selectedTab.url}>
{storedData.selectedTab && storedData.selectedTab.url}
</div>
<CopyIcon onClick={() => copyDataToClipboard(storedData.selectedTab.url)} />
<div className="vertical_bar" />
<ClearIcon
className={
filteredData && filteredData.length <= 0 ? "clear_button__disabled" : undefined
}
onClick={clearInteractions}
/>
</div>
<RequestsTableWrapper
data={[...filteredData]}
selectedInteraction={selectedInteraction as any}
handleRowClick={handleRowClick}
filter={storedData.filter}
/>
<div className="notes light_bg">
<div className="detailed_notes" style={{ display: isNotesOpen ? "flex" : "none" }}>
{/* <SyntaxHighlighter language="javascript" style={dark}> */}
{/* {tabs[selectedTabsIndex].note} */}
<textarea
id="notes_textarea"
className="light_bg"
placeholder="You can paste your notes here (max 1200 characters)"
value={
storedData.tabs[selectedTabsIndex] && storedData.tabs[selectedTabsIndex].note
}
onChange={handleNoteInputChange}
/>
{/* </SyntaxHighlighter> */}
</div>
<button type="button" onClick={handleNotesVisibility} className="notes_footer">
<span>Notes</span>
<ChevronUpIcon
style={{
transform: isNotesOpen ? "rotate(180deg)" : "rotate(0)",
}}
/>
</button>
</div>
</div>
{selectedInteraction !== null && selectedInteractionData !== null && (
<div className="right_section">
<div className="result_header">
{selectedInteractionData.protocol !== "smtp" && (
<>
<div className="req_res_buttons">
<button
type="button"
className={
View.eq.equals(storedData.view, "request")
? "__selected_req_res_button"
: undefined
}
onClick={() => handleChangeView("request")}
>
Request
</button>
<button
type="button"
className={
View.eq.equals(storedData.view, "response")
? "__selected_req_res_button"
: undefined
}
onClick={() => handleChangeView("response")}
>
Response
</button>
</div>
<SideBySideIcon
style={{
fill: View.eq.equals(storedData.view, "side_by_side")
? "#ffffff"
: "#4a4a4a",
}}
onClick={() => handleChangeView("side_by_side")}
/>
<UpDownIcon
style={{
fill: View.eq.equals(storedData.view, "up_and_down")
? "#ffffff"
: "#4a4a4a",
}}
onClick={() => handleChangeView("up_and_down")}
/>
</>
)}
<div className="result_info">
From IP address
<span>: <a target="__blank" href={`https://ipinfo.io/${selectedInteractionData["remote-address"]}`}>{selectedInteractionData["remote-address"]}</a></span>
{` at `}
<span>
{format(new Date(selectedInteractionData.timestamp), "yyyy-MM-dd_hh:mm")}
</span>
</div>
</div>
<RequestDetailsWrapper
selectedInteractionData={selectedInteractionData as any}
view={storedData.view}
/>
</div>
)}
</div>
</div>
</ThemeProvider>
);
};
export default HomePage; | the_stack |
import { Equatable } from "@siteimprove/alfa-equatable";
import { Serializable } from "@siteimprove/alfa-json";
import { Parser } from "@siteimprove/alfa-parser";
import { Predicate } from "@siteimprove/alfa-predicate";
import { Result, Err } from "@siteimprove/alfa-result";
import { Refinement } from "@siteimprove/alfa-refinement";
import { Slice } from "@siteimprove/alfa-slice";
import * as json from "@siteimprove/alfa-json";
const { fromCharCode } = String;
const { and } = Refinement;
/**
* @public
*/
export type Token =
| Token.Ident
| Token.Function
| Token.AtKeyword
| Token.Hash
| Token.String
| Token.URL
| Token.BadURL
| Token.Delim
| Token.Number
| Token.Percentage
| Token.Dimension
| Token.Whitespace
| Token.Colon
| Token.Semicolon
| Token.Comma
| Token.OpenParenthesis
| Token.CloseParenthesis
| Token.OpenSquareBracket
| Token.CloseSquareBracket
| Token.OpenCurlyBracket
| Token.CloseCurlyBracket
| Token.OpenComment
| Token.CloseComment;
/**
* @public
*/
export namespace Token {
export type JSON =
| Ident.JSON
| Function.JSON
| AtKeyword.JSON
| Hash.JSON
| String.JSON
| URL.JSON
| BadURL.JSON
| Delim.JSON
| Number.JSON
| Percentage.JSON
| Dimension.JSON
| Whitespace.JSON
| Colon.JSON
| Semicolon.JSON
| Comma.JSON
| OpenParenthesis.JSON
| CloseParenthesis.JSON
| OpenSquareBracket.JSON
| CloseSquareBracket.JSON
| OpenCurlyBracket.JSON
| CloseCurlyBracket.JSON
| OpenComment.JSON
| CloseComment.JSON;
export class Ident implements Equatable, Serializable<Ident.JSON> {
public static of(value: string): Ident {
return new Ident(value);
}
private readonly _value: string;
private constructor(value: string) {
this._value = value;
}
public get type(): "ident" {
return "ident";
}
public get value(): string {
return this._value;
}
public equals(value: unknown): value is this {
return value instanceof Ident && value._value === this._value;
}
public toJSON(): Ident.JSON {
return {
type: "ident",
value: this._value,
};
}
public toString(): string {
return this._value;
}
}
export namespace Ident {
export interface JSON {
[key: string]: json.JSON;
type: "ident";
value: string;
}
export function isIdent(value: unknown): value is Ident {
return value instanceof Ident;
}
}
export const { of: ident, isIdent } = Ident;
export function parseIdent(query: string | Predicate<Ident> = () => true) {
let predicate: Predicate<Ident>;
if (typeof query === "function") {
predicate = query;
} else {
const value = query;
predicate = (ident) => ident.value === value;
}
return parseToken(and(isIdent, predicate));
}
export class Function implements Equatable, Serializable<Function.JSON> {
public static of(value: string): Function {
return new Function(value);
}
private readonly _value: string;
private constructor(value: string) {
this._value = value;
}
public get type(): "function" {
return "function";
}
public get value(): string {
return this._value;
}
public get mirror(): CloseParenthesis {
return CloseParenthesis.of();
}
public equals(value: unknown): value is this {
return value instanceof Function && value._value === this._value;
}
public toJSON(): Function.JSON {
return {
type: "function",
value: this._value,
};
}
public toString(): string {
return `${this._value}(`;
}
}
export namespace Function {
export interface JSON {
[key: string]: json.JSON;
type: "function";
value: string;
}
export function isFunction(value: unknown): value is Function {
return value instanceof Function;
}
}
export const { of: func, isFunction } = Function;
export function parseFunction(
query: string | Predicate<Function> = () => true
) {
let predicate: Predicate<Function>;
if (typeof query === "function") {
predicate = query;
} else {
const value = query;
predicate = (ident) => ident.value === value;
}
return parseToken(and(isFunction, predicate));
}
export class AtKeyword implements Equatable, Serializable<AtKeyword.JSON> {
public static of(value: string): AtKeyword {
return new AtKeyword(value);
}
private readonly _value: string;
private constructor(value: string) {
this._value = value;
}
public get type(): "at-keyword" {
return "at-keyword";
}
public get value(): string {
return this._value;
}
public equals(value: unknown): value is this {
return value instanceof AtKeyword && value._value === this._value;
}
public toJSON(): AtKeyword.JSON {
return {
type: "at-keyword",
value: this._value,
};
}
public toString(): string {
return `@${this._value}`;
}
}
export namespace AtKeyword {
export interface JSON {
[key: string]: json.JSON;
type: "at-keyword";
value: string;
}
}
export const { of: atKeyword } = AtKeyword;
export class Hash implements Equatable, Serializable<Hash.JSON> {
public static of(value: string, isIdentifier: boolean): Hash {
return new Hash(value, isIdentifier);
}
private readonly _value: string;
private readonly _isIdentifier: boolean;
private constructor(value: string, isIdentifier: boolean) {
this._value = value;
this._isIdentifier = isIdentifier;
}
public get type(): "hash" {
return "hash";
}
public get value(): string {
return this._value;
}
public get isIdentifier(): boolean {
return this._isIdentifier;
}
public equals(value: unknown): value is this {
return (
value instanceof Hash &&
value._value === this._value &&
value._isIdentifier === this._isIdentifier
);
}
public toJSON(): Hash.JSON {
return {
type: "hash",
value: this._value,
isIdentifier: this._isIdentifier,
};
}
public toString(): string {
return `#${this._value}`;
}
}
export namespace Hash {
export interface JSON {
[key: string]: json.JSON;
type: "hash";
value: string;
isIdentifier: boolean;
}
export function isHash(value: unknown): value is Hash {
return value instanceof Hash;
}
}
export const { of: hash, isHash } = Hash;
export function parseHash(predicate: Predicate<Hash> = () => true) {
return parseToken(and(isHash, predicate));
}
export class String implements Equatable, Serializable<String.JSON> {
public static of(value: string): String {
return new String(value);
}
private readonly _value: string;
private constructor(value: string) {
this._value = value;
}
public get type(): "string" {
return "string";
}
public get value(): string {
return this._value;
}
public equals(value: unknown): value is this {
return value instanceof String && value._value === this._value;
}
public toJSON(): String.JSON {
return {
type: "string",
value: this._value,
};
}
public toString(): string {
return `"${this._value.replace(/"/g, `\\"`)}"`;
}
}
export namespace String {
export interface JSON {
[key: string]: json.JSON;
type: "string";
value: string;
}
export function isString(value: unknown): value is String {
return value instanceof String;
}
}
export const { of: string, isString } = String;
export function parseString(predicate: Predicate<String> = () => true) {
return parseToken(and(isString, predicate));
}
export class URL implements Equatable, Serializable<URL.JSON> {
public static of(value: string): URL {
return new URL(value);
}
private readonly _value: string;
private constructor(value: string) {
this._value = value;
}
public get type(): "url" {
return "url";
}
public get value(): string {
return this._value;
}
public equals(value: unknown): value is this {
return value instanceof URL && value._value === this._value;
}
public toJSON(): URL.JSON {
return {
type: "url",
value: this._value,
};
}
public toString(): string {
return `url(${this._value})`;
}
}
export namespace URL {
export interface JSON {
[key: string]: json.JSON;
type: "url";
value: string;
}
export function isURL(value: unknown): value is URL {
return value instanceof URL;
}
}
export const { of: url, isURL } = URL;
export function parseURL(predicate: Predicate<URL> = () => true) {
return parseToken(and(isURL, predicate));
}
export class BadURL implements Equatable, Serializable<BadURL.JSON> {
public static of(): BadURL {
return new BadURL();
}
private constructor() {}
public get type(): "bad-url" {
return "bad-url";
}
public equals(value: unknown): value is this {
return value instanceof BadURL;
}
public toJSON(): BadURL.JSON {
return {
type: "bad-url",
};
}
public toString(): string {
return "";
}
}
export namespace BadURL {
export interface JSON {
[key: string]: json.JSON;
type: "bad-url";
}
}
export const { of: badURL } = BadURL;
export class Delim implements Equatable, Serializable<Delim.JSON> {
private static _delims = new Map<number, Delim>();
public static of(value: number): Delim {
let delim = Delim._delims.get(value);
if (delim === undefined) {
delim = new Delim(value);
Delim._delims.set(value, delim);
}
return delim;
}
private readonly _value: number;
private constructor(value: number) {
this._value = value;
}
public get type(): "delim" {
return "delim";
}
public get value(): number {
return this._value;
}
public equals(value: unknown): value is this {
return value instanceof Delim && value._value === this._value;
}
public toJSON(): Delim.JSON {
return {
type: "delim",
value: this._value,
};
}
public toString(): string {
return fromCharCode(this._value);
}
}
export namespace Delim {
export interface JSON {
[key: string]: json.JSON;
type: "delim";
value: number;
}
export function isDelim(value: unknown): value is Delim {
return value instanceof Delim;
}
}
export const { of: delim, isDelim } = Delim;
export function parseDelim(
query: string | number | Predicate<Delim> = () => true
) {
let predicate: Predicate<Delim>;
if (typeof query === "function") {
predicate = query;
} else {
const value = typeof query === "number" ? query : query.charCodeAt(0);
predicate = (delim) => delim.value === value;
}
return parseToken(and(isDelim, predicate));
}
export class Number implements Equatable, Serializable<Number.JSON> {
public static of(
value: number,
isInteger: boolean,
isSigned: boolean
): Number {
return new Number(value, isInteger, isSigned);
}
private readonly _value: number;
private readonly _isInteger: boolean;
private readonly _isSigned: boolean;
private constructor(value: number, isInteger: boolean, isSigned: boolean) {
this._value = value;
this._isInteger = isInteger;
this._isSigned = isSigned;
}
public get type(): "number" {
return "number";
}
public get value(): number {
return this._value;
}
public get isInteger(): boolean {
return this._isInteger;
}
public get isSigned(): boolean {
return this._isSigned;
}
public equals(value: unknown): value is this {
return (
value instanceof Number &&
value._value === this._value &&
value._isInteger === this._isInteger &&
value._isSigned === this._isSigned
);
}
public toJSON(): Number.JSON {
return {
type: "number",
value: this._value,
isInteger: this._isInteger,
isSigned: this._isSigned,
};
}
public toString(): string {
// If the token is explicitly signed and the value is positive, we must
// add a `+` as this won't be included in the stringified value.
const sign = this._isSigned && this._value >= 0 ? "+" : "";
return `${sign}${this._value}`;
}
}
export namespace Number {
export interface JSON {
[key: string]: json.JSON;
type: "number";
value: number;
isInteger: boolean;
isSigned: boolean;
}
export function isNumber(value: unknown): value is Number {
return value instanceof Number;
}
}
export const { of: number, isNumber } = Number;
export function parseNumber(predicate: Predicate<Number> = () => true) {
return parseToken(and(isNumber, predicate));
}
export class Percentage implements Equatable, Serializable<Percentage.JSON> {
public static of(value: number, isInteger: boolean): Percentage {
return new Percentage(value, isInteger);
}
private readonly _value: number;
private readonly _isInteger: boolean;
private constructor(value: number, isInteger: boolean) {
this._value = value;
this._isInteger = isInteger;
}
public get type(): "percentage" {
return "percentage";
}
public get value(): number {
return this._value;
}
public get isInteger(): boolean {
return this._isInteger;
}
public equals(value: unknown): value is this {
return (
value instanceof Percentage &&
value._value === this._value &&
value._isInteger === this._isInteger
);
}
public toJSON(): Percentage.JSON {
return {
type: "percentage",
value: this._value,
isInteger: this._isInteger,
};
}
public toString(): string {
return `${this._value * 100}%`;
}
}
export namespace Percentage {
export interface JSON {
[key: string]: json.JSON;
type: "percentage";
value: number;
isInteger: boolean;
}
export function isPercentage(value: unknown): value is Percentage {
return value instanceof Percentage;
}
}
export const { of: percentage, isPercentage } = Percentage;
export function parsePercentage(
predicate: Predicate<Percentage> = () => true
) {
return parseToken(and(isPercentage, predicate));
}
export class Dimension implements Equatable, Serializable<Dimension.JSON> {
public static of(
value: number,
unit: string,
isInteger: boolean,
isSigned: boolean
): Dimension {
return new Dimension(value, unit, isInteger, isSigned);
}
private readonly _value: number;
private readonly _unit: string;
private readonly _isInteger: boolean;
private readonly _isSigned: boolean;
private constructor(
value: number,
unit: string,
isInteger: boolean,
isSigned: boolean
) {
this._value = value;
this._unit = unit;
this._isInteger = isInteger;
this._isSigned = isSigned;
}
public get type(): "dimension" {
return "dimension";
}
public get value(): number {
return this._value;
}
public get unit(): string {
return this._unit;
}
public get isInteger(): boolean {
return this._isInteger;
}
public get isSigned(): boolean {
return this._isSigned;
}
public equals(value: unknown): value is this {
return (
value instanceof Dimension &&
value._value === this._value &&
value._unit === this._unit &&
value._isInteger === this._isInteger &&
value._isSigned === this._isSigned
);
}
public toJSON(): Dimension.JSON {
return {
type: "dimension",
value: this._value,
unit: this._unit,
isInteger: this._isInteger,
isSigned: this._isSigned,
};
}
public toString(): string {
// If the token is explicitly signed and the value is positive, we must
// add a `+` as this won't be included in the stringified value.
const sign = this._isSigned && this._value >= 0 ? "+" : "";
return `${sign}${this._value}${this._unit}`;
}
}
export namespace Dimension {
export interface JSON {
[key: string]: json.JSON;
type: "dimension";
value: number;
unit: string;
isInteger: boolean;
isSigned: boolean;
}
export function isDimension(value: unknown): value is Dimension {
return value instanceof Dimension;
}
}
export const { of: dimension, isDimension } = Dimension;
export function parseDimension(predicate: Predicate<Dimension> = () => true) {
return parseToken(and(isDimension, predicate));
}
export class Whitespace implements Equatable, Serializable<Whitespace.JSON> {
private static _instance = new Whitespace();
public static of(): Whitespace {
return Whitespace._instance;
}
private constructor() {}
public get type(): "whitespace" {
return "whitespace";
}
public equals(value: unknown): value is this {
return value instanceof Whitespace;
}
public toJSON(): Whitespace.JSON {
return {
type: "whitespace",
};
}
public toString(): string {
return " ";
}
}
export namespace Whitespace {
export interface JSON {
[key: string]: json.JSON;
type: "whitespace";
}
export function isWhitespace(value: unknown): value is Whitespace {
return value instanceof Whitespace;
}
}
export const { of: whitespace, isWhitespace } = Whitespace;
export const parseWhitespace = parseToken(isWhitespace);
export class Colon implements Equatable, Serializable<Colon.JSON> {
private static _instance = new Colon();
public static of(): Colon {
return Colon._instance;
}
private constructor() {}
public get type(): "colon" {
return "colon";
}
public equals(value: unknown): value is this {
return value instanceof Colon;
}
public toJSON(): Colon.JSON {
return {
type: "colon",
};
}
public toString(): string {
return ":";
}
}
export namespace Colon {
export interface JSON {
[key: string]: json.JSON;
type: "colon";
}
export function isColon(value: unknown): value is Colon {
return value instanceof Colon;
}
}
export const { of: colon, isColon } = Colon;
export const parseColon = parseToken(isColon);
export class Semicolon implements Equatable, Serializable<Semicolon.JSON> {
private static _instance = new Semicolon();
public static of(): Semicolon {
return Semicolon._instance;
}
private constructor() {}
public get type(): "semicolon" {
return "semicolon";
}
public equals(value: unknown): value is this {
return value instanceof Semicolon;
}
public toJSON(): Semicolon.JSON {
return {
type: "semicolon",
};
}
public toString(): string {
return ";";
}
}
export namespace Semicolon {
export interface JSON {
[key: string]: json.JSON;
type: "semicolon";
}
export function isSemicolon(value: unknown): value is Semicolon {
return value instanceof Semicolon;
}
}
export const { of: semicolon, isSemicolon } = Semicolon;
export const parseSemicolon = parseToken(isSemicolon);
export class Comma implements Equatable, Serializable<Comma.JSON> {
private static _instance = new Comma();
public static of(): Comma {
return Comma._instance;
}
private constructor() {}
public get type(): "comma" {
return "comma";
}
public equals(value: unknown): value is this {
return value instanceof Comma;
}
public toJSON(): Comma.JSON {
return {
type: "comma",
};
}
public toString(): string {
return ",";
}
}
export namespace Comma {
export interface JSON {
[key: string]: json.JSON;
type: "comma";
}
export function isComma(value: unknown): value is Comma {
return value instanceof Comma;
}
}
export const { of: comma, isComma } = Comma;
export const parseComma = parseToken(isComma);
export class OpenParenthesis
implements Equatable, Serializable<OpenParenthesis.JSON> {
private static _instance = new OpenParenthesis();
public static of(): OpenParenthesis {
return OpenParenthesis._instance;
}
private constructor() {}
public get type(): "open-parenthesis" {
return "open-parenthesis";
}
public get mirror(): CloseParenthesis {
return CloseParenthesis.of();
}
public equals(value: unknown): value is this {
return value instanceof OpenParenthesis;
}
public toJSON(): OpenParenthesis.JSON {
return {
type: "open-parenthesis",
};
}
public toString(): string {
return "(";
}
}
export namespace OpenParenthesis {
export interface JSON {
[key: string]: json.JSON;
type: "open-parenthesis";
}
export function isOpenParenthesis(
value: unknown
): value is OpenParenthesis {
return value instanceof OpenParenthesis;
}
}
export const { of: openParenthesis, isOpenParenthesis } = OpenParenthesis;
export const parseOpenParenthesis = parseToken(isOpenParenthesis);
export class CloseParenthesis
implements Equatable, Serializable<CloseParenthesis.JSON> {
private static _instance = new CloseParenthesis();
public static of(): CloseParenthesis {
return CloseParenthesis._instance;
}
private constructor() {}
public get type(): "close-parenthesis" {
return "close-parenthesis";
}
public get mirror(): OpenParenthesis {
return OpenParenthesis.of();
}
public equals(value: unknown): value is this {
return value instanceof CloseParenthesis;
}
public toJSON(): CloseParenthesis.JSON {
return {
type: "close-parenthesis",
};
}
public toString(): string {
return ")";
}
}
export namespace CloseParenthesis {
export interface JSON {
[key: string]: json.JSON;
type: "close-parenthesis";
}
export function isCloseParenthesis(
value: unknown
): value is CloseParenthesis {
return value instanceof CloseParenthesis;
}
}
export const { of: closeParenthesis, isCloseParenthesis } = CloseParenthesis;
export const parseCloseParenthesis = parseToken(isCloseParenthesis);
export class OpenSquareBracket
implements Equatable, Serializable<OpenSquareBracket.JSON> {
private static _instance = new OpenSquareBracket();
public static of(): OpenSquareBracket {
return OpenSquareBracket._instance;
}
private constructor() {}
public get type(): "open-square-bracket" {
return "open-square-bracket";
}
public get mirror(): CloseSquareBracket {
return CloseSquareBracket.of();
}
public equals(value: unknown): value is this {
return value instanceof OpenSquareBracket;
}
public toJSON(): OpenSquareBracket.JSON {
return {
type: "open-square-bracket",
};
}
public toString(): string {
return "[";
}
}
export namespace OpenSquareBracket {
export interface JSON {
[key: string]: json.JSON;
type: "open-square-bracket";
}
export function isOpenSquareBracket(
value: unknown
): value is OpenSquareBracket {
return value instanceof OpenSquareBracket;
}
}
export const {
of: openSquareBracket,
isOpenSquareBracket,
} = OpenSquareBracket;
export const parseOpenSquareBracket = parseToken(isOpenSquareBracket);
export class CloseSquareBracket
implements Equatable, Serializable<CloseSquareBracket.JSON> {
private static _instance = new CloseSquareBracket();
public static of(): CloseSquareBracket {
return CloseSquareBracket._instance;
}
private constructor() {}
public get type(): "close-square-bracket" {
return "close-square-bracket";
}
public get mirror(): OpenSquareBracket {
return OpenSquareBracket.of();
}
public equals(value: unknown): value is this {
return value instanceof CloseSquareBracket;
}
public toJSON(): CloseSquareBracket.JSON {
return {
type: "close-square-bracket",
};
}
public toString(): string {
return "]";
}
}
export namespace CloseSquareBracket {
export interface JSON {
[key: string]: json.JSON;
type: "close-square-bracket";
}
export function isCloseSquareBracket(
value: unknown
): value is CloseSquareBracket {
return value instanceof CloseSquareBracket;
}
}
export const {
of: closeSquareBracket,
isCloseSquareBracket,
} = CloseSquareBracket;
export const parseCloseSquareBracket = parseToken(isCloseSquareBracket);
export class OpenCurlyBracket
implements Equatable, Serializable<OpenCurlyBracket.JSON> {
private static _instance = new OpenCurlyBracket();
public static of(): OpenCurlyBracket {
return OpenCurlyBracket._instance;
}
private constructor() {}
public get type(): "open-curly-bracket" {
return "open-curly-bracket";
}
public get mirror(): CloseCurlyBracket {
return CloseCurlyBracket.of();
}
public equals(value: unknown): value is this {
return value instanceof OpenCurlyBracket;
}
public toJSON(): OpenCurlyBracket.JSON {
return {
type: "open-curly-bracket",
};
}
public toString(): string {
return "{";
}
}
export namespace OpenCurlyBracket {
export interface JSON {
[key: string]: json.JSON;
type: "open-curly-bracket";
}
export function isOpenCurlyBracket(
value: unknown
): value is OpenCurlyBracket {
return value instanceof OpenCurlyBracket;
}
}
export const { of: openCurlyBracket, isOpenCurlyBracket } = OpenCurlyBracket;
export const parseOpenCurlyBracket = parseToken(isOpenCurlyBracket);
export class CloseCurlyBracket
implements Equatable, Serializable<CloseCurlyBracket.JSON> {
private static _instance = new CloseCurlyBracket();
public static of(): CloseCurlyBracket {
return CloseCurlyBracket._instance;
}
private constructor() {}
public get type(): "close-curly-bracket" {
return "close-curly-bracket";
}
public get mirror(): OpenCurlyBracket {
return OpenCurlyBracket.of();
}
public equals(value: unknown): value is this {
return value instanceof CloseCurlyBracket;
}
public toJSON(): CloseCurlyBracket.JSON {
return {
type: "close-curly-bracket",
};
}
public toString(): string {
return "}";
}
}
export namespace CloseCurlyBracket {
export interface JSON {
[key: string]: json.JSON;
type: "close-curly-bracket";
}
export function isCloseCurlyBracket(
value: unknown
): value is CloseCurlyBracket {
return value instanceof CloseCurlyBracket;
}
}
export const {
of: closeCurlyBracket,
isCloseCurlyBracket,
} = CloseCurlyBracket;
export const parseCloseCurlyBracket = parseToken(isCloseCurlyBracket);
export class OpenComment
implements Equatable, Serializable<OpenComment.JSON> {
private static _instance = new OpenComment();
public static of(): OpenComment {
return OpenComment._instance;
}
private constructor() {}
public get type(): "open-comment" {
return "open-comment";
}
public equals(value: unknown): value is this {
return value instanceof OpenComment;
}
public toJSON(): OpenComment.JSON {
return {
type: "open-comment",
};
}
public toString(): string {
return "<!--";
}
}
export namespace OpenComment {
export interface JSON {
[key: string]: json.JSON;
type: "open-comment";
}
export function isOpenComment(value: unknown): value is OpenComment {
return value instanceof OpenComment;
}
}
export const { of: openComment, isOpenComment } = OpenComment;
export const parseOpenComment = parseToken(isOpenComment);
export class CloseComment
implements Equatable, Serializable<CloseComment.JSON> {
private static _instance = new CloseComment();
public static of(): CloseComment {
return CloseComment._instance;
}
private constructor() {}
public get type(): "close-comment" {
return "close-comment";
}
public equals(value: unknown): value is this {
return value instanceof CloseComment;
}
public toJSON(): CloseComment.JSON {
return {
type: "close-comment",
};
}
public toString(): string {
return "-->";
}
}
export namespace CloseComment {
export interface JSON {
[key: string]: json.JSON;
type: "close-comment";
}
export function isCloseComment(value: unknown): value is CloseComment {
return value instanceof CloseComment;
}
}
export const { of: closeComment, isCloseComment } = CloseComment;
export const parseCloseComment = parseToken(isCloseComment);
}
function parseToken<T extends Token>(
refinement: Refinement<Token, T>
): Parser<Slice<Token>, T, string> {
return (input) => {
const token = input.array[input.offset];
if (token !== undefined && refinement(token)) {
return Result.of([input.slice(1), token]);
}
return Err.of("Expected token");
};
} | the_stack |
import React, { useContext } from 'react';
import { render, act, userEvent, waitFor } from '../../util/test-utils';
import { uniqueId } from '../../util/id';
import { useMedia } from '../../hooks/useMedia';
import {
SidePanelProvider,
SidePanelContext,
SetSidePanel,
RemoveSidePanel,
UpdateSidePanel,
SidePanelContextProps,
} from './SidePanelContext';
const mockSendEvent = jest.fn();
jest.mock('@sumup/collector', () => ({
useClickTrigger: () => mockSendEvent,
}));
jest.mock('../../hooks/useMedia');
describe('SidePanelContext', () => {
beforeAll(() => {
jest.useFakeTimers();
});
beforeEach(() => {
(useMedia as jest.Mock).mockReturnValue(false);
});
afterEach(() => {
jest.clearAllMocks();
});
afterAll(() => {
jest.useRealTimers();
jest.resetModules();
});
describe('SidePanelProvider', () => {
const getPanel = () => ({
backButtonLabel: 'Back',
children: <p data-testid="children">Side panel content</p>,
closeButtonLabel: 'Close',
group: 'primary',
headline: 'Side panel title',
id: uniqueId(),
onClose: undefined,
tracking: undefined,
});
const renderComponent = (Trigger, props = {}) =>
render(
<SidePanelProvider {...props}>
<Trigger />
</SidePanelProvider>,
);
const renderOpenButton = (
hookFn: SetSidePanel,
props: Partial<SidePanelContextProps> = {},
label = 'Open panel',
) => (
<button onClick={() => hookFn({ ...getPanel(), ...props })}>
{label}
</button>
);
const renderCloseButton = (
hookFn: RemoveSidePanel,
group: SidePanelContextProps['group'] = 'primary',
) => (
<button
onClick={() => {
void hookFn(group);
}}
>
Close panel
</button>
);
const renderUpdateButton = (
hookFn: UpdateSidePanel,
props: Partial<SidePanelContextProps> = {},
group: SidePanelContextProps['group'] = 'primary',
) => (
<button onClick={() => hookFn({ group, ...props })}>Update panel</button>
);
describe('render', () => {
it('should render the non-resized container', () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return renderOpenButton(setSidePanel);
};
const { baseElement } = renderComponent(Trigger);
expect(baseElement).toMatchSnapshot();
});
it('should render the side panel and the resized container', () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return renderOpenButton(setSidePanel);
};
const { baseElement, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(baseElement).toMatchSnapshot();
});
it('should render the side panel on mobile resolutions', () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return renderOpenButton(setSidePanel);
};
(useMedia as jest.Mock).mockReturnValue(true);
const { baseElement, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(baseElement).toMatchSnapshot();
});
it('should render the side panel with offset for the top navigation', () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return renderOpenButton(setSidePanel);
};
const { baseElement, getByText } = renderComponent(Trigger, {
withTopNavigation: true,
});
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(baseElement).toMatchSnapshot();
});
});
describe('setSidePanel', () => {
it('should open a side panel', () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return renderOpenButton(setSidePanel);
};
const { getByRole, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(getByRole('dialog')).toBeVisible();
});
it('should replace a side panel opened in the same group', async () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return renderOpenButton(setSidePanel);
};
const { getAllByRole, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
act(() => {
userEvent.click(getByText('Open panel'));
});
await waitFor(() => {
expect(getAllByRole('dialog')).toHaveLength(1);
});
});
it('should open a second side panel', () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel)}
{renderOpenButton(
setSidePanel,
{ group: 'secondary' },
'Open second panel',
)}
</>
);
};
const { getAllByRole, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
userEvent.click(getByText('Open second panel'));
});
expect(getAllByRole('dialog')).toHaveLength(2);
});
it('should close all stacked side panels when opening a panel from a lower group', async () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel)}
{renderOpenButton(
setSidePanel,
{ group: 'secondary' },
'Open second panel',
)}
</>
);
};
const { getAllByRole, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
userEvent.click(getByText('Open second panel'));
});
expect(getAllByRole('dialog')).toHaveLength(2);
act(() => {
userEvent.click(getByText('Open panel'));
});
await waitFor(() => {
expect(getAllByRole('dialog')).toHaveLength(1);
});
});
it('should send an open tracking event', () => {
const Trigger = () => {
const { setSidePanel } = useContext(SidePanelContext);
return renderOpenButton(setSidePanel, {
tracking: { label: 'test-side-panel' },
});
};
const { getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(mockSendEvent).toHaveBeenCalledWith({
component: 'side-panel',
label: 'test-side-panel|open',
});
});
});
describe('removeSidePanel', () => {
it('should close the side panel', () => {
const Trigger = () => {
const { setSidePanel, removeSidePanel } =
useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel)}
{renderCloseButton(removeSidePanel)}
</>
);
};
const { getByRole, queryByRole, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(getByRole('dialog')).toBeVisible();
act(() => {
userEvent.click(getByText('Close panel'));
});
act(() => {
jest.runAllTimers();
});
expect(queryByRole('dialog')).toBeNull();
});
it('should close all side panels stacked above the one being closed', () => {
const Trigger = () => {
const { setSidePanel, removeSidePanel } =
useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel)}
{renderOpenButton(
setSidePanel,
{ group: 'secondary' },
'Open second panel',
)}
{renderCloseButton(removeSidePanel)}
</>
);
};
const { getAllByRole, queryByRole, getByText } =
renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
userEvent.click(getByText('Open second panel'));
});
expect(getAllByRole('dialog')).toHaveLength(2);
act(() => {
userEvent.click(getByText('Close panel'));
});
act(() => {
jest.runAllTimers();
});
expect(queryByRole('dialog')).toBeNull();
});
it('should not close side panels stacked below the one being closed', () => {
const Trigger = () => {
const { setSidePanel, removeSidePanel } =
useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel)}
{renderOpenButton(
setSidePanel,
{ group: 'secondary' },
'Open second panel',
)}
{renderCloseButton(removeSidePanel, 'secondary')}
</>
);
};
const { getAllByRole, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
userEvent.click(getByText('Open second panel'));
});
expect(getAllByRole('dialog')).toHaveLength(2);
act(() => {
userEvent.click(getByText('Close panel'));
});
act(() => {
jest.runAllTimers();
});
expect(getAllByRole('dialog')).toHaveLength(1);
});
it('should not close the side panel when there is no match', () => {
const Trigger = () => {
const { setSidePanel, removeSidePanel } =
useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel)}
{renderCloseButton(removeSidePanel, 'secondary')}
</>
);
};
const { getByRole, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(getByRole('dialog')).toBeVisible();
act(() => {
userEvent.click(getByText('Close panel'));
jest.runAllTimers();
});
expect(getByRole('dialog')).toBeVisible();
});
it('should call the onClose callback of the side panel', () => {
const onClose = jest.fn();
const Trigger = () => {
const { setSidePanel, removeSidePanel } =
useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel, { onClose })}
{renderCloseButton(removeSidePanel)}
</>
);
};
const { getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
act(() => {
userEvent.click(getByText('Close panel'));
jest.runAllTimers();
});
expect(onClose).toHaveBeenCalled();
});
it('should send a close tracking event', () => {
const Trigger = () => {
const { setSidePanel, removeSidePanel } =
useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel, {
tracking: { label: 'test-side-panel' },
})}
{renderCloseButton(removeSidePanel)}
</>
);
};
const { getByRole, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(getByRole('dialog')).toBeVisible();
act(() => {
userEvent.click(getByText('Close panel'));
jest.runAllTimers();
});
expect(mockSendEvent).toHaveBeenCalledWith({
component: 'side-panel',
label: 'test-side-panel|close',
});
});
});
describe('updateSidePanel', () => {
it('should update the side panel', () => {
const Trigger = () => {
const { setSidePanel, updateSidePanel } =
useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel)}
{renderUpdateButton(updateSidePanel, {
children: <p data-testid="children">Updated content</p>,
})}
</>
);
};
const { getByTestId, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(getByTestId('children')).toHaveTextContent('Side panel content');
act(() => {
userEvent.click(getByText('Update panel'));
jest.runAllTimers();
});
expect(getByTestId('children')).toHaveTextContent('Updated content');
});
it('should not update the side panel when there is no match', () => {
const Trigger = () => {
const { setSidePanel, updateSidePanel } =
useContext(SidePanelContext);
return (
<>
{renderOpenButton(setSidePanel)}
{renderUpdateButton(
updateSidePanel,
{
children: <p data-testid="children">Updated content</p>,
},
'secondary',
)}
</>
);
};
const { getByTestId, getByText } = renderComponent(Trigger);
act(() => {
userEvent.click(getByText('Open panel'));
});
expect(getByTestId('children')).toHaveTextContent('Side panel content');
act(() => {
userEvent.click(getByText('Update panel'));
jest.runAllTimers();
});
expect(getByTestId('children')).toHaveTextContent('Side panel content');
});
});
});
}); | the_stack |
import { Column } from "../fields/types"
import { IFilter, IFilterGroup, OrderDirection } from "@/features/tables/types";
import { TableState } from "react-table";
import {
allColumnsCheckedSelector,
allFiltersAppliedSelector,
appliedFiltersSelector,
columnsSelector,
encodedFiltersSelector,
filtersSelector,
firstRecordIdSelector,
lastRecordIdSelector,
limitOffsetSelector,
metaSelector,
orderBySelector,
orderDirectionSelector,
pageSelector,
perPageSelector,
recordsSelector,
removeAppliedFilter,
removeFilter,
resetRecordsSelection as resetRecordsSelectionInState,
resetState as resetReduxState,
selectedRecordsSelector,
setAppliedFilters as setAppliedFiltersInState,
setColumnWidths,
setColumns as setColumnsInState,
setFilters,
setMeta as setMetaInState,
setOrderBy as setOrderByInState,
setOrderDirection as setOrderDirectionInState,
setPage as setPageInState,
setPerPage as setPerPageInState,
setRecords as setRecordsInState,
setRecordsSelected as setRecordsSelectedInState,
toggleRecordSelection as toggleRecordSelectionInState,
updateFilter,
} from "@/features/records/state-slice";
import { getVisibleColumns } from "../fields";
import { isEqual, isNull, isString, merge } from "lodash";
import { localStorageColumnWidthsKey } from "@/features/tables";
import { useAppDispatch, useAppSelector } from "@/hooks";
import { useEffect } from "react";
import { useMemo } from "react";
import { useRouter } from "next/router";
import ApiResponse from "@/features/api/ApiResponse";
import URI from "urijs";
export const useResetState = () => {
const dispatch = useAppDispatch();
const resetState = () => {
dispatch(resetReduxState());
};
return resetState;
};
export const useFilters = () => {
const dispatch = useAppDispatch();
const { setPage } = usePagination();
const filters = useAppSelector(filtersSelector);
const appliedFilters = useAppSelector(appliedFiltersSelector);
const allFiltersApplied = useAppSelector(allFiltersAppliedSelector);
const encodedFilters = useAppSelector(encodedFiltersSelector);
const setTheFilters = (filters: Array<IFilter | IFilterGroup>) =>
dispatch(setFilters(filters));
const removeTheFilter = (idx: number) => dispatch(removeFilter(idx));
const removeTheAppliedFilter = (idx: number) =>
dispatch(removeAppliedFilter(idx));
const updateTheFilter = (idx: number, filter: IFilter | IFilterGroup) =>
dispatch(updateFilter({ idx, filter }));
const setAppliedFilters = (filters: Array<IFilter | IFilterGroup>) => {
dispatch(setAppliedFiltersInState(filters));
setPage(1);
};
const resetFilters = () => {
dispatch(setFilters([]));
dispatch(setAppliedFiltersInState([]));
};
const appliedNonBaseFilters = useMemo(
() => appliedFilters.filter(({ isBase }) => !isBase),
[appliedFilters]
);
return {
filters,
appliedFilters,
appliedNonBaseFilters,
setFilters: setTheFilters,
setAppliedFilters,
allFiltersApplied,
removeFilter: removeTheFilter,
removeAppliedFilter: removeTheAppliedFilter,
updateFilter: updateTheFilter,
resetFilters,
encodedFilters,
};
};
export const useSelectRecords = () => {
const dispatch = useAppDispatch();
const selectedRecords = useAppSelector(selectedRecordsSelector);
const allColumnsChecked = useAppSelector(allColumnsCheckedSelector);
const selectAllIsIndeterminate =
selectedRecords.length > 0 && !allColumnsChecked;
const toggleRecordSelection = (value: number) => {
dispatch(toggleRecordSelectionInState(value));
};
const setRecordsSelected = (values: number[]) => {
dispatch(setRecordsSelectedInState(values));
};
const resetRecordsSelection = () => {
dispatch(resetRecordsSelectionInState());
};
return {
selectedRecords,
allColumnsChecked,
toggleRecordSelection,
setRecordsSelected,
resetRecordsSelection,
selectAllIsIndeterminate,
};
};
export const useOrderRecords = (
initialOrderBy?: string,
initialOrderDirection?: OrderDirection
) => {
const router = useRouter();
const dispatch = useAppDispatch();
const orderBy = useAppSelector(orderBySelector);
const orderDirection = useAppSelector(orderDirectionSelector);
const setOrderBy = (value: string) => {
dispatch(setOrderByInState(value));
};
const setOrderDirection = (values: OrderDirection) => {
dispatch(setOrderDirectionInState(values));
};
const resetOrder = () => {
setOrderBy("");
setOrderDirection("");
};
if (isString(initialOrderBy)) {
setOrderBy(initialOrderBy);
}
if (isString(initialOrderDirection)) {
setOrderDirection(initialOrderDirection);
}
const handleOrder = async (columnName: string) => {
let newOrderDirection: OrderDirection = "";
let newOrderBy = "";
if (orderBy !== columnName) {
newOrderDirection = "asc";
newOrderBy = columnName;
} else {
switch (orderDirection) {
default:
case "":
newOrderDirection = "asc";
newOrderBy = columnName;
break;
case "asc":
newOrderDirection = "desc";
newOrderBy = columnName;
break;
case "desc":
newOrderDirection = "";
newOrderBy = "";
break;
}
}
setOrderDirection(newOrderDirection);
setOrderBy(newOrderBy);
const query = { ...router.query };
if (newOrderBy) {
query.orderBy = newOrderBy;
} else {
delete query.orderBy;
}
if (newOrderDirection) {
query.orderDirection = newOrderDirection;
} else {
delete query.orderDirection;
}
await router.push({
pathname: router.pathname,
query,
});
};
return {
orderBy,
orderDirection,
setOrderBy,
setOrderDirection,
handleOrder,
resetOrder,
};
};
export const useColumns = ({
dataSourceResponse,
recordsResponse,
columnsResponse,
options,
}: {
dataSourceResponse?: ApiResponse;
recordsResponse?: ApiResponse;
columnsResponse?: ApiResponse;
options?: {
forEdit: boolean; // this refers to view edit page
};
}) => {
const dispatch = useAppDispatch();
const columns = useAppSelector(columnsSelector);
const setColumns = (columns: Column[]) => {
dispatch(setColumnsInState(columns));
};
// Figure out where we should fetch the columns from.
// If the data source can fetch the columns ahead of time use those, if not, fetch from the records response.
// We should probably use just one source in the future.
const rawColumns: Column[] = useMemo(() => {
if (
recordsResponse?.ok &&
dataSourceResponse?.ok &&
dataSourceResponse?.meta?.dataSourceInfo?.supports?.columnsRequest ===
false
) {
return recordsResponse?.meta?.columns;
} else if (columnsResponse?.ok) {
return columnsResponse?.data;
} else {
return [];
}
}, [dataSourceResponse, recordsResponse, columnsResponse]);
useEffect(() => {
if (options?.forEdit) {
setColumns(rawColumns);
} else {
setColumns(getVisibleColumns(rawColumns, "index"));
}
}, [rawColumns]);
return {
columns,
setColumns,
};
};
export const useRecords = (
initialRecords?: [],
meta?: Record<string, unknown>
) => {
const dispatch = useAppDispatch();
const records = useAppSelector(recordsSelector);
const setRecords = (records: []) => {
dispatch(setRecordsInState(records));
};
const setMeta = (meta: Record<string, unknown>) => {
dispatch(setMetaInState(meta as any));
};
useEffect(() => {
if (initialRecords) {
setRecords(initialRecords);
}
}, [initialRecords]);
useEffect(() => {
if (meta) {
setMeta(meta);
}
}, [meta]);
return {
records,
meta,
setRecords,
};
};
/**
* This hook handles the initialization and state updates for resizing columns.
*/
export const useResizableColumns = ({
dataSourceId,
tableName,
}: {
dataSourceId: string;
tableName: string;
}) => {
const dispatch = useAppDispatch();
const localStorageKey = localStorageColumnWidthsKey({
dataSourceId: dataSourceId as string,
tableName: tableName as string,
});
const updateColumnWidths = ({
state,
columnWidths,
}: {
state: TableState;
columnWidths: any;
}) => {
// Check if we have the right data to compute the new widths
if (
state?.columnResizing?.columnWidths &&
Object.keys(state.columnResizing.columnWidths).length > 0 &&
!isEqual(state.columnResizing.columnWidths, columnWidths) &&
isNull(state.columnResizing.isResizingColumn)
) {
// Create a final object that should be dispatched and stored in localStorage
const newWidths = merge(
{},
columnWidths,
state.columnResizing.columnWidths
);
// Dispatch and store it if it's different than what's there right now.
if (!isEqual(newWidths, columnWidths)) {
dispatch(setColumnWidths(newWidths));
window.localStorage.setItem(localStorageKey, JSON.stringify(newWidths));
}
}
};
// Parse the stored value and add it to redux
useEffect(() => {
let widths = {};
try {
const payload = window.localStorage.getItem(localStorageKey) as string;
widths = JSON.parse(payload);
} catch (error) {}
dispatch(setColumnWidths(widths));
}, []);
return updateColumnWidths;
};
export const useCursorPagination = () => {
const router = useRouter();
const meta = useAppSelector(metaSelector);
const firstRecordId = useAppSelector(firstRecordIdSelector);
const lastRecordId = useAppSelector(lastRecordIdSelector);
const hasMore = useMemo(() => meta?.hasMore === true, [meta?.hasMore]);
const [canNextPage, canPreviousPage] = useMemo(() => {
let canNext = hasMore;
if (router.query.endingBefore) {
canNext = true;
}
let canPrevious = false;
if (router.query.endingBefore) {
canPrevious = hasMore;
} else if (router.query.startingAfter) {
canPrevious = true;
}
return [canNext, canPrevious];
}, [router.query.startingAfter, router.query.endingBefore, hasMore]);
const nextPageLink = useMemo(() => {
const uri = URI(router.asPath);
uri.setQuery({
startingAfter: lastRecordId,
});
uri.removeQuery("endingBefore");
return uri.toString();
}, [router.query, lastRecordId]);
const previousPageLink = useMemo(() => {
const uri = URI(router.asPath);
uri.setQuery({
endingBefore: firstRecordId,
});
uri.removeQuery("startingAfter");
return uri.toString();
}, [router.query, firstRecordId]);
return {
nextPageLink,
previousPageLink,
canNextPage,
canPreviousPage,
hasMore,
firstRecordId,
lastRecordId,
};
};
export const usePagination = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const page = useAppSelector(pageSelector);
const perPage = useAppSelector(perPageSelector);
const [limit, offset] = useAppSelector(limitOffsetSelector);
const meta = useAppSelector(metaSelector);
const maxPages = useMemo(() => {
if (meta?.count) {
return Math.ceil((meta?.count as number) / perPage);
}
return 1;
}, [meta?.count]);
const canPreviousPage = useMemo(() => page > 1, [page]);
const canNextPage = useMemo(() => page < maxPages, [page, maxPages]);
const setPage = (page: number) => {
router.push({
pathname: router.pathname,
query: {
...router.query,
page,
},
});
dispatch(setPageInState(page));
};
const setPerPage = (page: number) => dispatch(setPerPageInState(page));
const nextPage = () => setPage(page + 1);
const previousPage = () => {
let prevPageNumber = page - 1;
if (prevPageNumber <= 0) prevPageNumber = 1;
setPage(prevPageNumber);
};
return {
page,
perPage,
limit,
offset,
nextPage,
previousPage,
setPage,
setPerPage,
maxPages,
canPreviousPage,
canNextPage,
recordsCount: meta.count,
};
}; | the_stack |
import {
arrayForEach, domData, removeNode
} from '@tko/utils'
import {
applyBindings
} from '@tko/bind'
import {
observable, observableArray, isObservable
} from '@tko/observable'
import { MultiProvider } from '@tko/provider.multi'
import { VirtualProvider } from '@tko/provider.virtual'
import { DataBindProvider } from '@tko/provider.databind'
import {
options
} from '@tko/utils'
import {
bindings as templateBindings, renderTemplate,
setTemplateEngine, nativeTemplateEngine
} from '../dist'
import {
bindings as coreBindings
} from '@tko/binding.core'
import '@tko/utils/helpers/jasmine-13-helper'
import {
dummyTemplateEngine
} from '../helpers/dummyTemplateEngine'
describe('Templating', function () {
var bindingHandlers
beforeEach(jasmine.prepareTestNode)
beforeEach(function () {
options.bindingGlobals = {}
// Set up the default binding handlers.
var provider = new MultiProvider({
providers: [new DataBindProvider(), new VirtualProvider()],
globals: options.bindingGlobals
})
options.bindingProviderInstance = provider
provider.bindingHandlers.set(coreBindings)
provider.bindingHandlers.set(templateBindings)
bindingHandlers = provider.bindingHandlers
})
afterEach(function () {
setTemplateEngine(new nativeTemplateEngine())
})
it('Template engines can return an array of DOM nodes', function () {
setTemplateEngine(new dummyTemplateEngine({ x: [document.createElement('div'), document.createElement('span')] }))
renderTemplate('x', null)
})
it('Should not be able to render a template until a template engine is provided', function () {
expect(function () {
setTemplateEngine(undefined)
renderTemplate('someTemplate', {})
}).toThrow()
})
it('Should be able to render a template into a given DOM element', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'ABC' }))
renderTemplate('someTemplate', null, null, testNode)
expect(testNode.childNodes.length).toEqual(1)
expect(testNode.innerHTML).toEqual('ABC')
})
it('Should be able to render an empty template', function () {
setTemplateEngine(new dummyTemplateEngine({ emptyTemplate: '' }))
renderTemplate('emptyTemplate', null, null, testNode)
expect(testNode.childNodes.length).toEqual(0)
})
it('Should be able to access newly rendered/inserted elements in \'afterRender\' callback', function () {
var passedElement, passedDataItem
var myCallback = function (elementsArray, dataItem) {
expect(elementsArray.length).toEqual(1)
passedElement = elementsArray[0]
passedDataItem = dataItem
}
var myModel = {}
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'ABC' }))
renderTemplate('someTemplate', myModel, { afterRender: myCallback }, testNode)
expect(passedElement.nodeValue).toEqual('ABC')
expect(passedDataItem).toEqual(myModel)
})
it('Should automatically rerender into DOM element when dependencies change', function () {
var dependency = observable('A')
setTemplateEngine(new dummyTemplateEngine({ someTemplate: function () {
return 'Value = ' + dependency()
}
}))
renderTemplate('someTemplate', null, null, testNode)
expect(testNode.childNodes.length).toEqual(1)
expect(testNode.innerHTML).toEqual('Value = A')
dependency('B')
expect(testNode.childNodes.length).toEqual(1)
expect(testNode.innerHTML).toEqual('Value = B')
})
it('Should not rerender DOM element if observable accessed in \'afterRender\' callback is changed', function () {
var myObservable = observable('A'), count = 0
var myCallback = function (/* elementsArray, dataItem */) {
myObservable() // access observable in callback
}
var myTemplate = function () {
return 'Value = ' + (++count)
}
setTemplateEngine(new dummyTemplateEngine({ someTemplate: myTemplate }))
renderTemplate('someTemplate', {}, { afterRender: myCallback }, testNode)
expect(testNode.childNodes.length).toEqual(1)
expect(testNode.innerHTML).toEqual('Value = 1')
myObservable('B')
expect(testNode.childNodes.length).toEqual(1)
expect(testNode.innerHTML).toEqual('Value = 1')
})
it('If the supplied data item is observable, evaluates it and has subscription on it', function () {
var myObservable = observable('A')
setTemplateEngine(new dummyTemplateEngine({ someTemplate: function (data) {
return 'Value = ' + data
}
}))
renderTemplate('someTemplate', myObservable, null, testNode)
expect(testNode.innerHTML).toEqual('Value = A')
myObservable('B')
expect(testNode.innerHTML).toEqual('Value = B')
})
it('Should stop updating DOM nodes when the dependency next changes if the DOM node has been removed from the document', function () {
var dependency = observable('A')
var template = { someTemplate: function () { return 'Value = ' + dependency() } }
setTemplateEngine(new dummyTemplateEngine(template))
renderTemplate('someTemplate', null, null, testNode)
expect(testNode.childNodes.length).toEqual(1)
expect(testNode.innerHTML).toEqual('Value = A')
testNode.parentNode.removeChild(testNode)
dependency('B')
expect(testNode.childNodes.length).toEqual(1)
expect(testNode.innerHTML).toEqual('Value = A')
})
it('Should be able to pick template via an observable', function () {
setTemplateEngine(new dummyTemplateEngine({
firstTemplate: 'First template output',
secondTemplate: 'Second template output'
}))
var chosenTemplate = observable('firstTemplate')
renderTemplate(chosenTemplate, null, null, testNode)
expect(testNode.innerHTML).toEqual('First template output')
chosenTemplate('secondTemplate')
expect(testNode.innerHTML).toEqual('Second template output')
})
it('Should be able to render a template using data-bind syntax', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'template output' }))
testNode.innerHTML = "<div data-bind='template:\"someTemplate\"'></div>"
applyBindings(null, testNode)
expect(testNode.childNodes[0].innerHTML).toEqual('template output')
})
it('Should remove existing content when rendering a template using data-bind syntax', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'template output' }))
testNode.innerHTML = "<div data-bind='template:\"someTemplate\"'><span>existing content</span></div>"
applyBindings(null, testNode)
expect(testNode.childNodes[0].innerHTML).toEqual('template output')
})
it('Should be able to tell data-bind syntax which object to pass as data for the template (otherwise, uses viewModel)', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'result = [js: nomangle$data.childProp]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>"
applyBindings({ someProp: { childProp: 123} }, testNode)
expect(testNode.childNodes[0].innerHTML).toEqual('result = 123')
})
it('Should re-render a named template when its data item notifies about mutation', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'result = [js: nomangle$data.childProp]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>"
var myData = observable({ childProp: 123 })
applyBindings({ someProp: myData }, testNode)
expect(testNode.childNodes[0].innerHTML).toEqual('result = 123')
// Now mutate and notify
myData().childProp = 456
myData.valueHasMutated()
expect(testNode.childNodes[0].innerHTML).toEqual('result = 456')
})
it('Should call a generic childrenComplete callback function', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'result = [js: nomangle$data.childProp]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someItem }, childrenComplete: callback'></div>"
var someItem = observable({ childProp: 'child' }),
callbacks = 0
applyBindings({ someItem: someItem, callback: function () { callbacks++ } }, testNode)
expect(callbacks).toEqual(1)
expect(testNode.childNodes[0]).toContainText('result = child')
someItem({ childProp: 'new child' })
expect(callbacks).toEqual(2)
expect(testNode.childNodes[0]).toContainText('result = new child')
})
it('Should stop tracking inner observables immediately when the container node is removed from the document', function () {
var innerObservable = observable('some value')
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'result = [js: nomangle$data.childProp()]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>"
applyBindings({ someProp: { childProp: innerObservable} }, testNode)
expect(innerObservable.getSubscriptionsCount()).toEqual(1)
removeNode(testNode.childNodes[0])
expect(innerObservable.getSubscriptionsCount()).toEqual(0)
})
it('Should be able to pick template via an observable model property', function () {
setTemplateEngine(new dummyTemplateEngine({
firstTemplate: 'First template output',
secondTemplate: 'Second template output'
}))
var chosenTemplate = observable('firstTemplate')
testNode.innerHTML = "<div data-bind='template: chosenTemplate'></div>"
applyBindings({ chosenTemplate: chosenTemplate }, testNode)
expect(testNode.childNodes[0].innerHTML).toEqual('First template output')
chosenTemplate('secondTemplate')
expect(testNode.childNodes[0].innerHTML).toEqual('Second template output')
})
it('Should be able to pick template via an observable model property when specified as "name"', function () {
setTemplateEngine(new dummyTemplateEngine({
firstTemplate: 'First template output',
secondTemplate: 'Second template output'
}))
var chosenTemplate = observable('firstTemplate')
testNode.innerHTML = "<div data-bind='template: { name: chosenTemplate }'></div>"
applyBindings({ chosenTemplate: chosenTemplate }, testNode)
expect(testNode.childNodes[0].innerHTML).toEqual('First template output')
chosenTemplate('secondTemplate')
expect(testNode.childNodes[0].innerHTML).toEqual('Second template output')
})
it('Should be able to pick template via an observable model property when specified as "name" in conjunction with "foreach"', function () {
setTemplateEngine(new dummyTemplateEngine({
firstTemplate: 'First',
secondTemplate: 'Second'
}))
var chosenTemplate = observable('firstTemplate')
testNode.innerHTML = "<div data-bind='template: { name: chosenTemplate, foreach: [1,2,3] }'></div>"
applyBindings({ chosenTemplate: chosenTemplate }, testNode)
expect(testNode.childNodes[0].innerHTML).toEqual('FirstFirstFirst')
chosenTemplate('secondTemplate')
expect(testNode.childNodes[0].innerHTML).toEqual('SecondSecondSecond')
})
it('Should be able to pick template as a function of the data item using data-bind syntax, with the binding context available as a second parameter', function () {
var templatePicker = function (dataItem, bindingContext) {
// Having the entire binding context available means you can read sibling or parent level properties
expect(bindingContext.$parent.anotherProperty).toEqual(456)
return dataItem.myTemplate
}
setTemplateEngine(new dummyTemplateEngine({ someTemplate: 'result = [js: nomangle$data.childProp]' }))
testNode.innerHTML = "<div data-bind='template: { name: templateSelectorFunction, data: someProp }'></div>"
applyBindings({ someProp: { childProp: 123, myTemplate: 'someTemplate' }, templateSelectorFunction: templatePicker, anotherProperty: 456 }, testNode)
expect(testNode.childNodes[0].innerHTML).toEqual('result = 123')
})
it('Should be able to chain templates, rendering one from inside another', function () {
setTemplateEngine(new dummyTemplateEngine({
outerTemplate: 'outer template output, [renderTemplate:innerTemplate]', // [renderTemplate:...] is special syntax supported by dummy template engine
innerTemplate: "inner template output <span data-bind='text: 123'></span>"
}))
testNode.innerHTML = "<div data-bind='template:\"outerTemplate\"'></div>"
applyBindings(null, testNode)
expect(testNode.childNodes[0]).toContainHtml('outer template output, inner template output <span data-bind="text: 123">123</span>')
})
it('Should rerender chained templates when their dependencies change, without rerendering parent templates', function () {
var myObservable = observable('ABC')
var timesRenderedOuter = 0, timesRenderedInner = 0
setTemplateEngine(new dummyTemplateEngine({
outerTemplate: function () { timesRenderedOuter++; return 'outer template output, [renderTemplate:innerTemplate]' }, // [renderTemplate:...] is special syntax supported by dummy template engine
innerTemplate: function () { timesRenderedInner++; return myObservable() }
}))
testNode.innerHTML = "<div data-bind='template:\"outerTemplate\"'></div>"
applyBindings(null, testNode)
expect(testNode.childNodes[0]).toContainHtml('outer template output, abc')
expect(timesRenderedOuter).toEqual(1)
expect(timesRenderedInner).toEqual(1)
myObservable('DEF')
expect(testNode.childNodes[0]).toContainHtml('outer template output, def')
expect(timesRenderedOuter).toEqual(1)
expect(timesRenderedInner).toEqual(2)
})
it('Should stop tracking inner observables referenced by a chained template as soon as the chained template output node is removed from the document', function () {
var innerObservable = observable('some value')
setTemplateEngine(new dummyTemplateEngine({
outerTemplate: "outer template output, <span id='innerTemplateOutput'>[renderTemplate:innerTemplate]</span>",
innerTemplate: 'result = [js: nomangle$data.childProp()]'
}))
testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\", data: someProp }'></div>"
applyBindings({ someProp: { childProp: innerObservable} }, testNode)
expect(innerObservable.getSubscriptionsCount()).toEqual(1)
removeNode(document.getElementById('innerTemplateOutput'))
expect(innerObservable.getSubscriptionsCount()).toEqual(0)
})
it('Should handle data-bind attributes from inside templates, regardless of element and attribute casing', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<INPUT Data-Bind='value:\"Hi\"' />" }))
renderTemplate('someTemplate', null, null, testNode)
expect(testNode.childNodes[0].value).toEqual('Hi')
})
it('Should handle data-bind attributes that include newlines from inside templates', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input data-bind='value:\n\"Hi\"' />" }))
renderTemplate('someTemplate', null, null, testNode)
expect(testNode.childNodes[0].value).toEqual('Hi')
})
xit('Data binding syntax should be able to reference variables put into scope by the template engine', function () {
// Disabling this because the only place where
// templateRenderingVariablesInScope appears is with the
// dummy template engine. The Provider/Parser is never made
// aware of it.
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input data-bind='value:message' />" }))
renderTemplate('someTemplate', null, { templateRenderingVariablesInScope: { message: 'hello'} }, testNode)
expect(testNode.childNodes[0].value).toEqual('hello')
})
it('Should handle data-bind attributes with spaces around equals sign from inside templates and reference variables', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input data-bind = 'value:message' />" }))
renderTemplate('someTemplate', { message: 'hello' }, {}, testNode)
expect(testNode.childNodes[0].value).toEqual('hello')
})
it('Data binding syntax should be able to use $element in binding value', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<div data-bind='text: $element.tagName'></div>" }))
renderTemplate('someTemplate', null, null, testNode)
expect(testNode.childNodes[0]).toContainText('DIV')
})
it('Data binding syntax should be able to use $context in binding value to refer to the context object', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<div data-bind='text: $context.$data === $data'></div>" }))
renderTemplate('someTemplate', {}, null, testNode)
expect(testNode.childNodes[0]).toContainText('true')
})
it('Data binding syntax should be able to use $rawData in binding value to refer to a top level template\'s view model observable', function () {
var data = observable('value')
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<div data-bind='text: isObservable($rawData)'></div>" }))
options.bindingGlobals.isObservable = isObservable
renderTemplate('someTemplate', data, null, testNode)
expect(testNode.childNodes[0]).toContainText('true')
expect(data.getSubscriptionsCount('change')).toEqual(1) // only subscription is from the templating code
})
it('Data binding syntax should be able to use $rawData in binding value to refer to a data-bound template\'s view model observable', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<div data-bind='text: isObservable($rawData)'></div>" }))
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>"
// Expose to access isObservable
options.bindingGlobals.isObservable = isObservable
var viewModel = { someProp: observable('value') }
applyBindings(viewModel, testNode)
expect(testNode.childNodes[0].childNodes[0]).toContainText('true')
expect(viewModel.someProp.getSubscriptionsCount('change')).toEqual(1) // only subscription is from the templating code
})
it('Data binding syntax should be able to use $rawData in binding value to refer to a top level template\'s view model observable', function () {
options.bindingGlobals.isObservable = isObservable
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<div data-bind='text: isObservable($rawData)'></div>" }))
renderTemplate('someTemplate', observable('value'), null, testNode)
expect(testNode.childNodes[0]).toContainText('true')
})
it('Data binding syntax should be able to use $rawData in binding value to refer to a data-bound template\'s view model observable', function () {
options.bindingGlobals.isObservable = isObservable
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<div data-bind='text: isObservable($rawData)'></div>" }))
testNode.innerHTML = "<div data-bind='template: { name: \"someTemplate\", data: someProp }'></div>"
const viewModel = { someProp: observable('value') }
applyBindings(viewModel, testNode)
expect(testNode.childNodes[0].childNodes[0]).toContainText('true')
})
it('Data binding syntax should defer evaluation of variables until the end of template rendering (so bindings can take independent subscriptions to them)', function () {
setTemplateEngine(new dummyTemplateEngine({
someTemplate: "<input data-bind='value:message' />[js: rt_options.templateRenderingVariablesInScope.message = 'goodbye'; undefined; ]"
}))
var viewModel = { message: 'hello' }
renderTemplate('someTemplate', viewModel, { templateRenderingVariablesInScope: viewModel }, testNode)
expect(testNode.childNodes[0].value).toEqual('goodbye')
})
it('Data binding syntax should use the template\'s \'data\' object as the viewModel value (so \'this\' is set correctly when calling click handlers etc.)', function () {
setTemplateEngine(new dummyTemplateEngine({
someTemplate: "<button data-bind='click: someFunctionOnModel'>click me</button>"
}))
var viewModel = {
didCallMyFunction: false,
someFunctionOnModel: function () { this.didCallMyFunction = true }
}
renderTemplate('someTemplate', viewModel, null, testNode)
var buttonNode = testNode.childNodes[0]
expect(buttonNode.tagName).toEqual('BUTTON') // Be sure we're clicking the right thing
buttonNode.click()
expect(viewModel.didCallMyFunction).toEqual(true)
})
it('Data binding syntax should permit nested templates, and only bind inner templates once when using getBindingAccessors', function () {
this.restoreAfter(options, 'bindingProviderInstance')
// Will verify that bindings are applied only once for both inline (rewritten) bindings,
// and external (non-rewritten) ones
var originalBindingProvider = options.bindingProviderInstance
options.bindingProviderInstance = {
FOR_NODE_TYPES: [document.ELEMENT_NODE],
bindingHandlers: originalBindingProvider.bindingHandlers,
nodeHasBindings: function (node, bindingContext) {
return (node.tagName == 'EM') || originalBindingProvider.nodeHasBindings(node, bindingContext)
},
getBindingAccessors: function (node, bindingContext) {
if (node.tagName == 'EM') {
return {
text: function () {
return ++model.numExternalBindings
}
}
}
return originalBindingProvider.getBindingAccessors(node, bindingContext)
}
}
setTemplateEngine(new dummyTemplateEngine({
outerTemplate: "Outer <div data-bind='template: { name: \"innerTemplate\", bypassDomNodeWrap: true }'></div>",
innerTemplate: "Inner via inline binding: <span data-bind='text: ++numRewrittenBindings'></span>" +
'Inner via external binding: <em></em>'
}))
var model = { numRewrittenBindings: 0, numExternalBindings: 0 }
testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\", bypassDomNodeWrap: true }'></div>"
applyBindings(model, testNode)
// FIXME: The following has the correct result in the
// binding provider tests (i.e. prefix operator). Unclear why
// it fails here -- but the result is correct in the string produced
// below.
// expect(model.numRewrittenBindings).toEqual(1);
expect(model.numExternalBindings).toEqual(1)
expect(testNode.childNodes[0]).toContainHtml('outer <div data-bind="template: { name: "innertemplate", bypassdomnodewrap: true }">inner via inline binding: <span data-bind="text: ++numrewrittenbindings">1</span>inner via external binding: <em>1</em></div>')
})
xit('Data binding syntax should permit nested templates, and only bind inner templates once when using getBindings', function () {
// SKIP because we have deprecated getBindings in favour of
// getBindingAccessors.
this.restoreAfter(options, 'bindingProviderInstance')
// Will verify that bindings are applied only once for both inline (rewritten) bindings,
// and external (non-rewritten) ones. Because getBindings actually gets called twice, we need
// to expect two calls (but still it's a single binding).
var originalBindingProvider = options.bindingProviderInstance
options.bindingProviderInstance = {
bindingHandlers: originalBindingProvider.bindingHandlers,
nodeHasBindings: function (node, bindingContext) {
return (node.tagName == 'EM') || originalBindingProvider.nodeHasBindings(node, bindingContext)
},
getBindings: function (node, bindingContext) {
if (node.tagName == 'EM') { return { text: ++model.numExternalBindings } }
return originalBindingProvider.getBindings(node, bindingContext)
}
}
setTemplateEngine(new dummyTemplateEngine({
outerTemplate: "Outer <div data-bind='template: { name: \"innerTemplate\", bypassDomNodeWrap: true }'></div>",
innerTemplate: "Inner via inline binding: <span data-bind='text: ++numRewrittenBindings'></span>" +
'Inner via external binding: <em></em>'
}))
var model = { numRewrittenBindings: 0, numExternalBindings: 0 }
testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\", bypassDomNodeWrap: true }'></div>"
applyBindings(model, testNode)
expect(model.numRewrittenBindings).toEqual(1)
expect(model.numExternalBindings).toEqual(2)
expect(testNode.childNodes[0]).toContainHtml('outer <div>inner via inline binding: <span>1</span>inner via external binding: <em>2</em></div>')
})
it('Should accept a "nodes" option that gives the template nodes', function () {
// This is an alternative to specifying a named template, and is useful in conjunction with components
setTemplateEngine(new dummyTemplateEngine({
innerTemplate: 'the name is [js: nomangle$data.name()]' // See that custom template engines are applied to the injected nodes
}))
testNode.innerHTML = "<div data-bind='template: { nodes: testNodes, data: testData, bypassDomNodeWrap: true }'></div>"
var model = {
testNodes: [
document.createTextNode('begin'),
document.createElement('span'),
document.createTextNode('end')
],
testData: { name: observable('alpha') }
}
model.testNodes[1].setAttribute('data-bind', "template: 'innerTemplate'") // See that bindings are applied to the injected nodes
applyBindings(model, testNode)
expect(testNode.childNodes[0]).toContainHtml('begin<span data-bind="template: \'innertemplate\'">the name is alpha</span>end')
// The injected bindings update to match model changes as usual
model.testData.name('beta')
expect(testNode.childNodes[0]).toContainHtml('begin<span data-bind="template: \'innertemplate\'">the name is beta</span>end')
})
it('Should accept a "nodes" option that gives the template nodes, and able to use the same nodes for multiple bindings', function () {
testNode.innerHTML = "<div data-bind='template: { nodes: testNodes, data: testData1, bypassDomNodeWrap: true }'></div><div data-bind='template: { nodes: testNodes, data: testData2, bypassDomNodeWrap: true }'></div>"
var model = {
testNodes: [
document.createTextNode('begin'),
document.createElement('span'),
document.createTextNode('end')
],
testData1: observable({ name: observable('alpha1') }),
testData2: observable({ name: observable('alpha2') })
}
model.testNodes[1].setAttribute('data-bind', 'text: name') // See that bindings are applied to the injected nodes
applyBindings(model, testNode)
expect(testNode.childNodes[0]).toContainText('beginalpha1end')
expect(testNode.childNodes[1]).toContainText('beginalpha2end')
// The injected bindings update to match model changes as usual
model.testData1().name('beta1')
model.testData2().name('beta2')
expect(testNode.childNodes[0]).toContainText('beginbeta1end')
expect(testNode.childNodes[1]).toContainText('beginbeta2end')
// The template binding re-renders successfully if model changes
model.testData1({ name: observable('gamma1') })
model.testData2({ name: observable('gamma2') })
expect(testNode.childNodes[0]).toContainText('begingamma1end')
expect(testNode.childNodes[1]).toContainText('begingamma2end')
})
it('Should accept a "nodes" option that gives the template nodes, and it can be used in conjunction with "foreach"', function () {
testNode.innerHTML = "<div data-bind='template: { nodes: testNodes, foreach: testData, bypassDomNodeWrap: true }'></div>"
// This time we'll check that the nodes array doesn't have to be a real array - it can be the .childNodes
// property of a DOM element, which is subtly different.
var templateContainer = document.createElement('div')
templateContainer.innerHTML = "[<span data-bind='text: name'></span>]"
var model = {
testNodes: templateContainer.childNodes,
testData: observableArray([{ name: observable('alpha') }, { name: 'beta' }, { name: 'gamma' }])
}
model.testNodes[1].setAttribute('data-bind', 'text: name')
applyBindings(model, testNode)
expect(testNode.childNodes[0]).toContainText('[alpha][beta][gamma]')
// The injected bindings update to match model changes as usual
model.testData.splice(1, 1)
expect(testNode.childNodes[0]).toContainText('[alpha][gamma]')
// Changing the nodes array does *not* affect subsequent output from the template.
// This behavior may be subject to change. I'm adding this assertion just to record what
// the current behavior is, even if we might want to alter it in the future. We don't need
// to document or make any guarantees about what happens if you do this - it's just not
// a supported thing to do.
templateContainer.innerHTML = '[Modified, but will not appear in template output because the nodes were already cloned]'
model.testData.splice(1, 0, { name: 'delta' })
expect(testNode.childNodes[0]).toContainText('[alpha][delta][gamma]')
})
it('Should interpret "nodes: anyfalsyValue" as being equivalent to supplying an empty node array', function () {
// This behavior helps to avoid inconsistency if you're programmatically supplying a node array
// but sometimes you might not have any nodes - you don't want the template binding to dynamically
// switch over to "inline template" mode just because your 'nodes' value is null, for example.
testNode.innerHTML = "<div data-bind='template: { nodes: null, bypassDomNodeWrap: true }'>Should not use this inline template</div>"
applyBindings(null, testNode)
expect(testNode.childNodes[0]).toContainHtml('')
})
it('Should not allow "nodes: someObservableArray"', function () {
// See comment in implementation for reasoning
testNode.innerHTML = "<div data-bind='template: { nodes: myNodes, bypassDomNodeWrap: true }'>Should not use this inline template</div>"
expect(function () {
applyBindings({ myNodes: observableArray() }, testNode)
}).toThrowContaining('The "nodes" option must be a plain, non-observable array')
})
/**
* Update the templating engine to handle JSX nodes.
*/
xit('Should accept `jsx:...`', function () {
testNode.innerHTML = "<div data-bind='template: { jsx: testJsx }'></div>"
const obs = observable('alpha')
var model = {
testJsx: {
elementName: 'begin',
attributes: {},
children: [
{elementName: 'span', children: [obs], attributes: {}},
{elementName: 'end', children: [], attributes: {}}
]
}
}
applyBindings(model, testNode)
expect(testNode.childNodes[0]).toContainHtml('<begin><span>alpha</span><end></end></begin>')
obs('beta')
expect(testNode.childNodes[0]).toContainHtml('<begin><span>beta</span><end></end></begin>')
})
describe('Data binding \'foreach\' option', function () {
it('Should remove existing content', function () {
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: '<span>template content</span>' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'><span>existing content</span></div>"
applyBindings({ myCollection: [ {} ] }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<span>template content</span>')
})
it('Should render for each item in an array but doesn\'t rerender everything if you push or splice', function () {
var myArray = observableArray([{ personName: 'Bob' }, { personName: 'Frank'}])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: '<div>The item is [js: nomangle$data.personName]</div>' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div>the item is bob</div><div>the item is frank</div>')
var originalBobNode = testNode.childNodes[0].childNodes[0]
var originalFrankNode = testNode.childNodes[0].childNodes[1]
myArray.push({ personName: 'Steve' })
expect(testNode.childNodes[0]).toContainHtml('<div>the item is bob</div><div>the item is frank</div><div>the item is steve</div>')
expect(testNode.childNodes[0].childNodes[0]).toEqual(originalBobNode)
expect(testNode.childNodes[0].childNodes[1]).toEqual(originalFrankNode)
})
it('Should apply bindings within the context of each item in the array', function () {
var myArray = observableArray([{ personName: 'Bob' }, { personName: 'Frank'}])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is <span data-bind='text: personName'></span>" }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('the item is <span data-bind="text: personname">bob</span>the item is <span data-bind="text: personname">frank</span>')
})
it('Should only bind each group of output nodes once', function () {
var initCalls = 0
bindingHandlers.countInits = { init: function () { initCalls++ } }
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "<span data-bind='countInits: true'></span>" }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: [1, 2, 3] }, testNode)
expect(initCalls).toEqual(3) // 3 because there were 3 items in myCollection
})
it('Should handle templates in which the very first node has a binding', function () {
// Represents https://github.com/SteveSanderson/knockout/pull/440
// Previously, the rewriting (which introduces a comment node before the bound node) was interfering
// with the array-to-DOM-node mapping state tracking
setTemplateEngine(new dummyTemplateEngine({ mytemplate: "<div data-bind='text: $data'></div>" }))
testNode.innerHTML = "<div data-bind=\"template: { name: 'mytemplate', foreach: items }\"></div>"
// Bind against initial array containing one entry. UI just shows "original"
var myArray = observableArray(['original'])
applyBindings({ items: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div data-bind="text: $data">original</div>')
// Now replace the entire array contents with one different entry.
// UI just shows "new" (previously with bug, showed "original" AND "new")
myArray(['new'])
expect(testNode.childNodes[0]).toContainHtml('<div data-bind="text: $data">new</div>')
})
it('Should handle chained templates in which the very first node has a binding', function () {
// See https://github.com/SteveSanderson/knockout/pull/440 and https://github.com/SteveSanderson/knockout/pull/144
setTemplateEngine(new dummyTemplateEngine({
outerTemplate: "<div data-bind='text: $data'></div>[renderTemplate:innerTemplate]x", // [renderTemplate:...] is special syntax supported by dummy template engine
innerTemplate: "inner <span data-bind='text: 123'></span>"
}))
testNode.innerHTML = "<div data-bind=\"template: { name: 'outerTemplate', foreach: items }\"></div>"
// Bind against initial array containing one entry.
var myArray = observableArray(['original'])
applyBindings({ items: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div data-bind="text: $data">original</div>inner <span data-bind="text: 123">123</span>x')
// Now replace the entire array contents with one different entry.
myArray(['new'])
expect(testNode.childNodes[0]).toContainHtml('<div data-bind="text: $data">new</div>inner <span data-bind="text: 123">123</span>x')
})
it('Should handle templates in which the very first node has a binding but it does not reference any observables', function () {
// Represents https://github.com/SteveSanderson/knockout/issues/739
// Previously, the rewriting (which introduces a comment node before the bound node) was interfering
// with the array-to-DOM-node mapping state tracking
setTemplateEngine(new dummyTemplateEngine({ mytemplate: "<div data-bind='attr: {}'>[js:nomangle$data.name()]</div>" }))
testNode.innerHTML = "<div data-bind=\"template: { name: 'mytemplate', foreach: items }\"></div>"
// Bind against array, referencing an observable property
var myItem = { name: observable('a') }
applyBindings({ items: [myItem] }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div data-bind="attr: {}">a</div>')
// Modify the observable property and check that UI is updated
// Previously with the bug, it wasn't updated because the removal of the memo comment caused the array-to-DOM-node computed to be disposed
myItem.name('b')
expect(testNode.childNodes[0]).toContainHtml('<div data-bind="attr: {}">b</div>')
})
it('Should apply bindings with an $index in the context', function () {
var myArray = observableArray([{ personName: 'Bob' }, { personName: 'Frank'}])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item # is <span data-bind='text: $index'></span>" }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('the item # is <span data-bind="text: $index">0</span>the item # is <span data-bind="text: $index">1</span>')
})
it('Should update bindings that reference an $index if the list changes', function () {
var myArray = observableArray([{ personName: 'Bob' }, { personName: 'Frank'}])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item <span data-bind='text: personName'></span>is <span data-bind='text: $index'></span>" }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('the item <span data-bind="text: personname">bob</span>is <span data-bind="text: $index">0</span>the item <span data-bind="text: personname">frank</span>is <span data-bind="text: $index">1</span>')
var frank = myArray.pop() // remove frank
expect(testNode.childNodes[0]).toContainHtml('the item <span data-bind="text: personname">bob</span>is <span data-bind="text: $index">0</span>')
myArray.unshift(frank) // put frank in the front
expect(testNode.childNodes[0]).toContainHtml('the item <span data-bind="text: personname">frank</span>is <span data-bind="text: $index">0</span>the item <span data-bind="text: personname">bob</span>is <span data-bind="text: $index">1</span>')
})
it('Should accept array with "undefined" and "null" items', function () {
var myArray = observableArray([undefined, null])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is <span data-bind='text: String($data)'></span>" }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
options.bindingGlobals.String = String
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('the item is <span data-bind="text: string($data)">undefined</span>the item is <span data-bind="text: string($data)">null</span>')
})
it('Should update DOM nodes when a dependency of their mapping function changes', function () {
var myObservable = observable('Steve')
var myArray = observableArray([{ personName: 'Bob' }, { personName: myObservable }, { personName: 'Another' }])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: '<div>The item is [js: unwrap(nomangle$data.personName)]</div>' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div>the item is bob</div><div>the item is steve</div><div>the item is another</div>')
var originalBobNode = testNode.childNodes[0].childNodes[0]
myObservable('Steve2')
expect(testNode.childNodes[0]).toContainHtml('<div>the item is bob</div><div>the item is steve2</div><div>the item is another</div>')
expect(testNode.childNodes[0].childNodes[0]).toEqual(originalBobNode)
// Ensure we can still remove the corresponding nodes (even though they've changed), and that doing so causes the subscription to be disposed
expect(myObservable.getSubscriptionsCount()).toEqual(1)
myArray.splice(1, 1)
expect(testNode.childNodes[0]).toContainHtml('<div>the item is bob</div><div>the item is another</div>')
myObservable('Something else') // Re-evaluating the observable causes the orphaned subscriptions to be disposed
expect(myObservable.getSubscriptionsCount()).toEqual(0)
})
it('Should treat a null parameter as meaning \'no items\'', function () {
var myArray = observableArray(['A', 'B'])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: 'hello' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0].childNodes.length).toEqual(2)
// Now set the observable to null and check it's treated like an empty array
// (because how else should null be interpreted?)
myArray(null)
expect(testNode.childNodes[0].childNodes.length).toEqual(0)
})
it('Should accept an \"as\" option to define an alias for the iteration variable', function () {
// Note: There are more detailed specs (e.g., covering nesting) associated with the "foreach" binding which
// uses this templating functionality internally.
var myArray = observableArray(['A', 'B'])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: '[js:bindingContext.myAliasedItem]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection, as: \"myAliasedItem\" }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainText('AB')
})
it('Should stop tracking inner observables when the container node is removed', function () {
var innerObservable = observable('some value')
var myArray = observableArray([{obsVal: innerObservable}, {obsVal: innerObservable}])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: 'The item is [js: unwrap(nomangle$data.obsVal)]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(innerObservable.getSubscriptionsCount()).toEqual(2)
removeNode(testNode.childNodes[0])
expect(innerObservable.getSubscriptionsCount()).toEqual(0)
})
it('Should stop tracking inner observables related to each array item when that array item is removed', function () {
var innerObservable = observable('some value')
var myArray = observableArray([{obsVal: innerObservable}, {obsVal: innerObservable}])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: 'The item is [js: unwrap(nomangle$data.obsVal)]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(innerObservable.getSubscriptionsCount()).toEqual(2)
myArray.splice(1, 1)
expect(innerObservable.getSubscriptionsCount()).toEqual(1)
myArray([])
expect(innerObservable.getSubscriptionsCount()).toEqual(0)
})
it('Should omit any items whose \'_destroy\' flag is set (unwrapping the flag if it is observable)', function () {
options.includeDestroyed = false
var myArray = observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp: 3 }, { someProp: 4, _destroy: observable(false) }])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: '<div>someProp=[js: nomangle$data.someProp]</div>' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection, includeDestroyed: false }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div>someprop=1</div><div>someprop=3</div><div>someprop=4</div>')
})
it('Should include any items whose \'_destroy\' flag is set if you use includeDestroyed', function () {
var myArray = observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp: 3 }])
setTemplateEngine(new dummyTemplateEngine({ itemTemplate: '<div>someProp=[js: nomangle$data.someProp]</div>' }))
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: myCollection, includeDestroyed: true }'></div>"
applyBindings({ myCollection: myArray }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div>someprop=1</div><div>someprop=2</div><div>someprop=3</div>')
})
it('Should be able to render a different template for each array entry by passing a function as template name, with the array entry\'s binding context available as a second parameter', function () {
var myArray = observableArray([
{ preferredTemplate: 1, someProperty: 'firstItemValue' },
{ preferredTemplate: 2, someProperty: 'secondItemValue' }
])
setTemplateEngine(new dummyTemplateEngine({
firstTemplate: '<div>Template1Output, [js: nomangle$data.someProperty]</div>',
secondTemplate: '<div>Template2Output, [js: nomangle$data.someProperty]</div>'
}))
testNode.innerHTML = "<div data-bind='template: {name: getTemplateModelProperty, foreach: myCollection}'></div>"
var getTemplate = function (dataItem, bindingContext) {
// Having the item's binding context available means you can read sibling or parent level properties
expect(bindingContext.$parent.anotherProperty).toEqual(123)
return dataItem.preferredTemplate == 1 ? 'firstTemplate' : 'secondTemplate'
}
applyBindings({ myCollection: myArray, getTemplateModelProperty: getTemplate, anotherProperty: 123 }, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div>template1output, firstitemvalue</div><div>template2output, seconditemvalue</div>')
})
it('Should update all child contexts and bindings when used with a top-level observable view model', function () {
var myVm = observable({items: ['A', 'B', 'C'], itemValues: { 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }})
var engine = new dummyTemplateEngine({
itemTemplate: "<span>The <span data-bind='text: $index'> </span> item <span data-bind='text: $data'> </span> has <span data-bind='template: { name: \"valueTemplate\", foreach: $root.itemValues[$data] }'> </span> </span>",
valueTemplate: "<span data-bind='text: $index'> </span>.<span data-bind='text: $data'> </span>,"
})
engine.createJavaScriptEvaluatorBlock = function (script) { return '[[js:' + script + ']]' } // because we're using a binding with brackets
setTemplateEngine(engine)
testNode.innerHTML = "<div data-bind='template: { name: \"itemTemplate\", foreach: items }'></div>"
applyBindings(myVm, testNode)
expect(testNode.childNodes[0]).toContainText('The 0 item A has 0.1,1.2,2.3, The 1 item B has 0.4,1.5,2.6, The 2 item C has 0.7,1.8,2.9, ')
myVm({items: ['C', 'B', 'A'], itemValues: { 'A': [1, 2, 30], 'B': [4, 5, 60], 'C': [7, 8, 90] }})
expect(testNode.childNodes[0]).toContainText('The 0 item C has 0.7,1.8,2.90, The 1 item B has 0.4,1.5,2.60, The 2 item A has 0.1,1.2,2.30, ')
})
})
it('Data binding syntax should support \"if\" condition', function () {
setTemplateEngine(new dummyTemplateEngine({ myTemplate: 'Value: [js: nomangle$data.myProp().childProp]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", \"if\": myProp }'></div>"
var viewModel = { myProp: observable({ childProp: 'abc' }) }
applyBindings(viewModel, testNode)
// Initially there is a value
expect(testNode.childNodes[0]).toContainText('Value: abc')
// Causing the condition to become false causes the output to be removed
viewModel.myProp(null)
expect(testNode.childNodes[0]).toContainText('')
// Causing the condition to become true causes the output to reappear
viewModel.myProp({ childProp: 'def' })
expect(testNode.childNodes[0]).toContainText('Value: def')
})
it('Data binding syntax should support \"ifnot\" condition', function () {
setTemplateEngine(new dummyTemplateEngine({ myTemplate: 'Hello' }))
testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", ifnot: shouldHide }'></div>"
var viewModel = { shouldHide: observable(true) }
applyBindings(viewModel, testNode)
// Initially there is no output (shouldHide=true)
expect(testNode.childNodes[0]).toContainText('')
// Causing the condition to become false causes the output to be displayed
viewModel.shouldHide(false)
expect(testNode.childNodes[0]).toContainText('Hello')
// Causing the condition to become true causes the output to disappear
viewModel.shouldHide(true)
expect(testNode.childNodes[0]).toContainText('')
})
it('Data binding syntax should support \"if\" condition in conjunction with foreach', function () {
setTemplateEngine(new dummyTemplateEngine({ myTemplate: 'Value: [js: nomangle$data.myProp().childProp]' }))
testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", \"if\": myProp, foreach: [$data, $data, $data] }'></div>"
var viewModel = { myProp: observable({ childProp: 'abc' }) }
applyBindings(viewModel, testNode)
expect(testNode.childNodes[0].childNodes[0].nodeValue).toEqual('Value: abc')
expect(testNode.childNodes[0].childNodes[1].nodeValue).toEqual('Value: abc')
expect(testNode.childNodes[0].childNodes[2].nodeValue).toEqual('Value: abc')
// Causing the condition to become false causes the output to be removed
viewModel.myProp(null)
expect(testNode.childNodes[0]).toContainText('')
// Causing the condition to become true causes the output to reappear
viewModel.myProp({ childProp: 'def' })
expect(testNode.childNodes[0].childNodes[0].nodeValue).toEqual('Value: def')
expect(testNode.childNodes[0].childNodes[1].nodeValue).toEqual('Value: def')
expect(testNode.childNodes[0].childNodes[2].nodeValue).toEqual('Value: def')
})
it('Should be able to populate checkboxes from inside templates, despite IE6 limitations', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input type='checkbox' data-bind='checked:isChecked' />" }))
renderTemplate('someTemplate', {isChecked: true}, {}, testNode)
expect(testNode.childNodes[0].checked).toEqual(true)
})
it('Should be able to populate radio buttons from inside templates, despite IE6 limitations', function () {
setTemplateEngine(new dummyTemplateEngine({ someTemplate: "<input type='radio' name='somename' value='abc' data-bind='checked:someValue' />" }))
renderTemplate('someTemplate', {someValue: 'abc'}, {}, testNode)
expect(testNode.childNodes[0].checked).toEqual(true)
})
it('Data binding \'templateOptions\' should be passed to template', function () {
var myModel = {
someAdditionalData: { myAdditionalProp: 'someAdditionalValue' },
people: observableArray([
{ name: 'Alpha' },
{ name: 'Beta' }
])
}
setTemplateEngine(new dummyTemplateEngine({myTemplate: '<div>Person [js:nomangle$data.name] has additional property [js:rt_options.templateOptions.myAdditionalProp]</div>'}))
testNode.innerHTML = "<div data-bind='template: {name: \"myTemplate\", foreach: people, templateOptions: someAdditionalData }'></div>"
applyBindings(myModel, testNode)
expect(testNode.childNodes[0]).toContainHtml('<div>person alpha has additional property someadditionalvalue</div><div>person beta has additional property someadditionalvalue</div>')
})
it('If the template binding is updated, should dispose any template subscriptions previously associated with the element', function () {
var myObservable = observable('some value'),
myModel = {
subModel: observable({ myObservable: myObservable })
}
setTemplateEngine(new dummyTemplateEngine({myTemplate: '<span>The value is [js: nomangle$data.myObservable()]</span>'}))
testNode.innerHTML = "<div data-bind='template: {name: \"myTemplate\", data: subModel}'></div>"
applyBindings(myModel, testNode)
// Right now the template references myObservable, so there should be exactly one subscription on it
expect(testNode.childNodes[0]).toContainText('The value is some value')
expect(myObservable.getSubscriptionsCount()).toEqual(1)
var renderedNode1 = testNode.childNodes[0].childNodes[0]
// By changing the object for subModel, we force the data-bind value to be re-evaluated and the template to be re-rendered,
// setting up a new template subscription, so there have now existed two subscriptions on myObservable...
myModel.subModel({ myObservable: myObservable })
expect(testNode.childNodes[0].childNodes[0]).not.toEqual(renderedNode1)
// ...but, because the old subscription should have been disposed automatically, there should only be one left
expect(myObservable.getSubscriptionsCount()).toEqual(1)
})
it('Should be able to specify a template engine instance using data-bind syntax', function () {
setTemplateEngine(new dummyTemplateEngine({ theTemplate: 'Default output' })) // Not going to use this one
var alternativeTemplateEngine = new dummyTemplateEngine({ theTemplate: 'Alternative output' })
testNode.innerHTML = "<div data-bind='template: { name: \"theTemplate\", templateEngine: chosenEngine }'></div>"
applyBindings({ chosenEngine: alternativeTemplateEngine }, testNode)
expect(testNode.childNodes[0]).toContainText('Alternative output')
})
it('Should be able to bind $data to an alias using \'as\'', function () {
setTemplateEngine(new dummyTemplateEngine({
myTemplate: "ValueLiteral: [js: nomangle$data.prop], ValueBound: <span data-bind='text: item.prop'></span>"
}))
testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", data: someItem, as: \"item\" }'></div>"
applyBindings({ someItem: { prop: 'Hello' } }, testNode)
expect(testNode.childNodes[0]).toContainText('ValueLiteral: Hello, ValueBound: Hello')
})
it('Data-bind syntax should expose parent binding context as $parent if binding with an explicit \"data\" value', function () {
setTemplateEngine(new dummyTemplateEngine({
myTemplate: "ValueLiteral: [js:bindingContext.$parent.parentProp], ValueBound: <span data-bind='text: $parent.parentProp'></span>"
}))
testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\", data: someItem }'></div>"
applyBindings({ someItem: {}, parentProp: 'Hello' }, testNode)
expect(testNode.childNodes[0]).toContainText('ValueLiteral: Hello, ValueBound: Hello')
})
it('Data-bind syntax should expose all ancestor binding contexts as $parents', function () {
setTemplateEngine(new dummyTemplateEngine({
outerTemplate: "<div data-bind='template: { name:\"middleTemplate\", data: middleItem }'></div>",
middleTemplate: "<div data-bind='template: { name: \"innerTemplate\", data: innerItem }'></div>",
innerTemplate: '(Data:[js:bindingContext.$data.val], Parent:[[js:bindingContext.$parents[0].val]], Grandparent:[[js:bindingContext.$parents[1].val]], Root:[js:bindingContext.$root.val], Depth:[js:bindingContext.$parents.length])'
}))
testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\", data: outerItem }'></div>"
applyBindings({
val: 'ROOT',
outerItem: {
val: 'OUTER',
middleItem: {
val: 'MIDDLE',
innerItem: { val: 'INNER' }
}
}
}, testNode)
expect(testNode.childNodes[0].childNodes[0]).toContainText('(Data:INNER, Parent:MIDDLE, Grandparent:OUTER, Root:ROOT, Depth:3)')
})
xit('Should not be allowed to rewrite templates that embed anonymous templates', function () {
// SKIP because we have removed template rewriting.
//
// ----
// The reason is that your template engine's native control flow and variable evaluation logic is going to run first, independently
// of any KO-native control flow, so variables would get evaluated in the wrong context. Example:
//
// <div data-bind="foreach: someArray">
// ${ somePropertyOfEachArrayItem } <-- This gets evaluated *before* the foreach binds, so it can't reference array entries
// </div>
//
// It should be perfectly OK to fix this just by preventing anonymous templates within rewritten templates, because
// (1) The developer can always use their template engine's native control flow syntax instead of the KO-native ones - that will work
// (2) The developer can use KO's native templating instead, if they are keen on KO-native control flow or anonymous templates
setTemplateEngine(new dummyTemplateEngine({
myTemplate: "<div data-bind='template: { data: someData }'>Childprop: [js: nomangle$data.childProp]</div>"
}))
testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\" }'></div>"
expect(function () {
applyBindings({ someData: { childProp: 'abc' } }, testNode)
}).toThrowContaining('This template engine does not support anonymous templates nested within its templates')
})
xit('Should not be allowed to rewrite templates that embed control flow bindings', function () {
// SKIP because we have removed template rewriting.
// ----
// Same reason as above (also include binding names with quotes and spaces to show that formatting doesn't matter)
arrayForEach(['if', 'ifnot', 'with', 'foreach', '"if"', ' with '], function (bindingName) {
setTemplateEngine(new dummyTemplateEngine({ myTemplate: "<div data-bind='" + bindingName + ": \"SomeValue\"'>Hello</div>" }))
testNode.innerHTML = "<div data-bind='template: { name: \"myTemplate\" }'></div>"
domData.clear(testNode)
expect(function () {
applyBindings({ someData: { childProp: 'abc' } }, testNode)
}).toThrowContaining('This template engine does not support')
})
})
it('Data binding syntax should permit nested templates using virtual containers (with arbitrary internal whitespace and newlines)', function () {
setTemplateEngine(new dummyTemplateEngine({
outerTemplate: 'Outer <!-- ko template: ' +
'{ name: "innerTemplate" } ' +
'--><!-- /ko -->',
innerTemplate: "Inner via inline binding: <span data-bind='text: \"someText\"'></span>"
}))
var model = { }
testNode.innerHTML = "<div data-bind='template: { name: \"outerTemplate\" }'></div>"
applyBindings(model, testNode)
expect(testNode.childNodes[0]).toContainHtml('outer <!-- ko template: { name: "innertemplate" } -->inner via inline binding: <span data-bind="text: "sometext"">sometext</span><!-- /ko -->')
})
it('Should be able to render anonymous templates using virtual containers', function () {
setTemplateEngine(new dummyTemplateEngine())
testNode.innerHTML = 'Start <!-- ko template: { data: someData } -->Childprop: [js: nomangle$data.childProp]<!-- /ko --> End'
applyBindings({ someData: { childProp: 'abc' } }, testNode)
expect(testNode).toContainHtml('start <!-- ko template: { data: somedata } -->childprop: abc<!-- /ko -->end')
})
it('Should render sub-context with {data: }', function () {
testNode.innerHTML = "<div data-bind='template: {data: outer}'><span data-bind='text: inner'></span></div>"
applyBindings({ outer: {inner: 'x' }}, testNode)
expect(testNode).toContainHtml('<div data-bind="template: {data: outer}"><span data-bind="text: inner">x</span></div>')
})
it('Should be able to use anonymous templates that contain first-child comment nodes', function () {
// This represents issue https://github.com/SteveSanderson/knockout/issues/188
// (IE < 9 strips out leading comment nodes when you use .innerHTML)
setTemplateEngine(new dummyTemplateEngine({}))
testNode.innerHTML = "start <div data-bind='foreach: [1,2]'><span><!-- leading comment -->hello</span></div>"
applyBindings(null, testNode)
expect(testNode).toContainHtml('start <div data-bind="foreach: [1,2]"><span><!-- leading comment -->hello</span><span><!-- leading comment -->hello</span></div>')
})
it('Should allow anonymous templates output to include top-level virtual elements, and will bind their virtual children only once', function () {
delete bindingHandlers.nonexistentHandler
var initCalls = 0
bindingHandlers.countInits = { init: function () { initCalls++ } }
testNode.innerHTML = "<div data-bind='template: {}'><!-- ko nonexistentHandler: true --><span data-bind='countInits: true'></span><!-- /ko --></div>"
applyBindings(null, testNode)
expect(initCalls).toEqual(1)
})
it('Should be possible to combine template rewriting, foreach, and a node preprocessor', function () {
// This spec verifies that the use of fixUpContinuousNodeArray in templating.js correctly handles the scenario
// where a memoized comment node is the first node outputted by 'foreach', and it gets removed by unmemoization.
// In this case we rely on fixUpContinuousNodeArray to work out which remaining nodes correspond to the 'foreach'
// output so they can later be removed when the model array changes.
class TemplateTestProvider extends DataBindProvider {
preprocessNode (node) {
// This preprocessor doesn't change the rendered nodes. But simply having a preprocessor means
// that templating.js has to recompute which DOM nodes correspond to the foreach output, since
// you might have modified that set.
return [node]
}
}
options.bindingProviderInstance = new TemplateTestProvider()
options.bindingProviderInstance.bindingHandlers.set(templateBindings)
options.bindingProviderInstance.bindingHandlers.set(coreBindings)
setTemplateEngine(new dummyTemplateEngine({}))
testNode.innerHTML = "<div data-bind='template: { foreach: items }'><button data-bind='text: $data'></button> OK. </div>"
var items = observableArray(['Alpha', 'Beta'])
applyBindings({ items: items }, testNode)
expect(testNode).toContainText('Alpha OK. Beta OK. ')
// Check that 'foreach' knows which set of elements to remove when an item vanishes from the model array,
// even though the original 'foreach' output's first node, the memo comment, was removed during unmemoization.
items.shift()
expect(testNode).toContainText('Beta OK. ')
})
it('Should not throw errors if trying to apply text to a non-rendered node', function () {
// Represents https://github.com/SteveSanderson/knockout/issues/660
// A <span> can't go directly into a <tr>, so modern browsers will silently strip it. We need to verify this doesn't
// throw errors during unmemoization (when unmemoizing, it will try to apply the text to the following text node
// instead of the node you intended to bind to).
// Note that IE < 9 won't strip the <tr>; instead it has much stranger behaviors regarding unexpected DOM structures.
// It just happens not to give an error in this particular case, though it would throw errors in many other cases
// of malformed template DOM.
setTemplateEngine(new dummyTemplateEngine({
myTemplate: "<tr><span data-bind=\"text: 'Some text'\"></span> </tr>" // The whitespace after the closing span is what triggers the strange HTML parsing
}))
testNode.innerHTML = "<div data-bind='template: \"myTemplate\"'></div>"
applyBindings(null, testNode)
// Since the actual template markup was invalid, we don't really care what the
// resulting DOM looks like. We are only verifying there were no exceptions.
})
it('Should be possible to render a template to a document fragment', function () {
// Represents https://github.com/knockout/knockout/issues/1162
// This was failing on IE8
setTemplateEngine(new dummyTemplateEngine({
myTemplate: '<p>myval: [js: nomangle$data.myVal]</p>' // The whitespace after the closing span is what triggers the strange HTML parsing
}))
var testDocFrag = document.createDocumentFragment()
renderTemplate('myTemplate', { myVal: 123 }, null, testDocFrag)
// Can't use .toContainHtml directly on doc frags, so check DOM structure manually
expect(testDocFrag.childNodes.length).toEqual(1)
expect(testDocFrag.childNodes[0].tagName).toEqual('P')
expect(testDocFrag.childNodes[0]).toContainHtml('myval: 123')
})
describe('The `condition` exposed via the domData for `else` chaining', function () {
it('is false iff the `if` is false', function () {
var condition = observable(true)
testNode.innerHTML = '<!-- ko template: {if: condition} -->True<!-- /ko -->'
applyBindings({condition: condition}, testNode)
expect(domData.get(testNode.childNodes[0], 'conditional').elseChainSatisfied()).toEqual(true)
condition(false)
expect(domData.get(testNode.childNodes[0], 'conditional').elseChainSatisfied()).toEqual(false)
})
it('is false iff the `ifnot` is true', function () {
var condition = observable(true)
testNode.innerHTML = '<!-- ko template: {ifnot: condition} -->True<!-- /ko -->'
applyBindings({condition: condition}, testNode)
expect(domData.get(testNode.childNodes[0], 'conditional').elseChainSatisfied()).toEqual(false)
condition(false)
expect(domData.get(testNode.childNodes[0], 'conditional').elseChainSatisfied()).toEqual(true)
})
it('is false iff the `foreach` is empty', function () {
var items = observable()
testNode.innerHTML = '<!-- ko template: {foreach: items} -->True<!-- /ko -->'
applyBindings({items: items}, testNode)
expect(domData.get(testNode.childNodes[0], 'conditional').elseChainSatisfied()).toEqual(false)
items([])
expect(domData.get(testNode.childNodes[0], 'conditional').elseChainSatisfied()).toEqual(false)
expect(domData.get(testNode.childNodes[0], 'conditional').elseChainSatisfied()).toEqual(false)
items([123])
expect(domData.get(testNode.childNodes[0], 'conditional').elseChainSatisfied()).toEqual(true)
})
it('is false iff the `if` is false, on a DOM node', function () {
var condition = observable(true)
testNode.setAttribute('data-bind', 'template: {if: condition}')
testNode.innerHTML = 'True'
applyBindings({condition: condition}, testNode)
expect(domData.get(testNode, 'conditional')
.elseChainSatisfied()).toEqual(true)
condition(false)
expect(domData.get(testNode, 'conditional')
.elseChainSatisfied()).toEqual(false)
})
})
}) | the_stack |
import Game from '../Game';
import ReturnOfGanon from '../fonts/ReturnOfGanon';
import { itemDescriptors, IItemDescriptor, IconCallback } from '../data/ItemDescriptors';
import Constants from '../data/Constants';
import GameState from '../states/GameState';
class InventoryItemSprite extends Phaser.Sprite {
game: Game;
item: IItemDescriptor;
_frame: Phaser.Frame;
}
export default class Inventory extends Phaser.Group {
game: Game;
private openSound: Phaser.Sound;
private empty: boolean;
private frames: Phaser.FrameData;
private grid: InventoryItemSprite[][][];
private items: TTable<InventoryItemSprite>;
private selected: InventoryItemSprite;
private selector: Phaser.Sprite;
private activeItem: Phaser.Sprite;
private activeText: ReturnOfGanon;
private isSliding: boolean;
private _temp: Phaser.Point;
constructor(game: Game, parent?: any) {
super(game, parent, 'inventory');
this.openSound = game.add.sound('effect_pause_close', Constants.AUDIO_EFFECT_VOLUME);
this.grid = [];
this.empty = false;
this.isSliding = false;
this.frames = game.cache.getFrameData('sprite_gui');
this.position.y = -Constants.GAME_HEIGHT;
this.visible = false;
this._temp = new Phaser.Point();
this._setup();
(<GameState>this.game.state.getCurrentState()).onInputDown.add(this._onInputDown, this);
(<GameState>this.game.state.getCurrentState()).onInputUp.add(this._onInputUp, this);
}
destroy(destroyChildren?: boolean) {
super.destroy(destroyChildren);
(<GameState>this.game.state.getCurrentState()).onInputDown.removeAll(this);
(<GameState>this.game.state.getCurrentState()).onInputUp.removeAll(this);
}
updateValues() {
const wasEmpty = this.empty;
for (let i in this.items) {
if (!this.items.hasOwnProperty(i)) { continue; }
const sprite = this.items[i];
const item = sprite.item;
if (!item) { continue; }
const name: string = item.name;
const val: number = this.game.player.inventory[name];
let ico: string;
// set the texture and visibility
if (val || (val === 0 && (name === 'armor' || name === 'crystal'))) {
// some items have other sprites that should be enabled as well
if (name === 'flippers') {
this.items['txtSwim'].visible = true;
}
else if (name === 'boot') {
this.items['txtRun'].visible = true;
}
// run icon function if there is one
if (typeof item.icon === 'function') {
ico = (<IconCallback>item.icon)(this.game);
}
else {
ico = (<string>item.icon).replace('%d', val.toString());
}
// enable item and set texture
sprite.setFrame(this.frames.getFrameByName(ico));
sprite.visible = true;
if (item.grid) {
this.empty = false;
}
}
else {
sprite.visible = false;
}
}
// always show lift power
this.items['txtLiftNum'].visible = true;
this.items['txtLiftNum'].setFrame(this.frames.getFrameByName(
(<string>this.items['txtLiftNum'].item.icon).replace('%d', (this.game.player.inventory.gloves + 1).toString())
));
// first item added
if (wasEmpty && !this.empty) {
// setup to scan right to the first item and select it
// this.selected.x = -1;
// this.selected.y = 0;
// this.onMove('right', { down: true });
// this.onMove('right', { down: false });
// make sure it is equipted
// TODO: hud updates??
// this.game.player.equipted = this.grid[this.selected.x][this.selected.y][0].item.name;
// lttp.play.hud.updateValues(link);
}
this._moveSelector();
}
open(cb?: Function) {
if (this.isSliding) { return; }
this.isSliding = true;
this.visible = true;
this.openSound.play();
this.game.add.tween(this)
.to({ y: 0 }, Constants.PLAYER_INVENTORY_DROP_TIME)
.start()
.onComplete.addOnce(function () {
this.isSliding = false;
if (cb) { cb(); }
}, this);
}
close(cb: Function) {
if (this.isSliding) { return; }
this.isSliding = true;
this.game.add.tween(this)
.to({ y: -Constants.GAME_HEIGHT }, Constants.PLAYER_INVENTORY_DROP_TIME)
.start()
.onComplete.addOnce(function () {
this.visible = false;
this.isSliding = false;
if (cb) { cb(); }
}, this);
}
move(dir: number) {
if (this.empty) { return; }
let next: Phaser.Point;
switch (dir) {
case Phaser.UP:
next = this._findNext(0, -1); break;
case Phaser.DOWN:
next = this._findNext(0, 1); break;
case Phaser.LEFT:
next = this._findNext(-1, 0); break;
case Phaser.RIGHT:
next = this._findNext(1, 0); break;
}
if (next) {
this.selected = this.grid[next.x][next.y][0];
this._moveSelector();
}
}
private _setup() {
// add background
this.game.add.sprite(0, 0, 'sprite_gui', 'inventory.png', this);
// add item sprites
for (let i in itemDescriptors) {
if (!itemDescriptors.hasOwnProperty(i)) { continue; }
const item = itemDescriptors[i];
const ico = typeof item.icon === 'function' ? (<IconCallback>item.icon)(this.game) : (<string>item.icon);
ico.replace('%d', '1');
let sprite = new InventoryItemSprite(this.game, item.position[0], item.position[1], 'sprite_gui', ico);
sprite.item = item;
this.add(sprite);
if (item.grid) {
this._addToGrid(sprite, item.grid);
}
this.items[item.name] = sprite;
}
this.selector = this.game.add.sprite(0, 0, 'sprite_gui', 'selector.png', this);
this.selector.visible = false;
this.activeItem = this.game.add.sprite(200, 25, 'sprite_gui', 'items/lantern.png', this);
this.activeItem.visible = false;
this.activeText = new ReturnOfGanon(this.game, 175, 55);
this.activeText.visible = false;
this.add(this.activeText);
}
private _addToGrid(sprite: InventoryItemSprite, pos: number[]) {
if (!this.grid[pos[0]]) {
this.grid[pos[0]] = [];
}
if (!this.grid[pos[0]][pos[1]]) {
this.grid[pos[0]][pos[1]] = [];
}
this.grid[pos[0]][pos[1]].push(sprite);
}
private _moveSelector() {
const sprite = this.selected;
this.selector.position.x = sprite.position.x - 5;
this.selector.position.y = sprite.position.y - 5;
this.activeItem.setFrame(sprite._frame);
this.activeText.text = sprite.item.name;
if (sprite.visible) {
this.selector.visible = true;
this.activeItem.visible = true;
this.activeText.visible = true;
}
}
private _findNext(stepX: number, stepY: number) {
const pos = this._temp.set(this.selected.item.grid[0], this.selected.item.grid[1]);
const maxX = this.grid.length - 1;
const maxY = this.grid[0].length - 1;
let found = false;
while (!found) {
pos.x += stepX;
pos.y += stepY;
this._wrapGrid(pos, maxX, maxY);
const val = this.grid[pos.x][pos.y];
for (let i = val.length - 1; i > -1; --i) {
found = found || val[i].visible;
}
}
return pos;
}
private _wrapGrid(pos: Phaser.Point, maxX: number, maxY: number) {
// wrap X
if (pos.x < 0) {
pos.y--;
pos.x = maxX;
// left of first slot, goto last
if (pos.y < 0) {
pos.y = maxY;
}
}
else if (pos.x > maxX) {
pos.y++;
pos.x = 0;
// right of last slot, goto first
if (pos.y > maxY) {
pos.y = 0;
}
}
// wrap Y
if (pos.y < 0) {
pos.x--;
pos.y = maxY;
// up off first slot, goto last
if (pos.x < 0) {
pos.x = maxX;
}
}
else if (pos.y > maxY) {
pos.x++;
pos.y = 0;
// down off last slot, goto first
if (pos.x > maxX) {
pos.x = 0;
}
}
}
private _onInputDown(key: number, value: number, event: any) {
switch (key) {
// UP
case Phaser.Keyboard.UP:
case Phaser.Keyboard.W:
case Phaser.Gamepad.XBOX360_DPAD_UP:
this.move(Phaser.UP);
break;
// DOWN
case Phaser.Keyboard.DOWN:
case Phaser.Keyboard.S:
case Phaser.Gamepad.XBOX360_DPAD_DOWN:
this.move(Phaser.DOWN);
break;
// LEFT
case Phaser.Keyboard.LEFT:
case Phaser.Keyboard.A:
case Phaser.Gamepad.XBOX360_DPAD_LEFT:
this.move(Phaser.LEFT);
break;
// RIGHT
case Phaser.Keyboard.RIGHT:
case Phaser.Keyboard.D:
case Phaser.Gamepad.XBOX360_DPAD_RIGHT:
this.move(Phaser.RIGHT);
break;
// AXIS UP/DOWN
case Phaser.Gamepad.XBOX360_STICK_LEFT_Y:
this.move(value > 0 ? Phaser.DOWN : Phaser.UP);
break;
// AXIS LEFT/RIGHT
case Phaser.Gamepad.XBOX360_STICK_LEFT_X:
this.move(value > 0 ? Phaser.RIGHT : Phaser.LEFT);
break;
}
}
private _onInputUp(key: number, value: number, event: any) {
// TODO: Implementation needed?
}
} | the_stack |
import * as child_process from "child_process";
import * as util from 'util';
import U = pxt.Util;
/*
Purpose:
UploadRefs uploads git objects (commits, trees, blobs) to cloud storage for
retrieval when serving our web apps or docs. The cloud also has logic to
request (from github) git objects and store them in the cloud however the
server can run out of memory (which should be fixable) when we're uploading lots of objects
so this CLI command is useful when uploading large amounts of git objects.
TODOs (updated 8/14/2019 by Daryl & Michal)
- Upload tree & file objects first: currently this code uploads
all commits first and then the associated "tree" and blob objects.
The issue with this is that the cloud checks for the exists of a
commit object and assumes if it exists that all the associated tree
objects have already been uploaded. So if "uploadRefs" gets interrupted,
the git cache could be in an inconsitent state where commits are uploaded
but not all of the necessary data is present. To fix the broken state, we
simply need to let uploadRefs run to completion, but it'd be better to not
allow this inconsitency in the first place by uploading commits last.
- Handle network interruptions: when running "pxt uploadrefs", we occassionally
get "INTERNAL ERROR: Error: socket hang up" errors which can leave things in a
bad state (see above.) We should have retry logic built in.
- Add commandline switches for:
- Traverse parent commits. By default uploadRefs will not follow the parents of a
commit, but there may be times where this is useful (it could save the server extra
work).
- Start from a specific commit. If uploadRefs gets interrupted it would save a lot
of time if we could pass a certain commit to resume from.
*/
export async function uploadRefs(id: string, repoUrl: string): Promise<void> {
pxt.log(`uploading refs starting from ${id} in ${repoUrl} to ${pxt.Cloud.apiRoot}`);
let gitCatFile: child_process.ChildProcess
let gitCatFileBuf = new U.PromiseBuffer<Buffer>()
let apiLockAsync = new U.PromiseQueue()
let gitCache = new Cache<GitObject>()
let lastUsage = 0
let repoPath = ''
startGitCatFile()
let visited: SMap<boolean> = {};
let toCheck: string[] = [];
await processCommit(id);
await uploadMissingObjects(undefined, true);
await refreshRefs(id, repoUrl);
killGitCatFile();
process.exit(0);
async function processCommit(id: string, uploadParents = false) {
if (visited[id]) return;
visited[id] = true;
await uploadMissingObjects(id);
//console.log('commit: ' + id);
let obj = await getGitObjectAsync(id);
if (obj.type != "commit")
throw new Error("bad type")
if (uploadParents && obj.commit.parents) {
// Iterate through every parent and parse the commit.
for (let parent of obj.commit.parents) {
await processCommit(parent);
}
}
// Process every tree
await processTreeEntry('000', obj.commit.tree);
}
async function processTree(entries: TreeEntry[]) {
for (let entry of entries) {
//console.log(entry.name, entry.sha);
await processTreeEntry(entry.mode, entry.sha);
}
}
async function processTreeEntry(mode: string, id: string) {
if (visited[id]) return;
visited[id] = true;
await uploadMissingObjects(id);
if (mode.indexOf('1') != 0) {
let obj = await getGitObjectAsync(id);
if (obj.type == 'tree') {
//console.log('tree:' + obj.id);
await processTree(obj.tree);
} else {
throw new Error("bad entry type: " + obj.type)
}
}
}
function maybeGcGitCatFile() {
if (!gitCatFile) return
let d = Date.now() - lastUsage
if (d < 3000) return
//console.log("[gc] git cat-file")
gitCatFile.stdin.end()
gitCatFile = null
gitCatFileBuf.drain()
}
function startGitCatFile() {
if (!lastUsage) {
setInterval(maybeGcGitCatFile, 1000)
}
lastUsage = Date.now()
if (!gitCatFile) {
//console.log("[run] git cat-file --batch")
gitCatFile = child_process.spawn("git", ["cat-file", "--batch"], {
cwd: repoPath,
env: process.env,
stdio: "pipe",
shell: false
})
gitCatFile.stderr.setEncoding("utf8")
gitCatFile.stderr.on('data', (msg: string) => {
console.error("[git cat-file error] " + msg)
})
gitCatFile.stdout.on('data', (buf: Buffer) => gitCatFileBuf.push(buf))
}
}
function killGitCatFile() {
gitCatFile.kill();
}
async function uploadMissingObjects(id: string, force?: boolean) {
if (id) toCheck.push(id);
if (toCheck.length > 50 || force) {
let hashes = toCheck;
toCheck = [];
// Check with cloud
console.log(`checking hashes with cloud`);
let response = await pxt.Cloud.privateRequestAsync({
url: 'upload/status',
data: {
hashes: hashes
}
});
let missingHashes = response.json.missing;
for (let missing of missingHashes) {
let obj = await getGitObjectAsync(missing);
// Upload data to cloud
console.log(`uploading raw ${missing} with type ${obj.type} to cloud`);
await pxt.Cloud.privateRequestAsync({
url: `upload/raw`,
data: {
type: obj.type,
content: obj.data.toString('base64'),
encoding: 'base64',
hash: missing
}
});
}
}
}
async function refreshRefs(id: string, repoUrl: string) {
console.log("Updating refs");
const data = {
HEAD: id,
repoUrl: repoUrl
}
await pxt.Cloud.privateRequestAsync({
url: `upload/rawrefs`,
data: data
});
}
function getGitObjectAsync(id: string) {
if (!id || /[\r\n]/.test(id))
throw new Error("bad id: " + id)
let cached = gitCache.get(id)
if (cached)
return Promise.resolve(cached)
return apiLockAsync.enqueue("cat-file", () => {
// check again, maybe the object has been cached while we were waiting
cached = gitCache.get(id)
if (cached)
return Promise.resolve(cached)
//console.log("cat: " + id)
startGitCatFile()
gitCatFile.stdin.write(id + "\n")
let sizeLeft = 0
let bufs: Buffer[] = []
let res: GitObject = {
id: id,
type: "",
memsize: 64,
data: null
}
let typeBuf: Buffer = null
let loop = (): Promise<GitObject> =>
gitCatFileBuf.shiftAsync()
.then(buf => {
startGitCatFile() // make sure the usage counter is updated
if (!res.type) {
//console.log(`cat-file ${id} -> ${buf.length} bytes; ${buf[0]} ${buf[1]}`)
if (typeBuf) {
buf = Buffer.concat([typeBuf, buf])
typeBuf = null
} else {
while (buf[0] == 10)
buf = buf.slice(1)
}
let end = buf.indexOf(10)
//console.log(`len-${buf.length} pos=${end}`)
if (end < 0) {
if (buf.length == 0) {
// skip it
} else {
typeBuf = buf
}
//console.info(`retrying read; sz=${buf.length}`)
return loop()
}
let line = buf
if (end >= 0) {
line = buf.slice(0, end)
buf = buf.slice(end + 1)
} else {
throw new Error("bad cat-file respose: " + buf.toString("utf8").slice(0, 100))
}
let lineS = line.toString("utf8")
if (/ missing/.test(lineS)) {
throw new Error("file missing")
}
let m = /^([0-9a-f]{40}) (\S+) (\d+)/.exec(lineS)
if (!m)
throw new Error("invalid cat-file response: "
+ lineS + " <nl> " + buf.toString("utf8"))
res.id = m[1]
res.type = m[2]
sizeLeft = parseInt(m[3])
res.memsize += sizeLeft // approximate
}
if (buf.length > sizeLeft) {
buf = buf.slice(0, sizeLeft)
}
bufs.push(buf)
sizeLeft -= buf.length
if (sizeLeft <= 0) {
res.data = Buffer.concat(bufs)
return res
} else {
return loop()
}
})
return loop().then(obj => {
//console.log(`[cat-file] ${id} -> ${obj.id} ${obj.type} ${obj.data.length}`)
if (obj.type == "tree") {
obj.tree = parseTree(obj.data)
} else if (obj.type == "commit") {
obj.commit = parseCommit(obj.data)
}
// check if this is an object in a specific revision, not say on 'master'
// and if it's small enough to warant caching
if (/^[0-9a-f]{40}/.test(id)) {
gitCache.set(id, obj, obj.memsize)
}
return obj
})
})
}
}
export interface GitObject {
id: string;
type: string;
memsize: number;
data: Buffer;
tree?: TreeEntry[];
commit?: Commit;
}
export interface Commit {
tree: string;
parents: string[];
author: string;
date: number;
msg: string;
}
export interface TreeEntry {
mode: string;
name: string;
sha: string;
}
export type SMap<T> = { [s: string]: T };
interface QEntry {
run: () => Promise<any>;
resolve: (v: any) => void;
reject: (err: any) => void;
}
const maxCacheSize = 32 * 1024 * 1024
const maxCacheEltSize = 256 * 1024
export class Cache<T> {
cache: SMap<T> = {}
size = 0
get(key: string) {
if (!key) return null
if (this.cache.hasOwnProperty(key))
return this.cache[key]
return null
}
set(key: string, v: T, sz: number) {
if (!key) return
delete this.cache[key]
if (!v || sz > maxCacheEltSize) return
if (this.size + sz > maxCacheSize) {
this.flush()
}
this.size += sz
this.cache[key] = v
}
flush() {
this.size = 0
this.cache = {}
}
}
export function splitName(fullname: string) {
let m = /(.*)\/([^\/]+)/.exec(fullname)
let parent: string = null
let name = ""
if (!m) {
if (fullname == "/") { }
else if (fullname.indexOf("/") == -1) {
parent = "/"
name = fullname
} else {
throw new Error("bad name")
}
} else {
parent = m[1] || "/"
name = m[2]
}
return { parent, name }
}
function parseTree(buf: Buffer) {
let entries: TreeEntry[] = []
let ptr = 0
while (ptr < buf.length) {
let start = ptr
while (48 <= buf[ptr] && buf[ptr] <= 55)
ptr++
if (buf[ptr] != 32)
throw new Error("bad tree format")
let mode = buf.slice(start, ptr).toString("utf8")
ptr++
start = ptr
while (buf[ptr])
ptr++
if (buf[ptr] != 0)
throw new Error("bad tree format 2")
let name = buf.slice(start, ptr).toString("utf8")
ptr++
let sha = buf.slice(ptr, ptr + 20).toString("hex")
ptr += 20
if (ptr > buf.length)
throw new Error("bad tree format 3")
entries.push({ mode, name, sha })
}
return entries
}
function parseCommit(buf: Buffer): Commit {
let cmt = buf.toString("utf8")
let mtree = /^tree (\S+)/m.exec(cmt)
let mpar = /^parent (.+)/m.exec(cmt)
let mauthor = /^author (.+) (\d+) ([+\-]\d{4})$/m.exec(cmt)
let midx = cmt.indexOf("\n\n")
return {
tree: mtree[1],
parents: mpar ? mpar[1].split(/\s+/) : undefined,
author: mauthor[1],
date: parseInt(mauthor[2]),
msg: cmt.slice(midx + 2)
}
} | the_stack |
import { parseStringsArray, getByProp, readUInt8, readInt16, readUInt32, readFloat64, readInt8, getOperatantByBuffer, getOperantName } from '../utils'
import { Scope } from '../scope'
export enum I {
VAR, CLS,
MOV, ADD, SUB, MUL, DIV, MOD,
EXP, INC, DEC,
LT, GT, EQ, LE, GE, NE, WEQ, WNE,
LG_AND, LG_OR,
AND, OR, XOR, SHL, SHR, ZSHR,
JMP, JE, JNE, JG, JL, JIF, JF,
JGE, JLE, PUSH, POP, CALL, PRINT,
RET, PAUSE, EXIT,
CALL_CTX, CALL_VAR, CALL_REG, MOV_CTX, MOV_PROP,
SET_CTX, // SET_CTX "name" R1
NEW_OBJ, NEW_ARR, NEW_REG, SET_KEY,
FUNC, ALLOC,
/* UnaryExpression */
PLUS, // PLUS %r0 +
MINUS, // MINUS %r0 -
NOT, // NOT %r0 ~
VOID, // VOID %r0 void
DEL, // DEL %r0 %r1 delete
NEG, // NEG %r0 !
TYPE_OF,
IN,
INST_OF, // instanceof
MOV_THIS, // moving this to resgister
// try catch
TRY, TRY_END, THROW, GET_ERR,
// arguments
MOV_ARGS,
FORIN, FORIN_END, BREAK_FORIN, CONT_FORIN,
BVAR, BLOCK, END_BLOCK, CLR_BLOCK,
}
const NO_RETURN_SYMBOL = Symbol()
class VMRunTimeError extends Error {
constructor(public error: any) {
super(error)
}
}
interface ICallingFunctionInfo {
isInitClosure: boolean,
closureScope: Scope,
variables: Scope | null,
returnValue?: any,
args: any[],
}
export const enum IOperatantType {
REGISTER = 0 << 4,
CLOSURE_REGISTER = 1 << 4,
GLOBAL = 2 << 4,
NUMBER = 3 << 4,
// tslint:disable-next-line: no-identical-expressions
FUNCTION_INDEX = 4 << 4,
STRING = 5 << 4,
ARG_COUNT = 6 << 4,
RETURN_VALUE = 7 << 4,
ADDRESS = 8 << 4,
BOOLEAN = 9 << 4,
NULL = 10 << 4,
UNDEFINED = 11 << 4,
VAR_SYMBOL = 13 << 4,
}
export interface IOperant {
type: IOperatantType,
value: any,
raw?: any,
index?: any,
}
export type IClosureTable = {
[x in number]: number
}
// tslint:disable-next-line: max-classes-per-file
export class VirtualMachine {
/** 指令索引 */
public ip: number = 0
/** 当前函数帧基索引 */
public fp: number = 0
/** 操作的栈顶 */
public sp: number = -1
/** 寄存器 */
public RET: any // 函数返回寄存器
public REG: any // 通用寄存器
/** 函数操作栈 */
public stack: any[] = []
/** 闭包变量存储 */
// public closureScope: Scope
/** 闭包映射表 */
public callingFunctionInfo: ICallingFunctionInfo = {
isInitClosure: true,
closureScope: new Scope(),
variables: new Scope(),
args: [],
}
public callingFunctionInfos: ICallingFunctionInfo[] = []
/** this 链 */
public currentThis: any
public allThis: any[] = []
public isRunning: boolean = false
public mainFunction: CallableFunction
public error: any
constructor (
public codes: Uint8Array,
public functionsTable: FuncInfoMeta[],
public entryIndx: number,
public stringsTable: string[],
public globalSize: number,
public ctx: any,
) {
const mainClosureScope = new Scope()
mainClosureScope.isRestoreWhenChange = false
this.mainFunction = this.parseToJsFunc(functionsTable[this.entryIndx], mainClosureScope)
this.init()
}
public init(): void {
const { globalSize, mainFunction } = this
const { meta } = this.getMetaFromFunc(mainFunction)
const [ip, numArgs, localSize] = meta
this.stack.splice(0)
const globalIndex = globalSize + 1
this.fp = globalIndex // fp 指向 old fp 位置,兼容普通函数
this.stack[this.fp] =-1
this.sp = this.fp
this.stack.length = this.sp + 1
this.callingFunctionInfos = []
this.allThis = []
}
public reset(): void {
this.init()
this.error = null
}
// tslint:disable-next-line: no-big-function
public run(): void {
this.callFunction(this.mainFunction, void 0, '', 0, false)
this.isRunning = true
while (this.isRunning) {
this.fetchAndExecute()
}
}
public setReg(dst: IOperant, src: { value: any }): void {
const callingFunctionInfo = this.callingFunctionInfo
if (dst.type === IOperatantType.VAR_SYMBOL) {
this.checkVariableScopeAndNew()
callingFunctionInfo.variables!.set(dst.index, src.value)
} else if (dst.type === IOperatantType.CLOSURE_REGISTER) {
this.checkClosureAndFork()
this.callingFunctionInfo.closureScope.set(dst.index, src.value)
} else if (dst.type === IOperatantType.REGISTER || dst.type === IOperatantType.RETURN_VALUE) {
if (dst.type === IOperatantType.RETURN_VALUE) {
this.callingFunctionInfo.returnValue = src.value
}
if (dst.raw <= -4) {
this.callingFunctionInfo.args[-4 - dst.raw] = src.value
} else {
this.stack[dst.index] = src.value
}
} else {
console.error(dst)
throw new Error(`Cannot process register type ${dst.type}`)
}
}
public newReg(o: IOperant): any {
const callingFunctionInfo = this.callingFunctionInfo
if (o.type === IOperatantType.VAR_SYMBOL) {
this.checkVariableScopeAndNew()
this.callingFunctionInfo.variables!.new(o.index)
} else if (o.type === IOperatantType.CLOSURE_REGISTER) {
this.checkClosureAndFork()
this.callingFunctionInfo.closureScope.new(o.index)
} else {
console.error(o)
throw new Error(`Cannot process register type ${o.type}`)
}
}
public getReg(o: IOperant): any {
if (o.type === IOperatantType.VAR_SYMBOL) {
if (!this.callingFunctionInfo.variables) {
throw new Error('variable is not declared.')
}
return this.callingFunctionInfo.variables.get(o.index)
} else if (o.type === IOperatantType.CLOSURE_REGISTER) {
return this.callingFunctionInfo.closureScope.get(o.index)
} else if (o.type === IOperatantType.REGISTER || o.type === IOperatantType.RETURN_VALUE) {
return this.stack[o.index]
} else {
throw new Error(`Cannot process register type ${o.type}`)
}
}
// tslint:disable-next-line: no-big-function cognitive-complexity
public fetchAndExecute(): [I, boolean] {
if (!this.isRunning) {
throw new VMRunTimeError('try to run again...')
}
let op = this.nextOperator()
// 用来判断是否嵌套调用 vm 函数
let isCallVMFunction = false
// tslint:disable-next-line: max-switch-cases
switch (op) {
case I.VAR:
case I.CLS: {
const o = this.nextOperant()
this.newReg(o)
break
}
case I.PUSH: {
const value = this.nextOperant().value
this.push(value)
break
}
case I.EXIT: {
this.isRunning = false
break
}
case I.RET: {
this.returnCurrentFunction()
break
}
case I.PRINT: {
const val = this.nextOperant()
console.log(val.value)
break
}
case I.MOV: {
const dst = this.nextOperant()
const src = this.nextOperant()
this.setReg(dst, src)
break
}
case I.JMP: {
const address = this.nextOperant()
this.ip = address.value
break
}
case I.JE: {
this.jumpWithCondidtion((a: any, b: any): boolean => a === b)
break
}
case I.JNE: {
this.jumpWithCondidtion((a: any, b: any): boolean => a !== b)
break
}
case I.JG: {
this.jumpWithCondidtion((a: any, b: any): boolean => a > b)
break
}
case I.JL: {
this.jumpWithCondidtion((a: any, b: any): boolean => a < b)
break
}
case I.JGE: {
this.jumpWithCondidtion((a: any, b: any): boolean => a >= b)
break
}
case I.JLE: {
this.jumpWithCondidtion((a: any, b: any): boolean => a <= b)
break
}
case I.JIF: {
const cond = this.nextOperant()
const address = this.nextOperant()
if (cond.value) {
this.ip = address.value
}
break
}
case I.JF: {
const cond = this.nextOperant()
const address = this.nextOperant()
if (!cond.value) {
this.ip = address.value
}
break
}
case I.CALL_CTX:
case I.CALL_VAR: {
let o
if (op === I.CALL_CTX) {
o = this.ctx
} else {
o = this.nextOperant().value
}
const funcName = this.nextOperant().value
const numArgs = this.nextOperant().value
const isNewExpression = this.nextOperant().value
isCallVMFunction = this.callFunction(void 0, o, funcName, numArgs, isNewExpression)
break
}
case I.CALL_REG: {
const o = this.nextOperant()
const f = o.value
const numArgs = this.nextOperant().value
const isNewExpression = this.nextOperant().value
isCallVMFunction = this.callFunction(f, void 0, '', numArgs, isNewExpression)
break
}
case I.MOV_CTX: {
const dst = this.nextOperant()
const propKey = this.nextOperant()
const src = this.ctx[propKey.value] // getByProp(this.ctx, propKey.value)
this.setReg(dst, { value: src })
break
}
case I.SET_CTX: {
const propKey = this.nextOperant()
const val = this.nextOperant()
this.ctx[propKey.value] = val.value
break
}
case I.NEW_OBJ: {
const dst = this.nextOperant()
const o = {}
this.setReg(dst, { value: o })
break
}
case I.NEW_REG: {
const dst = this.nextOperant()
const pattern = this.nextOperant()
const flags = this.nextOperant()
try {
this.setReg(dst, { value: new RegExp(pattern.value, flags.value) })
} catch(e) {
throw new VMRunTimeError(e)
}
break
}
case I.NEW_ARR: {
const dst = this.nextOperant()
const o: any[] = []
this.setReg(dst, { value: o })
break
}
case I.SET_KEY: {
const o = this.nextOperant().value
const key = this.nextOperant().value
const value = this.nextOperant().value
// console.log(o, key, value)
o[key] = value
break
}
/** 这是定义一个函数 */
case I.FUNC: {
const dst = this.nextOperant()
const funcOperant = this.nextOperant()
const funcInfoMeta = funcOperant.value
const func = this.parseToJsFunc(funcInfoMeta, this.callingFunctionInfo.closureScope.fork())
this.setReg(dst, { value: func })
break
}
case I.MOV_PROP: {
const dst = this.nextOperant()
const o = this.nextOperant()
const k = this.nextOperant()
const v = o.value[k.value] // getByProp(o.value, k.value)
this.setReg(dst, { value: v })
break
}
case I.LT: {
this.binaryExpression((a, b): any => a < b)
break
}
case I.GT: {
this.binaryExpression((a, b): any => a > b)
break
}
case I.EQ: {
this.binaryExpression((a, b): any => a === b)
break
}
case I.NE: {
this.binaryExpression((a, b): any => a !== b)
break
}
case I.WEQ: {
// tslint:disable-next-line: triple-equals
this.binaryExpression((a, b): any => a == b)
break
}
case I.WNE: {
// tslint:disable-next-line: triple-equals
this.binaryExpression((a, b): any => a != b)
break
}
case I.LE: {
this.binaryExpression((a, b): any => a <= b)
break
}
case I.GE: {
this.binaryExpression((a, b): any => a >= b)
break
}
case I.ADD: {
this.binaryExpression((a, b): any => a + b)
break
}
case I.SUB: {
this.binaryExpression((a, b): any => a - b)
break
}
case I.MUL: {
this.binaryExpression((a, b): any => a * b)
break
}
case I.DIV: {
this.binaryExpression((a, b): any => a / b)
break
}
case I.MOD: {
this.binaryExpression((a, b): any => a % b)
break
}
case I.AND: {
// tslint:disable-next-line: no-bitwise
this.binaryExpression((a, b): any => a & b)
break
}
case I.OR: {
// tslint:disable-next-line: no-bitwise
this.binaryExpression((a, b): any => a | b)
break
}
case I.XOR: {
// tslint:disable-next-line: no-bitwise
this.binaryExpression((a, b): any => a ^ b)
break
}
case I.SHL: {
// tslint:disable-next-line: no-bitwise
this.binaryExpression((a, b): any => a << b)
break
}
case I.SHR: {
// tslint:disable-next-line: no-bitwise
this.binaryExpression((a, b): any => a >> b)
break
}
case I.ZSHR: {
// tslint:disable-next-line: no-bitwise
this.binaryExpression((a, b): any => a >>> b)
break
}
case I.LG_AND: {
this.binaryExpression((a, b): any => a && b)
break
}
case I.LG_OR: {
this.binaryExpression((a, b): any => a || b)
break
}
case I.INST_OF: {
this.binaryExpression((a, b): any => {
return a instanceof b
})
break
}
case I.IN: {
this.binaryExpression((a, b): any => {
return a in b
})
break
}
case I.ALLOC: {
const dst = this.nextOperant()
// this.makeClosureIndex()
this.getReg(dst)
break
}
case I.PLUS: {
this.uniaryExpression((val: any): any => +val)
break
}
case I.MINUS: {
this.uniaryExpression((val: any): any => -val)
break
}
case I.VOID: {
// tslint:disable-next-line: no-unused-expression
this.uniaryExpression((val: any): any => void val)
break
}
case I.NOT: {
// tslint:disable-next-line: no-bitwise
this.uniaryExpression((val: any): any => ~val)
break
}
case I.NEG: {
// tslint:disable-next-line: no-bitwise
this.uniaryExpression((val: any): any => !val)
break
}
case I.TYPE_OF: {
this.uniaryExpression((val: any): any => typeof val)
break
}
case I.DEL: {
const o1 = this.nextOperant().value
const o2 = this.nextOperant().value
delete o1[o2]
break
}
case I.MOV_THIS: {
this.setReg(this.nextOperant(), { value: this.currentThis })
break
}
case I.TRY: {
const catchAddress = this.nextOperant()
const endAddress = this.nextOperant()
let callCount = 1
const currentFunctionInfo = this.callingFunctionInfo
while (callCount > 0 && this.isRunning) {
try {
const [o, isCallVMFunc] = this.fetchAndExecute()
op = o
if (isCallVMFunc) {
callCount++
}
if (o === I.RET) {
callCount--
if (callCount === 0) {
break
}
}
if (o === I.TRY_END && callCount === 1) {
this.ip = endAddress.value
break
}
} catch(e) {
if (e instanceof VMRunTimeError) {
throw e
}
this.popToFunction(currentFunctionInfo)
this.error = e
this.ip = catchAddress.value
break
}
}
break
}
case I.THROW: {
const err = this.nextOperant()
throw err.value
// throw new VMRunTimeError(err)
break
}
case I.TRY_END: {
// throw new VMRunTimeError('Should not has `TRY_END` here.')
break
}
case I.GET_ERR: {
const o = this.nextOperant()
this.setReg(o, { value: this.error })
break
}
case I.MOV_ARGS: {
const dst = this.nextOperant()
this.setReg(dst, { value: this.stack[this.fp - 3] })
break
}
case I.FORIN: {
const dst = this.nextOperant()
const target = this.nextOperant()
const startAddress = this.nextOperant()
const endAddress = this.nextOperant()
forIn:
// tslint:disable-next-line: forin
for (const i in target.value) {
this.setReg(dst, { value: i })
while (true) {
const o = this.fetchAndExecute()[0]
if (o === I.BREAK_FORIN) {
break forIn
}
if (o === I.FORIN_END || o === I.CONT_FORIN) {
this.ip = startAddress.value
continue forIn
}
}
}
this.ip = endAddress.value
break
}
case I.FORIN_END:
case I.BREAK_FORIN:
case I.CONT_FORIN: {
break
}
case I.BLOCK: {
const o= this.nextOperant()
this.checkClosureAndFork()
this.checkVariableScopeAndNew()
this.callingFunctionInfo.closureScope.front(o.value)
this.callingFunctionInfo.variables!.front(o.value)
break
}
case I.CLR_BLOCK:
case I.END_BLOCK: {
const o = this.nextOperant()
this.callingFunctionInfo.closureScope.back(o.value)
this.callingFunctionInfo.variables!.back(o.value)
break
}
default:
throw new VMRunTimeError("Unknow command " + op + " " + I[op],)
}
return [op, isCallVMFunction]
}
public checkClosureAndFork(): void {
const callingFunctionInfo = this.callingFunctionInfo
if (!callingFunctionInfo.isInitClosure) {
callingFunctionInfo.closureScope = this.callingFunctionInfo.closureScope.fork()
callingFunctionInfo.isInitClosure = true
}
}
public checkVariableScopeAndNew(): void {
if (!this.callingFunctionInfo.variables) {
this.callingFunctionInfo.variables = new Scope()
}
}
public returnCurrentFunction(): void {
const stack = this.stack
const fp = this.fp
this.fp = stack[fp]
this.ip = stack[fp - 1]
// 减去参数数量,减去三个 fp ip numArgs args
this.sp = fp - stack[fp - 2] - 4
// 清空上一帧
this.stack.splice(this.sp + 1)
if (this.callingFunctionInfo.returnValue === NO_RETURN_SYMBOL) {
this.stack[0] = undefined
}
this.allThis.pop()
this.currentThis = this.allThis[this.allThis.length - 1]
this.callingFunctionInfos.pop()
this.callingFunctionInfo = this.callingFunctionInfos[this.callingFunctionInfos.length - 1]
}
public push(val: any): void {
this.stack[++this.sp] = val
}
public nextOperator(): I {
return readUInt8(this.codes, this.ip, ++this.ip)
}
public nextOperant(): IOperant {
const [operantType, value, byteLength] = getOperatantByBuffer(this.codes, this.ip++)
this.ip = this.ip + byteLength
if (operantType === IOperatantType.REGISTER) {
}
return {
type: operantType,
value: this.parseValue(operantType, value),
raw: value,
index: operantType === IOperatantType.REGISTER ? (this.fp + value) : value,
}
}
public parseValue(valueType: IOperatantType, value: any): any {
switch (valueType) {
case IOperatantType.CLOSURE_REGISTER:
return this.callingFunctionInfo.closureScope.get(value) // [this.callingFunctionInfo.closureTable[value]]
case IOperatantType.REGISTER:
// 参数数量控制
if (value <= -4) {
if ((-4 - value) < this.callingFunctionInfo.args.length) {
return this.callingFunctionInfo.args[-4 - value]
} else {
return void 0
}
}
return this.stack[this.fp + value]
case IOperatantType.ARG_COUNT:
case IOperatantType.NUMBER:
case IOperatantType.ADDRESS:
return value
case IOperatantType.GLOBAL:
return this.stack[value]
case IOperatantType.STRING:
return this.stringsTable[value]
case IOperatantType.FUNCTION_INDEX:
return this.functionsTable[value]
case IOperatantType.RETURN_VALUE:
return this.stack[0]
case IOperatantType.BOOLEAN:
return !!value
case IOperatantType.NULL:
return null
case IOperatantType.UNDEFINED:
return void 0
case IOperatantType.VAR_SYMBOL:
if (!this.callingFunctionInfo.variables) {
return undefined
}
return this.callingFunctionInfo.variables.get(value)
default:
throw new VMRunTimeError("Unknown operant " + valueType)
}
}
public jumpWithCondidtion(cond: (a: any, b: any) => boolean): void {
const op1 = this.nextOperant()
const op2 = this.nextOperant()
const address = this.nextOperant()
if (cond(op1.value, op2.value)) {
this.ip = address.value
}
}
public uniaryExpression(exp: (a: any) => any): void {
const o = this.nextOperant()
const ret = exp(o.value)
this.setReg(o, { value: ret })
}
public binaryExpression(exp: (a: any, b: any) => any): void {
const o1 = this.nextOperant()
const o2 = this.nextOperant()
const ret = exp(o1.value, o2.value)
this.setReg(o1, { value: ret })
}
// tslint:disable-next-line: cognitive-complexity
public callFunction(
func: Callable | undefined,
o: any,
funcName: string,
numArgs: number,
isNewExpression: boolean,
): boolean {
const stack = this.stack
const f = func || o[funcName]
let isCallVMFunction = false
const isNullOrUndefined = o === void 0 || o === null || o === this.ctx
if ((f instanceof Callable) && !isNewExpression) {
// console.log('---> THE IP IS -->', numArgs)
const arg = new NumArgs(numArgs)
if (!isNullOrUndefined) {
if (typeof o[funcName] === 'function') {
o[funcName](arg)
} else {
throw new VMRunTimeError(`The function ${funcName} is not a function`)
}
} else {
f(arg)
}
isCallVMFunction = true
} else {
const args = []
for (let i = 0; i < numArgs; i++) {
args.unshift(stack[this.sp--])
}
if (!isNullOrUndefined) {
stack[0] = isNewExpression
? new o[funcName](...args)
: o[funcName](...args)
} else {
stack[0] = isNewExpression
? new f(...args)
: f(...args)
}
this.stack.splice(this.sp + 1)
}
return isCallVMFunction
}
public popToFunction(targetFunctionInfo: ICallingFunctionInfo): void {
while (this.callingFunctionInfos[this.callingFunctionInfos.length - 1] !== targetFunctionInfo) {
this.returnCurrentFunction()
}
}
// tslint:disable-next-line: cognitive-complexity
public parseToJsFunc (meta: FuncInfoMeta, closureScope: Scope): any {
const vm = this
const func = function (this: any, ...args: any[]): any {
const [ip, _, localSize] = meta
vm.isRunning = true
const n = args[0]
const isCalledFromJs = !(n instanceof NumArgs)
let numArgs = 0
let allArgs = []
if (isCalledFromJs) {
args.forEach((arg: any): void => vm.push(arg))
numArgs = args.length
allArgs = [...args]
} else {
numArgs = n.numArgs
const end = vm.sp + 1
allArgs = vm.stack.slice(end - numArgs, end) // []
}
const currentCallingFunctionInfo: ICallingFunctionInfo = vm.callingFunctionInfo = {
isInitClosure: false,
closureScope,
variables: null,
args: allArgs,
returnValue: NO_RETURN_SYMBOL,
}
vm.callingFunctionInfos.push(vm.callingFunctionInfo)
if (vm.allThis.length === 0) {
vm.currentThis = vm.ctx
} else {
vm.currentThis = this || vm.ctx
}
vm.allThis.push(vm.currentThis)
const stack = vm.stack
if (isCalledFromJs) {
stack[0] = undefined
}
// console.log('call', funcInfo, numArgs)
// | R3 |
// | R2 |
// | R1 |
// | R0 |
// sp -> | fp | # for restoring old fp
// | ip | # for restoring old ip
// | numArgs | # for restoring old sp: old sp = current sp - numArgs - 3
// | arguments | # for store arguments for js `arguments` keyword
// | arg1 |
// | arg2 |
// | arg3 |
// old sp -> | .... |
stack[++vm.sp] = allArgs
stack[++vm.sp] = numArgs
stack[++vm.sp] = vm.ip
stack[++vm.sp] = vm.fp
// set to new ip and fp
vm.ip = ip
vm.fp = vm.sp
vm.sp += localSize
if (isCalledFromJs) {
/** 嵌套 vm 函数调 vm 函数,需要知道嵌套多少层,等到当前层完结再返回 */
let callCount = 1
while (callCount > 0 && vm.isRunning) {
const [op, isCallVMFunction] = vm.fetchAndExecute()
if (isCallVMFunction) {
callCount++
} else if (op === I.RET) {
callCount--
}
}
if (currentCallingFunctionInfo.returnValue !== NO_RETURN_SYMBOL) {
return currentCallingFunctionInfo.returnValue
}
}
}
Object.setPrototypeOf(func, Callable.prototype)
try {
Object.defineProperty(func, 'length', { value: meta[1] })
} catch(e) {}
vm.setMetaToFunc(func, meta)
return func
}
private setMetaToFunc(func: any, meta: FuncInfoMeta): void {
Object.defineProperty(func, '__vm_func_info__', {
enumerable: false,
value: { meta },
writable: false,
})
}
private getMetaFromFunc(func: any): { meta: FuncInfoMeta, closureTable: any } {
return func.__vm_func_info__
}
}
/**
* Header:
*
* mainFunctionIndex: 1
* funcionTableBasicIndex: 1
* stringTableBasicIndex: 1
* globalsSize: 2
*/
const createVMFromArrayBuffer = (buffer: ArrayBuffer, ctx: any = {}): VirtualMachine => {
const mainFunctionIndex = readUInt32(buffer, 0, 4)
const funcionTableBasicIndex = readUInt32(buffer, 4, 8)
const stringTableBasicIndex = readUInt32(buffer, 8, 12)
const globalsSize = readUInt32(buffer, 12, 16)
// console.log(
// ' =========================== Start Running =======================\n',
// 'main function index', mainFunctionIndex, '\n',
// 'function table basic index', funcionTableBasicIndex, '\n',
// 'string table basic index', stringTableBasicIndex, '\n',
// 'globals szie ', globalsSize, '\n',
// '=================================================================\n',
// )
const stringsTable: string[] = parseStringsArray(buffer.slice(stringTableBasicIndex))
const codesBuf = new Uint8Array(buffer.slice(4 * 4, funcionTableBasicIndex))
const funcsBuf = buffer.slice(funcionTableBasicIndex, stringTableBasicIndex)
const funcsTable: FuncInfoMeta[] = parseFunctionTable(funcsBuf)
// console.log('string table', stringsTable)
// console.log('function table', funcsTable)
// console.log(mainFunctionIndex, 'function basic index', funcionTableBasicIndex)
// console.log('total codes bytes length -->', codesBuf.byteLength)
// console.log('main start index', funcsTable[mainFunctionIndex][0], stringTableBasicIndex)
return new VirtualMachine(codesBuf, funcsTable, mainFunctionIndex, stringsTable, globalsSize, ctx)
}
type FuncInfoMeta = [number, number, number] // address, numArgs, numLocals
const parseFunctionTable = (buffer: ArrayBuffer): FuncInfoMeta[] => {
const funcs: FuncInfoMeta[] = []
let i = 0
while (i < buffer.byteLength) {
const ipEnd = i + 4
const ip = readUInt32(buffer, i, ipEnd)
const numArgsAndLocal = new Uint16Array(buffer.slice(ipEnd, ipEnd + 2 * 2))
funcs.push([ip, numArgsAndLocal[0], numArgsAndLocal[1]])
i += 8
}
return funcs
}
export { createVMFromArrayBuffer }
// https://hackernoon.com/creating-callable-objects-in-javascript-d21l3te1
// tslint:disable-next-line: max-classes-per-file
class Callable extends Function {
constructor() {
super()
}
}
export { Callable }
// tslint:disable-next-line: max-classes-per-file
class NumArgs {
constructor(public numArgs: number) {
}
// tslint:disable-next-line: max-file-line-count
}
if (typeof window !== 'undefined') {
(window as any).VirtualMachine = VirtualMachine;
(window as any).createVMFromArrayBuffer = createVMFromArrayBuffer
} | the_stack |
import { vtkObject } from "../../../interfaces" ;
import { Vector3 } from "../../../types";
/**
*
*/
export interface IPlaneInitialValues {
normal?: Vector3;
origin?: Vector3;
}
interface IIntersectWithLine {
intersection: boolean;
betweenPoints: boolean;
t: number;
x: Vector3;
}
export interface vtkPlane extends vtkObject {
/**
* Get the distance of a point x to a plane defined by n (x-p0) = 0.
* The normal n must be magnitude = 1.
* @param {Vector3} x The point coordiante.
*/
distanceToPlane(x: Vector3): number;
/**
* Get plane normal.
* Plane is defined by point and normal.
*/
getNormal(): Vector3;
/**
* Get plane normal.
* Plane is defined by point and normal.
*/
getNormalByReference(): Vector3;
/**
* Get the origin of the plane
*/
getOrigin(): Vector3;
/**
* Get the origin of the plane
*/
getOriginByReference(): Vector3;
/**
*
* @param {Vector3} x The point coordinate.
* @param {Vector3} xproj The projection point's coordinate.
*/
projectPoint(x: Vector3, xproj: Vector3): void;
/**
* Project a vector v onto plane. The projected vector is returned in vproj.
* @param {Vector3} v The vector coordinate.
* @param {Vector3} vproj The projection vector's coordinate..
*/
projectVector(v: Vector3, vproj: Vector3): void;
/**
* Translate the plane in the direction of the normal by the distance
* specified. Negative values move the plane in the opposite direction.
* @param {Number} distance
*/
push(distance: number): void;
/**
*
* @param {Vector3} x The point coordinate.
* @param {Vector3} xproj The projection point's coordinate.
*/
generalizedProjectPoint(x: Vector3, xproj: Vector3): void;
/**
* Evaluate plane equation for point x.
*
* Accepts both an array point representation and individual xyz arguments.
*
* ```js
* plane.evaluateFunction([0.0, 0.0, 0.0]);
* plane.evaluateFunction(0.0, 0.0, 0.0);
* ```
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
evaluateFunction(x: number, y: number, z: number): number;
/**
* Evaluate plane equation for point x.
*
* Accepts both an array point representation and individual xyz arguments.
*
* ```js
* plane.evaluateFunction([0.0, 0.0, 0.0]);
* plane.evaluateFunction(0.0, 0.0, 0.0);
* ```
* @param {Vector3} value
*/
evaluateFunction(value: Vector3): number;
/**
* Given the point xyz (three floating values) evaluate the equation for the
* plane gradient. Note that the normal and origin must have already been
* specified. The method returns an array of three floats.
* @param xyz
*/
evaluateGradient(xyz: any): Vector3;
/**
* Given a line defined by the two points p1,p2; and a plane defined by the
* normal n and point p0, compute an intersection. Return an object:
*
* ```js
* let obj = {intersection: ..., betweenPoints: ..., t: ..., x: ...};
* ```
*
* where:
* - **intersection** (_boolean_): indicates if the plane and line
* intersect.
* - **betweenPoints** (_boolean_): indicates if the intersection is between
* the provided points. True if (0 <= t <= 1), and false otherwise.
* - **t** (_Number_): parametric coordinate along the line.
* - **x** (_Array_): coordinates of intersection.
*
* If the plane and line are parallel, intersection is false and t is set to
* Number.MAX_VALUE.
* @param {Vector3} p1 The first point coordiante.
* @param {Vector3} p2 The second point coordiante.
*/
intersectWithLine(p1: Vector3, p2: Vector3): IIntersectWithLine;
/**
* Given a planes defined by the normals n0 & n1 and origin points p0 & p1,
* compute the line representing the plane intersection. Return an object:
*
* ```js
* let obj = {intersection: ..., error: ..., l0: ..., l1: ...};
* ```
*
* where:
*
* - **intersection** (_boolean_): indicates if the two planes intersect.
* Intersection is true if (0 <= t <= 1), and false otherwise.
* - **l0** (_Array_): coordinates of point 0 of the intersection line.
* - **l1** (_Array_): coordinates of point 1 of the intersection line.
* - **error** (_String|null_): Conditional, if the planes do not intersect,
* is it because they are coplanar (`COINCIDE`) or parallel (`DISJOINT`).
* @param {Vector3} planeOrigin
* @param {Vector3} planeNormal
*/
intersectWithPlane(planeOrigin: Vector3, planeNormal: Vector3): IIntersectWithLine;
/**
* Set the normal of the plane.
* @param {Vector3} normal The normal coordinate.
*/
setNormal(normal: Vector3): boolean;
/**
* Set the normal of the plane.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setNormal(x: number, y: number, z: number): boolean;
/**
* Set the normal object.
* @param {Vector3} normal The normal coordinate.
*/
setNormalFrom(normal: Vector3): boolean;
/**
* Set the origin of the plane.
* @param {Vector3} origin The coordinate of the origin point.
*/
setOrigin(origin: Vector3): boolean;
/**
* Set the origin of the plane.
* @param {Number} x The x coordinate of the origin point.
* @param {Number} y The y coordinate of the origin point.
* @param {Number} z The z coordinate of the origin point.
*/
setOrigin(x: number, y: number, z: number): boolean;
/**
* Set the origin of the plane.
* @param {Vector3} origin The coordinate of the origin point.
*/
setOriginFrom(origin: Vector3): boolean;
}
/**
* Method used to decorate a given object (publicAPI+model) with vtkPlane characteristics.
*
* @param publicAPI object on which methods will be bounds (public)
* @param model object on which data structure will be bounds (protected)
* @param {IPlaneInitialValues} [initialValues] (default: {})
*/
export function extend(publicAPI: object, model: object, initialValues?: IPlaneInitialValues): void;
/**
* Method used to create a new instance of vtkPlane.
* @param {IPlaneInitialValues} [initialValues] for pre-setting some of its content
*/
export function newInstance(initialValues?: IPlaneInitialValues): vtkPlane;
/**
* Quick evaluation of plane equation n(x-origin) = 0.
* @static
* @param {Vector3} normal
* @param {Vector3} origin The coordinate of the origin point.
* @param {Vector3} x
*/
export function evaluate(normal: Vector3, origin: Vector3, x: Vector3): number;
/**
* Return the distance of a point x to a plane defined by n (x-p0) = 0.
* The normal n must be magnitude = 1.
* @static
* @param {Vector3} x
* @param {Vector3} origin The coordinate of the origin point.
* @param {Vector3} normal
*/
export function distanceToPlane(x: Vector3, origin: Vector3, normal: Vector3): number;
/**
* Project a point x onto plane defined by origin and normal. The projected point
* is returned in xproj.
* !!! note
* normal assumed to have magnitude 1.
* @static
* @param {Vector3} x
* @param {Vector3} origin The coordinate of the origin point.
* @param {Vector3} normal
* @param {Vector3} xproj
*/
export function projectPoint(x: any, origin: Vector3, normal: Vector3, xproj: Vector3): void;
/**
* Project a vector v onto a plane defined by a normal. The projected vector is
* returned in vproj.
* @static
* @param {Vector3} v The vector coordinate.
* @param {Vector3} normal
* @param {Vector3} vproj The projection vector's coordinate..
*/
export function projectVector(v: Vector3, normal: Vector3, vproj: Vector3,): void;
/**
* Project a point x onto plane defined by origin and normal. The projected
point is returned in xproj.
*
* !!! note
* normal does NOT have to have magnitude 1.
* @static
* @param {Vector3} x
* @param {Vector3} origin The coordinate of the origin point.
* @param {Vector3} normal
* @param {Vector3} xproj
*/
export function generalizedProjectPoint(x: any, origin: Vector3, normal: Vector3, xproj: Vector3): void;
/**
* Given a line defined by the two points p1,p2; and a plane defined by the normal n and point p0, compute an intersection.
* Return an object:
*
* ```js
* let obj = {intersection: ..., betweenPoints: ..., t: ..., x: ...};
* ```
*
* where:
* - **intersection** (_boolean_): indicates if the plane and line intersect.
* - **betweenPoints** (_boolean_): indicates if the intersection is between the provided points. True if (0 <= t <= 1), and false otherwise.
* - **t** (_Number_): parametric coordinate along the line.
* - **x** (_Array_): coordinates of intersection.
*
* If the plane and line are parallel, intersection is false and t is set to
* Number.MAX_VALUE.
* @static
* @param {Vector3} p1
* @param {Vector3} p2
* @param {Vector3} origin The coordinate of the origin point.
* @param {Vector3} normal
*/
export function intersectWithLine(p1: Vector3, p2: Vector3, origin: Vector3, normal: Vector3): IIntersectWithLine;
/**
* Given a planes defined by the normals n0 & n1 and origin points p0 & p1,
* compute the line representing the plane intersection. Return an object:
*
* ```js
* let obj = {intersection: ..., error: ..., l0: ..., l1: ...};
* ```
*
* where:
*
* - **intersection** (_boolean_): indicates if the two planes intersect.
* Intersection is true if (0 <= t <= 1), and false otherwise.
* - **l0** (_Array_): coordinates of point 0 of the intersection line.
* - **l1** (_Array_): coordinates of point 1 of the intersection line.
* - **error** (_String|null_): Conditional, if the planes do not intersect,
* is it because they are coplanar (`COINCIDE`) or parallel (`DISJOINT`).
* @static
* @param {Vector3} plane1Origin
* @param {Vector3} plane1Normal
* @param {Vector3} plane2Origin
* @param {Vector3} plane2Normal
*/
export function intersectWithPlane(plane1Origin: Vector3, plane1Normal: Vector3, plane2Origin: Vector3, plane2Normal: Vector3): IIntersectWithLine;
/**
* Constants for the `intersectWithPlane` function.
*/
export declare const COINCIDE: string;
/**
* Constants for the `intersectWithPlane` function.
*/
export declare const DISJOINT: string;
/**
* vtkPlane provides methods for various plane computations. These include
* projecting points onto a plane, evaluating the plane equation, and returning
* plane normal.
*/
export declare const vtkPlane: {
newInstance: typeof newInstance,
extend: typeof extend,
evaluate: typeof evaluate,
distanceToPlane: typeof distanceToPlane,
projectPoint: typeof projectPoint,
projectVector: typeof projectVector,
generalizedProjectPoint: typeof generalizedProjectPoint,
intersectWithLine: typeof intersectWithLine,
intersectWithPlane: typeof intersectWithPlane,
};
export default vtkPlane; | the_stack |
namespace ts.projectSystem {
describe("project telemetry", () => {
it("does nothing for inferred project", () => {
const file = makeFile("/a.js");
const et = new TestServerEventManager([file]);
et.service.openClientFile(file.path);
et.hasZeroEvent(server.ProjectInfoTelemetryEvent);
});
it("only sends an event once", () => {
const file = makeFile("/a/a.ts");
const file2 = makeFile("/b.ts");
const tsconfig = makeFile("/a/tsconfig.json", {});
const et = new TestServerEventManager([file, file2, tsconfig]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({}, tsconfig.path);
et.service.closeClientFile(file.path);
checkNumberOfProjects(et.service, { configuredProjects: 1 });
et.service.openClientFile(file2.path);
checkNumberOfProjects(et.service, { inferredProjects: 1 });
et.hasZeroEvent(server.ProjectInfoTelemetryEvent);
et.service.openClientFile(file.path);
checkNumberOfProjects(et.service, { configuredProjects: 1, inferredProjects: 1 });
et.hasZeroEvent(server.ProjectInfoTelemetryEvent);
});
it("counts files by extension", () => {
const files = ["ts.ts", "tsx.tsx", "moo.ts", "dts.d.ts", "jsx.jsx", "js.js", "badExtension.badExtension"].map(f => makeFile(`/src/${f}`));
const notIncludedFile = makeFile("/bin/ts.js");
const compilerOptions: CompilerOptions = { allowJs: true };
const tsconfig = makeFile("/tsconfig.json", { compilerOptions, include: ["src"] });
const et = new TestServerEventManager([...files, notIncludedFile, tsconfig]);
et.service.openClientFile(files[0].path);
et.assertProjectInfoTelemetryEvent({
fileStats: fileStats({ ts: 2, tsx: 1, js: 1, jsx: 1, dts: 1 }),
compilerOptions,
include: true,
});
});
it("works with external project", () => {
const file1 = makeFile("/a.ts");
const et = new TestServerEventManager([file1]);
const compilerOptions: server.protocol.CompilerOptions = { strict: true };
const projectFileName = "/hunter2/foo.csproj";
open();
// TODO: Apparently compilerOptions is mutated, so have to repeat it here!
et.assertProjectInfoTelemetryEvent({
compilerOptions: { strict: true },
compileOnSave: true,
// These properties can't be present for an external project, so they are undefined instead of false.
extends: undefined,
files: undefined,
include: undefined,
exclude: undefined,
configFileName: "other",
projectType: "external",
}, "/hunter2/foo.csproj");
// Also test that opening an external project only sends an event once.
et.service.closeClientFile(file1.path);
et.service.closeExternalProject(projectFileName);
checkNumberOfProjects(et.service, { externalProjects: 0 });
open();
assert.equal(et.getEvents().length, 0);
function open(): void {
et.service.openExternalProject({
rootFiles: toExternalFiles([file1.path]),
options: compilerOptions,
projectFileName,
});
checkNumberOfProjects(et.service, { externalProjects: 1 });
et.service.openClientFile(file1.path); // Only on file open the project will be updated
}
});
it("does not expose paths", () => {
const file = makeFile("/a.ts");
const compilerOptions: CompilerOptions = {
project: "",
outFile: "hunter2.js",
outDir: "hunter2",
rootDir: "hunter2",
baseUrl: "hunter2",
rootDirs: ["hunter2"],
typeRoots: ["hunter2"],
types: ["hunter2"],
sourceRoot: "hunter2",
mapRoot: "hunter2",
jsxFactory: "hunter2",
out: "hunter2",
reactNamespace: "hunter2",
charset: "hunter2",
locale: "hunter2",
declarationDir: "hunter2",
paths: {
"*": ["hunter2"],
},
// Boolean / number options get through
declaration: true,
// List of string enum gets through -- but only if legitimately a member of the enum
lib: ["es6", "dom", "hunter2"],
// Sensitive data doesn't get through even if sent to an option of safe type
checkJs: "hunter2" as any as boolean,
};
const safeCompilerOptions: CompilerOptions = {
project: "",
outFile: "",
outDir: "",
rootDir: "",
baseUrl: "",
rootDirs: [""],
typeRoots: [""],
types: [""],
sourceRoot: "",
mapRoot: "",
jsxFactory: "",
out: "",
reactNamespace: "",
charset: "",
locale: "",
declarationDir: "",
paths: "" as any,
declaration: true,
lib: ["es6", "dom"],
};
(compilerOptions as any).unknownCompilerOption = "hunter2"; // These are always ignored.
const tsconfig = makeFile("/tsconfig.json", { compilerOptions, files: ["/a.ts"] });
const et = new TestServerEventManager([file, tsconfig]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
compilerOptions: safeCompilerOptions,
files: true,
});
});
it("sends telemetry for extends, files, include, exclude, and compileOnSave", () => {
const file = makeFile("/hunter2/a.ts");
const tsconfig = makeFile("/tsconfig.json", {
compilerOptions: {},
extends: "hunter2.json",
files: ["hunter2/a.ts"],
include: ["hunter2"],
exclude: ["hunter2"],
compileOnSave: true,
});
const et = new TestServerEventManager([tsconfig, file]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
extends: true,
files: true,
include: true,
exclude: true,
compileOnSave: true,
});
});
const autoJsCompilerOptions = {
// Apparently some options are added by default.
allowJs: true,
allowSyntheticDefaultImports: true,
maxNodeModuleJsDepth: 2,
skipLibCheck: true,
noEmit: true
};
it("sends telemetry for typeAcquisition settings", () => {
const file = makeFile("/a.js");
const jsconfig = makeFile("/jsconfig.json", {
compilerOptions: {},
typeAcquisition: {
enable: true,
enableAutoDiscovery: false,
include: ["hunter2", "hunter3"],
exclude: [],
},
});
const et = new TestServerEventManager([jsconfig, file]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
fileStats: fileStats({ js: 1 }),
compilerOptions: autoJsCompilerOptions,
typeAcquisition: {
enable: true,
include: true,
exclude: false,
},
configFileName: "jsconfig.json",
}, "/jsconfig.json");
});
it("detects whether language service was disabled", () => {
const file = makeFile("/a.js");
const tsconfig = makeFile("/jsconfig.json", {});
const et = new TestServerEventManager([tsconfig, file]);
et.host.getFileSize = () => server.maxProgramSizeForNonTsFiles + 1;
et.service.openClientFile(file.path);
et.getEvent<server.ProjectLanguageServiceStateEvent>(server.ProjectLanguageServiceStateEvent);
et.assertProjectInfoTelemetryEvent({
fileStats: fileStats({ js: 1 }),
compilerOptions: autoJsCompilerOptions,
configFileName: "jsconfig.json",
typeAcquisition: {
enable: true,
include: false,
exclude: false,
},
languageServiceEnabled: false,
}, "/jsconfig.json");
});
describe("open files telemetry", () => {
it("sends event for inferred project", () => {
const ajs = makeFile("/a.js", "// @ts-check\nconst x = 0;");
const bjs = makeFile("/b.js");
const et = new TestServerEventManager([ajs, bjs]);
et.service.openClientFile(ajs.path);
et.assertOpenFileTelemetryEvent({ checkJs: true });
et.service.openClientFile(bjs.path);
et.assertOpenFileTelemetryEvent({ checkJs: false });
// No repeated send for opening a file seen before.
et.service.openClientFile(bjs.path);
et.assertNoOpenFilesTelemetryEvent();
});
it("not for '.ts' file", () => {
const ats = makeFile("/a.ts", "");
const et = new TestServerEventManager([ats]);
et.service.openClientFile(ats.path);
et.assertNoOpenFilesTelemetryEvent();
});
it("even for project with 'ts-check' in config", () => {
const file = makeFile("/a.js");
const compilerOptions: CompilerOptions = { checkJs: true };
const jsconfig = makeFile("/jsconfig.json", { compilerOptions });
const et = new TestServerEventManager([jsconfig, file]);
et.service.openClientFile(file.path);
et.assertOpenFileTelemetryEvent({ checkJs: false });
});
});
});
function makeFile(path: string, content: {} = ""): File {
return { path, content: isString(content) ? content : JSON.stringify(content) };
}
} | the_stack |
import * as cp from 'child_process';
import {EventEmitter} from 'events';
import * as fs from 'fs';
import * as path from 'path';
import * as shell from 'shelljs';
import {SHORT_SHA_LEN} from '../../lib/common/constants';
import {Logger} from '../../lib/common/utils';
import {BuildCreator} from '../../lib/preview-server/build-creator';
import {ChangedPrVisibilityEvent, CreatedBuildEvent} from '../../lib/preview-server/build-events';
import {PreviewServerError} from '../../lib/preview-server/preview-error';
import {customAsyncMatchers} from './jasmine-custom-async-matchers';
// Tests
describe('BuildCreator', () => {
const pr = 9;
const sha = '9'.repeat(40);
const shortSha = sha.substr(0, SHORT_SHA_LEN);
const archive = 'snapshot.tar.gz';
const buildsDir = 'builds/dir';
const hiddenPrDir = path.join(buildsDir, `hidden--${pr}`);
const publicPrDir = path.join(buildsDir, `${pr}`);
const hiddenShaDir = path.join(hiddenPrDir, shortSha);
const publicShaDir = path.join(publicPrDir, shortSha);
let bc: BuildCreator;
beforeEach(() => jasmine.addAsyncMatchers(customAsyncMatchers));
beforeEach(() => bc = new BuildCreator(buildsDir));
describe('constructor()', () => {
it('should throw if \'buildsDir\' is missing or empty', () => {
expect(() => new BuildCreator('')).toThrowError('Missing or empty required parameter \'buildsDir\'!');
});
it('should extend EventEmitter', () => {
expect(bc).toBeInstanceOf(BuildCreator);
expect(bc).toBeInstanceOf(EventEmitter);
expect(Object.getPrototypeOf(bc)).toBe(BuildCreator.prototype);
});
});
describe('create()', () => {
let bcEmitSpy: jasmine.Spy;
let bcExistsSpy: jasmine.Spy;
let bcExtractArchiveSpy: jasmine.Spy;
let bcUpdatePrVisibilitySpy: jasmine.Spy;
let shellMkdirSpy: jasmine.Spy;
let shellRmSpy: jasmine.Spy;
beforeEach(() => {
bcEmitSpy = spyOn(bc, 'emit');
bcExistsSpy = spyOn(bc as any, 'exists');
bcExtractArchiveSpy = spyOn(bc as any, 'extractArchive');
bcUpdatePrVisibilitySpy = spyOn(bc, 'updatePrVisibility');
shellMkdirSpy = spyOn(shell, 'mkdir');
shellRmSpy = spyOn(shell, 'rm');
});
[true, false].forEach(isPublic => {
const prDir = isPublic ? publicPrDir : hiddenPrDir;
const shaDir = isPublic ? publicShaDir : hiddenShaDir;
it('should return a promise', async () => {
const promise = bc.create(pr, sha, archive, isPublic);
expect(promise).toBeInstanceOf(Promise);
// Do not complete the test (and release the spies) synchronously to avoid running the actual
// `extractArchive()`.
await promise;
});
it('should update the PR\'s visibility first if necessary', async () => {
await bc.create(pr, sha, archive, isPublic);
expect(bcUpdatePrVisibilitySpy).toHaveBeenCalledBefore(shellMkdirSpy);
expect(bcUpdatePrVisibilitySpy).toHaveBeenCalledWith(pr, isPublic);
expect(shellMkdirSpy).toHaveBeenCalled();
});
it('should create the build directory (and any parent directories)', async () => {
await bc.create(pr, sha, archive, isPublic);
expect(shellMkdirSpy).toHaveBeenCalledWith('-p', shaDir);
});
it('should extract the archive contents into the build directory', async () => {
await bc.create(pr, sha, archive, isPublic);
expect(bcExtractArchiveSpy).toHaveBeenCalledWith(archive, shaDir);
});
it('should emit a CreatedBuildEvent on success', async () => {
let emitted = false;
bcEmitSpy.and.callFake((type: string, evt: CreatedBuildEvent) => {
expect(type).toBe(CreatedBuildEvent.type);
expect(evt).toBeInstanceOf(CreatedBuildEvent);
expect(evt.pr).toBe(+pr);
expect(evt.sha).toBe(shortSha);
expect(evt.isPublic).toBe(isPublic);
emitted = true;
});
await bc.create(pr, sha, archive, isPublic);
expect(emitted).toBe(true);
});
describe('on error', () => {
beforeEach(() => {
bcExistsSpy.and.returnValue(false);
});
it('should abort and skip further operations if changing the PR\'s visibility fails', async () => {
const mockError = new PreviewServerError(543, 'Test');
bcUpdatePrVisibilitySpy.and.rejectWith(mockError);
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWith(mockError);
expect(bcExistsSpy).not.toHaveBeenCalled();
expect(shellMkdirSpy).not.toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should abort and skip further operations if the build does already exist', async () => {
bcExistsSpy.withArgs(shaDir).and.returnValue(true);
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWithPreviewServerError(
409, `Request to overwrite existing ${isPublic ? '' : 'non-'}public directory: ${shaDir}`);
expect(shellMkdirSpy).not.toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should detect existing build directory after visibility change', async () => {
bcUpdatePrVisibilitySpy.and.callFake(() => bcExistsSpy.and.returnValue(true));
expect(bcExistsSpy(prDir)).toBe(false);
expect(bcExistsSpy(shaDir)).toBe(false);
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWithPreviewServerError(
409, `Request to overwrite existing ${isPublic ? '' : 'non-'}public directory: ${shaDir}`);
expect(shellMkdirSpy).not.toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should abort and skip further operations if it fails to create the directories', async () => {
shellMkdirSpy.and.throwError('');
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejected();
expect(shellMkdirSpy).toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should abort and skip further operations if it fails to extract the archive', async () => {
bcExtractArchiveSpy.and.throwError('');
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejected();
expect(shellMkdirSpy).toHaveBeenCalled();
expect(bcExtractArchiveSpy).toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should delete the PR directory (for new PR)', async () => {
bcExtractArchiveSpy.and.throwError('');
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejected();
expect(shellRmSpy).toHaveBeenCalledWith('-rf', prDir);
});
it('should delete the SHA directory (for existing PR)', async () => {
bcExistsSpy.withArgs(prDir).and.returnValue(true);
bcExtractArchiveSpy.and.throwError('');
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejected();
expect(shellRmSpy).toHaveBeenCalledWith('-rf', shaDir);
});
it('should reject with an PreviewServerError', async () => {
// tslint:disable-next-line: no-string-throw
shellMkdirSpy.and.callFake(() => { throw 'Test'; });
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWithPreviewServerError(
500, `Error while creating preview at: ${shaDir}\nTest`);
});
it('should pass PreviewServerError instances unmodified', async () => {
shellMkdirSpy.and.callFake(() => { throw new PreviewServerError(543, 'Test'); });
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWithPreviewServerError(543, 'Test');
});
});
});
});
describe('updatePrVisibility()', () => {
let bcEmitSpy: jasmine.Spy;
let bcExistsSpy: jasmine.Spy;
let bcListShasByDate: jasmine.Spy;
let shellMvSpy: jasmine.Spy;
beforeEach(() => {
bcEmitSpy = spyOn(bc, 'emit');
bcExistsSpy = spyOn(bc as any, 'exists');
bcListShasByDate = spyOn(bc as any, 'listShasByDate');
shellMvSpy = spyOn(shell, 'mv');
bcExistsSpy.and.returnValues(Promise.resolve(true), Promise.resolve(false));
bcListShasByDate.and.returnValue([]);
});
it('should return a promise', async () => {
const promise = bc.updatePrVisibility(pr, true);
expect(promise).toBeInstanceOf(Promise);
// Do not complete the test (and release the spies) synchronously to avoid running the actual `extractArchive()`.
await promise;
});
[true, false].forEach(makePublic => {
const oldPrDir = makePublic ? hiddenPrDir : publicPrDir;
const newPrDir = makePublic ? publicPrDir : hiddenPrDir;
it('should rename the directory', async () => {
await bc.updatePrVisibility(pr, makePublic);
expect(shellMvSpy).toHaveBeenCalledWith(oldPrDir, newPrDir);
});
describe('when the visibility is updated', () => {
it('should resolve to true', async () => {
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeResolvedTo(true);
});
it('should rename the directory', async () => {
await bc.updatePrVisibility(pr, makePublic);
expect(shellMvSpy).toHaveBeenCalledWith(oldPrDir, newPrDir);
});
it('should emit a ChangedPrVisibilityEvent on success', async () => {
let emitted = false;
bcEmitSpy.and.callFake((type: string, evt: ChangedPrVisibilityEvent) => {
expect(type).toBe(ChangedPrVisibilityEvent.type);
expect(evt).toBeInstanceOf(ChangedPrVisibilityEvent);
expect(evt.pr).toBe(+pr);
expect(evt.shas).toBeInstanceOf(Array);
expect(evt.isPublic).toBe(makePublic);
emitted = true;
});
await bc.updatePrVisibility(pr, makePublic);
expect(emitted).toBe(true);
});
it('should include all shas in the emitted event', async () => {
const shas = ['foo', 'bar', 'baz'];
let emitted = false;
bcListShasByDate.and.resolveTo(shas);
bcEmitSpy.and.callFake((type: string, evt: ChangedPrVisibilityEvent) => {
expect(bcListShasByDate).toHaveBeenCalledWith(newPrDir);
expect(type).toBe(ChangedPrVisibilityEvent.type);
expect(evt).toBeInstanceOf(ChangedPrVisibilityEvent);
expect(evt.pr).toBe(+pr);
expect(evt.shas).toBe(shas);
expect(evt.isPublic).toBe(makePublic);
emitted = true;
});
await bc.updatePrVisibility(pr, makePublic);
expect(emitted).toBe(true);
});
});
it('should do nothing if the visibility is already up-to-date', async () => {
bcExistsSpy.and.callFake((dir: string) => dir === newPrDir);
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeResolvedTo(false);
expect(shellMvSpy).not.toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should do nothing if the PR directory does not exist', async () => {
bcExistsSpy.and.returnValue(false);
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeResolvedTo(false);
expect(shellMvSpy).not.toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
describe('on error', () => {
it('should abort and skip further operations if both directories exist', async () => {
bcExistsSpy.and.returnValue(true);
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejectedWithPreviewServerError(
409, `Request to move '${oldPrDir}' to existing directory '${newPrDir}'.`);
expect(shellMvSpy).not.toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should abort and skip further operations if it fails to rename the directory', async () => {
shellMvSpy.and.throwError('');
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejected();
expect(shellMvSpy).toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should abort and skip further operations if it fails to list the SHAs', async () => {
bcListShasByDate.and.throwError('');
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejected();
expect(shellMvSpy).toHaveBeenCalled();
expect(bcListShasByDate).toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
});
it('should reject with an PreviewServerError', async () => {
// tslint:disable-next-line: no-string-throw
shellMvSpy.and.callFake(() => { throw 'Test'; });
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejectedWithPreviewServerError(
500, `Error while making PR ${pr} ${makePublic ? 'public' : 'hidden'}.\nTest`);
});
it('should pass PreviewServerError instances unmodified', async () => {
shellMvSpy.and.callFake(() => { throw new PreviewServerError(543, 'Test'); });
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejectedWithPreviewServerError(543, 'Test');
});
});
});
});
// Protected methods
describe('exists()', () => {
let fsAccessSpy: jasmine.Spy;
let fsAccessCbs: ((v?: any) => void)[];
beforeEach(() => {
fsAccessCbs = [];
fsAccessSpy = spyOn(fs, 'access').and.callFake(
((_: string, cb: (v?: any) => void) => fsAccessCbs.push(cb)) as unknown as typeof fs.access,
);
});
it('should return a promise', () => {
expect((bc as any).exists('foo')).toBeInstanceOf(Promise);
});
it('should call \'fs.access()\' with the specified argument', () => {
(bc as any).exists('foo');
expect(fsAccessSpy).toHaveBeenCalledWith('foo', jasmine.any(Function));
});
it('should resolve with \'true\' if \'fs.access()\' succeeds', async () => {
const existsPromises = [
(bc as any).exists('foo'),
(bc as any).exists('bar'),
];
fsAccessCbs[0]();
fsAccessCbs[1](null);
await expectAsync(Promise.all(existsPromises)).toBeResolvedTo([true, true]);
});
it('should resolve with \'false\' if \'fs.access()\' errors', async () => {
const existsPromises = [
(bc as any).exists('foo'),
(bc as any).exists('bar'),
];
fsAccessCbs[0]('Error');
fsAccessCbs[1](new Error());
await expectAsync(Promise.all(existsPromises)).toBeResolvedTo([false, false]);
});
});
describe('extractArchive()', () => {
let consoleWarnSpy: jasmine.Spy;
let shellChmodSpy: jasmine.Spy;
let shellRmSpy: jasmine.Spy;
let cpExecSpy: jasmine.Spy;
let cpExecCbs: ((...args: any[]) => void)[];
beforeEach(() => {
cpExecCbs = [];
consoleWarnSpy = spyOn(Logger.prototype, 'warn');
shellChmodSpy = spyOn(shell, 'chmod');
shellRmSpy = spyOn(shell, 'rm');
cpExecSpy = spyOn(cp, 'exec').and.callFake(
((_: string, cb: (...args: any[]) => void) =>
cpExecCbs.push(cb)) as unknown as typeof cp.exec,
);
});
it('should return a promise', () => {
expect((bc as any).extractArchive('foo', 'bar')).toBeInstanceOf(Promise);
});
it('should "gunzip" and "untar" the input file into the output directory', () => {
const cmd = 'tar --extract --gzip --directory "output/dir" --file "input/file"';
(bc as any).extractArchive('input/file', 'output/dir');
expect(cpExecSpy).toHaveBeenCalledWith(cmd, jasmine.any(Function));
});
it('should log (as a warning) any stderr output if extracting succeeded', async () => {
const extractPromise = (bc as any).extractArchive('foo', 'bar');
cpExecCbs[0](null, 'This is stdout', 'This is stderr');
await expectAsync(extractPromise).toBeResolved();
expect(consoleWarnSpy).toHaveBeenCalledWith('This is stderr');
});
it('should make the build directory non-writable', async () => {
const extractPromise = (bc as any).extractArchive('foo', 'bar');
cpExecCbs[0]();
await expectAsync(extractPromise).toBeResolved();
expect(shellChmodSpy).toHaveBeenCalledWith('-R', 'a-w', 'bar');
});
it('should delete the build artifact file on success', async () => {
const extractPromise = (bc as any).extractArchive('input/file', 'output/dir');
cpExecCbs[0]();
await expectAsync(extractPromise).toBeResolved();
expect(shellRmSpy).toHaveBeenCalledWith('-f', 'input/file');
});
describe('on error', () => {
it('should abort and skip further operations if it fails to extract the archive', async () => {
const extractPromise = (bc as any).extractArchive('foo', 'bar');
cpExecCbs[0]('Test');
await expectAsync(extractPromise).toBeRejectedWith('Test');
expect(shellChmodSpy).not.toHaveBeenCalled();
expect(shellRmSpy).not.toHaveBeenCalled();
});
it('should abort and skip further operations if it fails to make non-writable', async () => {
// tslint:disable-next-line: no-string-throw
shellChmodSpy.and.callFake(() => { throw 'Test'; });
const extractPromise = (bc as any).extractArchive('foo', 'bar');
cpExecCbs[0]();
await expectAsync(extractPromise).toBeRejectedWith('Test');
expect(shellChmodSpy).toHaveBeenCalled();
expect(shellRmSpy).not.toHaveBeenCalled();
});
it('should abort and reject if it fails to remove the build artifact file', async () => {
// tslint:disable-next-line: no-string-throw
shellRmSpy.and.callFake(() => { throw 'Test'; });
const extractPromise = (bc as any).extractArchive('foo', 'bar');
cpExecCbs[0]();
await expectAsync(extractPromise).toBeRejectedWith('Test');
expect(shellChmodSpy).toHaveBeenCalled();
expect(shellRmSpy).toHaveBeenCalled();
});
});
});
describe('listShasByDate()', () => {
let shellLsSpy: jasmine.Spy;
const lsResult = (name: string, mtimeMs: number, isDirectory = true) => ({
isDirectory: () => isDirectory,
mtime: new Date(mtimeMs),
name,
});
beforeEach(() => {
shellLsSpy = spyOn(shell, 'ls').and.returnValue([] as unknown as shell.ShellArray);
});
it('should return a promise', async () => {
const promise = (bc as any).listShasByDate('input/dir');
expect(promise).toBeInstanceOf(Promise);
// Do not complete the test (and release the spies) synchronously to avoid running the actual `ls()`.
await promise;
});
it('should `ls()` files with their metadata', async () => {
await (bc as any).listShasByDate('input/dir');
expect(shellLsSpy).toHaveBeenCalledWith('-l', 'input/dir');
});
it('should reject if listing files fails', async () => {
shellLsSpy.and.rejectWith('Test');
await expectAsync((bc as any).listShasByDate('input/dir')).toBeRejectedWith('Test');
});
it('should return the filenames', async () => {
shellLsSpy.and.resolveTo([
lsResult('foo', 100),
lsResult('bar', 200),
lsResult('baz', 300),
]);
await expectAsync((bc as any).listShasByDate('input/dir')).toBeResolvedTo(['foo', 'bar', 'baz']);
});
it('should sort by date', async () => {
shellLsSpy.and.resolveTo([
lsResult('foo', 300),
lsResult('bar', 100),
lsResult('baz', 200),
]);
await expectAsync((bc as any).listShasByDate('input/dir')).toBeResolvedTo(['bar', 'baz', 'foo']);
});
it('should not break with ShellJS\' custom `sort()` method', async () => {
const mockArray = [
lsResult('foo', 300),
lsResult('bar', 100),
lsResult('baz', 200),
];
mockArray.sort = jasmine.createSpy('sort');
shellLsSpy.and.resolveTo(mockArray);
await expectAsync((bc as any).listShasByDate('input/dir')).toBeResolvedTo(['bar', 'baz', 'foo']);
expect(mockArray.sort).not.toHaveBeenCalled();
});
it('should only include directories', async () => {
shellLsSpy.and.resolveTo([
lsResult('foo', 100),
lsResult('bar', 200, false),
lsResult('baz', 300),
]);
await expectAsync((bc as any).listShasByDate('input/dir')).toBeResolvedTo(['foo', 'baz']);
});
});
}); | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Manages a Log Analytics (formally Operational Insights) Windows Performance Counter DataSource.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAnalyticsWorkspace = new azure.operationalinsights.AnalyticsWorkspace("exampleAnalyticsWorkspace", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* sku: "PerGB2018",
* });
* const exampleDataSourceWindowsPerformanceCounter = new azure.loganalytics.DataSourceWindowsPerformanceCounter("exampleDataSourceWindowsPerformanceCounter", {
* resourceGroupName: exampleResourceGroup.name,
* workspaceName: exampleAnalyticsWorkspace.name,
* objectName: "CPU",
* instanceName: "*",
* counterName: "CPU",
* intervalSeconds: 10,
* });
* ```
*
* ## Import
*
* Log Analytics Windows Performance Counter DataSources can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:loganalytics/dataSourceWindowsPerformanceCounter:DataSourceWindowsPerformanceCounter example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.OperationalInsights/workspaces/workspace1/datasources/datasource1
* ```
*/
export class DataSourceWindowsPerformanceCounter extends pulumi.CustomResource {
/**
* Get an existing DataSourceWindowsPerformanceCounter resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: DataSourceWindowsPerformanceCounterState, opts?: pulumi.CustomResourceOptions): DataSourceWindowsPerformanceCounter {
return new DataSourceWindowsPerformanceCounter(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:loganalytics/dataSourceWindowsPerformanceCounter:DataSourceWindowsPerformanceCounter';
/**
* Returns true if the given object is an instance of DataSourceWindowsPerformanceCounter. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is DataSourceWindowsPerformanceCounter {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === DataSourceWindowsPerformanceCounter.__pulumiType;
}
/**
* The friendly name of the performance counter.
*/
public readonly counterName!: pulumi.Output<string>;
/**
* The name of the virtual machine instance to which the Windows Performance Counter DataSource be applied. Specify a `*` will apply to all instances.
*/
public readonly instanceName!: pulumi.Output<string>;
/**
* The time of sample interval in seconds. Supports values between 10 and 2147483647.
*/
public readonly intervalSeconds!: pulumi.Output<number>;
/**
* The Name which should be used for this Log Analytics Windows Performance Counter DataSource. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* The object name of the Log Analytics Windows Performance Counter DataSource.
*/
public readonly objectName!: pulumi.Output<string>;
/**
* The name of the Resource Group where the Log Analytics Windows Performance Counter DataSource should exist. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* The name of the Log Analytics Workspace where the Log Analytics Windows Performance Counter DataSource should exist. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
public readonly workspaceName!: pulumi.Output<string>;
/**
* Create a DataSourceWindowsPerformanceCounter resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: DataSourceWindowsPerformanceCounterArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: DataSourceWindowsPerformanceCounterArgs | DataSourceWindowsPerformanceCounterState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as DataSourceWindowsPerformanceCounterState | undefined;
inputs["counterName"] = state ? state.counterName : undefined;
inputs["instanceName"] = state ? state.instanceName : undefined;
inputs["intervalSeconds"] = state ? state.intervalSeconds : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["objectName"] = state ? state.objectName : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["workspaceName"] = state ? state.workspaceName : undefined;
} else {
const args = argsOrState as DataSourceWindowsPerformanceCounterArgs | undefined;
if ((!args || args.counterName === undefined) && !opts.urn) {
throw new Error("Missing required property 'counterName'");
}
if ((!args || args.instanceName === undefined) && !opts.urn) {
throw new Error("Missing required property 'instanceName'");
}
if ((!args || args.intervalSeconds === undefined) && !opts.urn) {
throw new Error("Missing required property 'intervalSeconds'");
}
if ((!args || args.objectName === undefined) && !opts.urn) {
throw new Error("Missing required property 'objectName'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
if ((!args || args.workspaceName === undefined) && !opts.urn) {
throw new Error("Missing required property 'workspaceName'");
}
inputs["counterName"] = args ? args.counterName : undefined;
inputs["instanceName"] = args ? args.instanceName : undefined;
inputs["intervalSeconds"] = args ? args.intervalSeconds : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["objectName"] = args ? args.objectName : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["workspaceName"] = args ? args.workspaceName : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(DataSourceWindowsPerformanceCounter.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering DataSourceWindowsPerformanceCounter resources.
*/
export interface DataSourceWindowsPerformanceCounterState {
/**
* The friendly name of the performance counter.
*/
counterName?: pulumi.Input<string>;
/**
* The name of the virtual machine instance to which the Windows Performance Counter DataSource be applied. Specify a `*` will apply to all instances.
*/
instanceName?: pulumi.Input<string>;
/**
* The time of sample interval in seconds. Supports values between 10 and 2147483647.
*/
intervalSeconds?: pulumi.Input<number>;
/**
* The Name which should be used for this Log Analytics Windows Performance Counter DataSource. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
name?: pulumi.Input<string>;
/**
* The object name of the Log Analytics Windows Performance Counter DataSource.
*/
objectName?: pulumi.Input<string>;
/**
* The name of the Resource Group where the Log Analytics Windows Performance Counter DataSource should exist. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
resourceGroupName?: pulumi.Input<string>;
/**
* The name of the Log Analytics Workspace where the Log Analytics Windows Performance Counter DataSource should exist. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
workspaceName?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a DataSourceWindowsPerformanceCounter resource.
*/
export interface DataSourceWindowsPerformanceCounterArgs {
/**
* The friendly name of the performance counter.
*/
counterName: pulumi.Input<string>;
/**
* The name of the virtual machine instance to which the Windows Performance Counter DataSource be applied. Specify a `*` will apply to all instances.
*/
instanceName: pulumi.Input<string>;
/**
* The time of sample interval in seconds. Supports values between 10 and 2147483647.
*/
intervalSeconds: pulumi.Input<number>;
/**
* The Name which should be used for this Log Analytics Windows Performance Counter DataSource. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
name?: pulumi.Input<string>;
/**
* The object name of the Log Analytics Windows Performance Counter DataSource.
*/
objectName: pulumi.Input<string>;
/**
* The name of the Resource Group where the Log Analytics Windows Performance Counter DataSource should exist. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
resourceGroupName: pulumi.Input<string>;
/**
* The name of the Log Analytics Workspace where the Log Analytics Windows Performance Counter DataSource should exist. Changing this forces a new Log Analytics Windows Performance Counter DataSource to be created.
*/
workspaceName: pulumi.Input<string>;
} | the_stack |
import { BatchCluster } from "batch-cluster"
import * as _path from "path"
import { times } from "./Array"
import { ExifDateTime } from "./ExifDateTime"
import { DefaultMaxProcs, ExifTool, exiftool, WriteTags } from "./ExifTool"
import { keys } from "./Object"
import { leftPad } from "./String"
import { Tags } from "./Tags"
import { expect, isWin32, testImg } from "./_chai.spec"
function normalize(tagNames: string[]): string[] {
return tagNames
.filter((i) => i !== "FileInodeChangeDate" && i !== "FileCreateDate")
.sort()
}
function posixPath(path: string) {
return path.split(_path.sep).join("/")
}
describe("ExifTool", function () {
this.timeout(15000)
this.slow(100)
const truncated = _path.join(__dirname, "..", "test", "truncated.jpg")
const noexif = _path.join(__dirname, "..", "test", "noexif.jpg")
const img = _path.join(__dirname, "..", "test", "img.jpg")
const img2 = _path.join(__dirname, "..", "test", "ExifTool.jpg")
const img3 = _path.join(__dirname, "..", "test", "with_thumb.jpg")
const nonEnglishImg = _path.join(__dirname, "..", "test", "中文.jpg")
const packageJson = require("../package.json")
function expectedExiftoolVersion(flavor: "exe" | "pl" = "pl"): string {
const vendorVersion: string =
packageJson.optionalDependencies["exiftool-vendored." + flavor]
// Everyone's a monster here:
// * semver is pissy about 0-padded version numbers (srsly, it's ok)
// * exiftool bumps the major version because minor hit 99</rant>
// vendorVersion might have a ^ or ~ or something else as a prefix, so get
// rid of that:
return vendorVersion
.replace(/^[^.0-9]+/, "")
.split(".")
.slice(0, 2)
.map((ea) => leftPad(ea, 2, "0"))
.join(".")
}
it("perl and win32 versions match", () => {
const pl = expectedExiftoolVersion("pl")
const exe = expectedExiftoolVersion("exe")
expect(pl).to.eql(exe)
})
it("exports a singleton instance", () => {
// don't call any methods that actually results in spinning up a child
// proc:
expect(exiftool.options.maxProcs).to.eql(DefaultMaxProcs)
})
const ignoreShebangs = []
if (exiftool.options.ignoreShebang) {
// If the default is true, we can only test true.
ignoreShebangs.push(true)
} else {
ignoreShebangs.push(false)
if (!isWin32()) ignoreShebangs.push(true)
}
for (const ignoreShebang of ignoreShebangs) {
describe("exiftool({ ignoreShebang: " + ignoreShebang + " })", () => {
let et: ExifTool
before(
() =>
(et = new ExifTool({
maxProcs: 2,
ignoreShebang,
}))
)
after(() => et.end())
it("returns the correct version", async function () {
this.slow(500)
return expect(await et.version()).to.eql(expectedExiftoolVersion())
})
it("returns a reasonable value for MaxProcs", () => {
// 64 cpus on my dream laptop
expect(DefaultMaxProcs).to.be.within(1, 64)
})
it("returns expected results for a given file", async function () {
this.slow(500)
return expect(
et.read(img).then((tags) => tags.Model)
).to.eventually.eql("iPhone 7 Plus")
})
it("returns raw tag values", async () => {
return expect(et.readRaw(img, ["-Make", "-Model"])).to.eventually.eql({
Make: "Apple",
Model: "iPhone 7 Plus",
SourceFile: posixPath(img),
}) // and nothing else
})
it("returns expected results for a given file with non-english filename", async function () {
this.slow(500)
return expect(
et.read(nonEnglishImg).then((tags) => tags.Model)
).to.eventually.eql("iPhone 7 Plus")
})
it("renders Orientation as numbers", async () => {
const tags = await et.read(img)
expect(tags.Orientation).to.eql(1)
return
})
it("omits OriginalImage{Width,Height} by default", async () => {
return expect(await et.read(img2)).to.containSubset({
Keywords: "jambalaya",
ImageHeight: 8,
ImageWidth: 8,
OriginalImageHeight: undefined,
OriginalImageWidth: undefined,
})
})
it("extracts OriginalImage{Width,Height} if [] is provided to override the -fast option", async () => {
return expect(await et.read(img2, [])).to.containSubset({
Keywords: "jambalaya",
ImageHeight: 8,
ImageWidth: 8,
OriginalImageHeight: 16,
OriginalImageWidth: 16,
})
})
it("returns warning for a truncated file", async () => {
return expect(await et.read(truncated)).to.containSubset({
FileName: "truncated.jpg",
FileSize: "1000 bytes",
FileType: "JPEG",
FileTypeExtension: "jpg",
MIMEType: "image/jpeg",
Warning: "JPEG format error",
})
})
it("returns no exif metadata for an image with no headers", () => {
return expect(
et.read(noexif).then((tags) => normalize(Object.keys(tags)))
).to.become(
normalize([
"BitsPerSample",
"ColorComponents",
"Directory",
"EncodingProcess",
"ExifToolVersion",
"FileAccessDate",
"FileModifyDate",
"FileName",
"FilePermissions",
"FileSize",
"FileType",
"FileTypeExtension",
"ImageHeight",
"ImageSize",
"ImageWidth",
"Megapixels",
"MIMEType",
"SourceFile",
"YCbCrSubSampling",
"errors",
])
)
})
it("returns error for missing file", () => {
return expect(et.read("bogus")).to.eventually.be.rejectedWith(
/ENOENT|file not found/i
)
})
it("works with text files", async () => {
return expect(await et.read(__filename)).to.containSubset({
FileType: "TXT",
FileTypeExtension: "txt",
MIMEType: "text/plain",
// may be utf-8 or us-ascii, but we don't really care.
// MIMEEncoding: "us-ascii",
errors: [],
})
})
function assertReasonableTags(tags: Tags[]): void {
tags.forEach((tag) => {
expect(tag.errors).to.eql([])
expect(tag.MIMEType).to.eql("image/jpeg")
expect(tag.GPSLatitude).to.be.within(-90, 90)
expect(tag.GPSLongitude).to.be.within(-180, 180)
})
}
it("ends procs when they've run > maxTasksPerProcess", async function () {
const maxProcs = 5
const maxTasksPerProcess = 8
const et2 = new ExifTool({ maxProcs, maxTasksPerProcess })
const iters = maxProcs * maxTasksPerProcess
// Warm up the children:
const promises = times(iters, () => et2.read(img))
const tags = await Promise.all(promises)
// I don't want to expose the .batchCluster field as part of the public API:
const bc = et2["batchCluster"] as BatchCluster
expect(bc.spawnedProcCount).to.be.gte(maxProcs)
expect(bc.meanTasksPerProc).to.be.within(
maxTasksPerProcess / 2,
maxTasksPerProcess
)
assertReasonableTags(tags)
await et2.end()
expect(await et2.pids).to.eql([])
return
})
it("ends with multiple procs", async function () {
const maxProcs = 4
const et2 = new ExifTool({ maxProcs })
try {
const tasks = await Promise.all(
times(maxProcs * 4, () => et2.read(img3))
)
tasks.forEach((t) =>
expect(t).to.include({
// SourceFile: img3, Don't include SourceFile, because it's wonky on windows. :\
MIMEType: "image/jpeg",
Model: "C2020Z",
ImageWidth: 1600,
ImageHeight: 1200,
})
)
await et2.end()
expect(await et2.pids).to.eql([])
} finally {
await et2.end()
}
return
})
it("invalid images throw errors on write", async function () {
const badImg = await testImg("bad-exif-ifd.jpg")
return expect(
et.write(badImg, { AllDates: new Date().toISOString() })
).to.be.rejectedWith(/Duplicate MakerNoteUnknown/)
})
it("reads from a dSLR", async () => {
const t = await et.read("./test/oly.jpg")
expect(t).to.contain({
MIMEType: "image/jpeg",
Make: "OLYMPUS IMAGING CORP.",
Model: "E-M1",
ExposureTime: "1/320",
FNumber: 5,
ExposureProgram: "Program AE",
ISO: 200,
Aperture: 5,
MaxApertureValue: 2.8,
ExifImageWidth: 3200,
ExifImageHeight: 2400,
LensInfo: "12-40mm f/2.8",
LensModel: "OLYMPUS M.12-40mm F2.8",
tz: "UTC-07",
})
expect(t.DateTimeOriginal?.toString()).to.eql(
"2014-07-19T12:05:19.000-07:00"
)
})
it("reads from a smartphone with GPS", async () => {
const t = await et.read("./test/pixel.jpg")
expect(t).to.contain({
MIMEType: "image/jpeg",
Make: "Google",
Model: "Pixel",
ExposureTime: "1/831",
FNumber: 2,
ExposureProgram: "Program AE",
ISO: 50,
Aperture: 2,
MaxApertureValue: 2,
ExifImageWidth: 4048,
ExifImageHeight: 3036,
GPSLatitude: 37.4836666666667,
GPSLongitude: -122.452094444444,
GPSAltitude: 47,
tz: "America/Los_Angeles",
})
expect(t.SubSecDateTimeOriginal?.toString()).to.eql(
"2016-12-13T09:05:27.120-08:00"
)
})
it("reads from a directory with dots", async () => {
const dots = await testImg("img.jpg", "2019.05.28")
const tags = await et.read(dots)
expect(tags).to.contain({
MIMEType: "image/jpeg",
GPSLatitudeRef: "N",
GPSLongitudeRef: "E",
Make: "Apple",
Model: "iPhone 7 Plus",
FNumber: 1.8,
tz: "Asia/Hong_Kong",
})
expect(tags.DateTimeCreated).to.eql(
ExifDateTime.fromISO(
"2016-08-12T13:28:50",
"Asia/Hong_Kong",
"2016:08:12 13:28:50"
)
)
})
it("deleteAllTags() removes all metadata tags", async () => {
const f = await testImg()
const before = await et.read(f)
// This is just a sample of additional tags that are expected to be removed:
const expectedBeforeTags = [
"ApertureValue",
"DateCreated",
"DateTimeOriginal",
"Flash",
"GPSAltitude",
"GPSLatitude",
"GPSLongitude",
"GPSTimeStamp",
"LensInfo",
"Make",
"Model",
"ShutterSpeedValue",
"TimeCreated",
"XPKeywords",
]
// These are intrinsic fields that are expected to remain:
const expectedAfterTags = [
"BitsPerSample",
"ColorComponents",
"Directory",
"EncodingProcess",
"errors",
"ExifToolVersion",
"FileAccessDate",
"FileModifyDate",
"FileName",
"FilePermissions",
"FileSize",
"FileType",
"FileTypeExtension",
"ImageHeight",
"ImageSize",
"ImageWidth",
"Megapixels",
"MIMEType",
"SourceFile",
"YCbCrSubSampling",
]
{
const beforeKeys = keys(before)
;[...expectedBeforeTags, ...expectedAfterTags].forEach((ea) =>
expect(beforeKeys).to.include(ea)
)
}
await et.deleteAllTags(f)
const after = await et.read(f)
const afterKeys = keys(after).sort()
expectedBeforeTags.forEach((ea) => expect(afterKeys).to.not.include(ea))
expectedAfterTags.forEach((ea) => expect(afterKeys).to.include(ea))
})
it("supports unknown tags via generics", async () => {
const dest = await testImg()
interface A {
// I couldn't find any writable tags that we're in Tags, so this is
// just incorrectly cased:
rating: number
}
type CustomWriteTags = WriteTags & A
await et.write<CustomWriteTags>(dest, { rating: 3 }, [
"-overwrite_original",
])
type CustomTags = Tags & A
const t = await et.read<CustomTags>(dest)
// this should compile...
expect(t.rating).to.eql(undefined)
// but ExifTool will have done the conversion to "Rating":
expect(t.Rating).to.eql(3)
})
})
}
}) | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A policy that can be attached to a resource to specify or schedule actions on that resource.
*
* ## Example Usage
* ### Resource Policy Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const foo = new gcp.compute.ResourcePolicy("foo", {
* region: "us-central1",
* snapshotSchedulePolicy: {
* schedule: {
* dailySchedule: {
* daysInCycle: 1,
* startTime: "04:00",
* },
* },
* },
* });
* ```
* ### Resource Policy Full
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const bar = new gcp.compute.ResourcePolicy("bar", {
* region: "us-central1",
* snapshotSchedulePolicy: {
* retentionPolicy: {
* maxRetentionDays: 10,
* onSourceDiskDelete: "KEEP_AUTO_SNAPSHOTS",
* },
* schedule: {
* hourlySchedule: {
* hoursInCycle: 20,
* startTime: "23:00",
* },
* },
* snapshotProperties: {
* guestFlush: true,
* labels: {
* my_label: "value",
* },
* storageLocations: "us",
* },
* },
* });
* ```
* ### Resource Policy Placement Policy
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const baz = new gcp.compute.ResourcePolicy("baz", {
* groupPlacementPolicy: {
* collocation: "COLLOCATED",
* vmCount: 2,
* },
* region: "us-central1",
* });
* ```
* ### Resource Policy Instance Schedule Policy
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const hourly = new gcp.compute.ResourcePolicy("hourly", {
* description: "Start and stop instances",
* instanceSchedulePolicy: {
* timeZone: "US/Central",
* vmStartSchedule: {
* schedule: "0 * * * *",
* },
* vmStopSchedule: {
* schedule: "15 * * * *",
* },
* },
* region: "us-central1",
* });
* ```
*
* ## Import
*
* ResourcePolicy can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:compute/resourcePolicy:ResourcePolicy default projects/{{project}}/regions/{{region}}/resourcePolicies/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/resourcePolicy:ResourcePolicy default {{project}}/{{region}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/resourcePolicy:ResourcePolicy default {{region}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/resourcePolicy:ResourcePolicy default {{name}}
* ```
*/
export class ResourcePolicy extends pulumi.CustomResource {
/**
* Get an existing ResourcePolicy resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ResourcePolicyState, opts?: pulumi.CustomResourceOptions): ResourcePolicy {
return new ResourcePolicy(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:compute/resourcePolicy:ResourcePolicy';
/**
* Returns true if the given object is an instance of ResourcePolicy. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is ResourcePolicy {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === ResourcePolicy.__pulumiType;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* Resource policy for instances used for placement configuration.
* Structure is documented below.
*/
public readonly groupPlacementPolicy!: pulumi.Output<outputs.compute.ResourcePolicyGroupPlacementPolicy | undefined>;
/**
* Resource policy for scheduling instance operations.
* Structure is documented below.
*/
public readonly instanceSchedulePolicy!: pulumi.Output<outputs.compute.ResourcePolicyInstanceSchedulePolicy | undefined>;
/**
* The name of the resource, provided by the client when initially creating
* the resource. The resource name must be 1-63 characters long, and comply
* with RFC1035. Specifically, the name must be 1-63 characters long and
* match the regular expression `a-z`? which means the
* first character must be a lowercase letter, and all following characters
* must be a dash, lowercase letter, or digit, except the last character,
* which cannot be a dash.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* Region where resource policy resides.
*/
public readonly region!: pulumi.Output<string>;
/**
* The URI of the created resource.
*/
public /*out*/ readonly selfLink!: pulumi.Output<string>;
/**
* Policy for creating snapshots of persistent disks.
* Structure is documented below.
*/
public readonly snapshotSchedulePolicy!: pulumi.Output<outputs.compute.ResourcePolicySnapshotSchedulePolicy | undefined>;
/**
* Create a ResourcePolicy resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args?: ResourcePolicyArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ResourcePolicyArgs | ResourcePolicyState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ResourcePolicyState | undefined;
inputs["description"] = state ? state.description : undefined;
inputs["groupPlacementPolicy"] = state ? state.groupPlacementPolicy : undefined;
inputs["instanceSchedulePolicy"] = state ? state.instanceSchedulePolicy : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["region"] = state ? state.region : undefined;
inputs["selfLink"] = state ? state.selfLink : undefined;
inputs["snapshotSchedulePolicy"] = state ? state.snapshotSchedulePolicy : undefined;
} else {
const args = argsOrState as ResourcePolicyArgs | undefined;
inputs["description"] = args ? args.description : undefined;
inputs["groupPlacementPolicy"] = args ? args.groupPlacementPolicy : undefined;
inputs["instanceSchedulePolicy"] = args ? args.instanceSchedulePolicy : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["region"] = args ? args.region : undefined;
inputs["snapshotSchedulePolicy"] = args ? args.snapshotSchedulePolicy : undefined;
inputs["selfLink"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(ResourcePolicy.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering ResourcePolicy resources.
*/
export interface ResourcePolicyState {
/**
* An optional description of this resource. Provide this property when you create the resource.
*/
description?: pulumi.Input<string>;
/**
* Resource policy for instances used for placement configuration.
* Structure is documented below.
*/
groupPlacementPolicy?: pulumi.Input<inputs.compute.ResourcePolicyGroupPlacementPolicy>;
/**
* Resource policy for scheduling instance operations.
* Structure is documented below.
*/
instanceSchedulePolicy?: pulumi.Input<inputs.compute.ResourcePolicyInstanceSchedulePolicy>;
/**
* The name of the resource, provided by the client when initially creating
* the resource. The resource name must be 1-63 characters long, and comply
* with RFC1035. Specifically, the name must be 1-63 characters long and
* match the regular expression `a-z`? which means the
* first character must be a lowercase letter, and all following characters
* must be a dash, lowercase letter, or digit, except the last character,
* which cannot be a dash.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Region where resource policy resides.
*/
region?: pulumi.Input<string>;
/**
* The URI of the created resource.
*/
selfLink?: pulumi.Input<string>;
/**
* Policy for creating snapshots of persistent disks.
* Structure is documented below.
*/
snapshotSchedulePolicy?: pulumi.Input<inputs.compute.ResourcePolicySnapshotSchedulePolicy>;
}
/**
* The set of arguments for constructing a ResourcePolicy resource.
*/
export interface ResourcePolicyArgs {
/**
* An optional description of this resource. Provide this property when you create the resource.
*/
description?: pulumi.Input<string>;
/**
* Resource policy for instances used for placement configuration.
* Structure is documented below.
*/
groupPlacementPolicy?: pulumi.Input<inputs.compute.ResourcePolicyGroupPlacementPolicy>;
/**
* Resource policy for scheduling instance operations.
* Structure is documented below.
*/
instanceSchedulePolicy?: pulumi.Input<inputs.compute.ResourcePolicyInstanceSchedulePolicy>;
/**
* The name of the resource, provided by the client when initially creating
* the resource. The resource name must be 1-63 characters long, and comply
* with RFC1035. Specifically, the name must be 1-63 characters long and
* match the regular expression `a-z`? which means the
* first character must be a lowercase letter, and all following characters
* must be a dash, lowercase letter, or digit, except the last character,
* which cannot be a dash.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Region where resource policy resides.
*/
region?: pulumi.Input<string>;
/**
* Policy for creating snapshots of persistent disks.
* Structure is documented below.
*/
snapshotSchedulePolicy?: pulumi.Input<inputs.compute.ResourcePolicySnapshotSchedulePolicy>;
} | the_stack |
import Debug from 'debug'
import { v4 as uuidgen } from 'uuid'
import {
Arguments,
Evaluator,
ExecOptions,
KResponse,
isCommandHandlerWithEvents,
ParsedOptions,
withLanguage,
UsageError,
isUsageError,
CodedError,
ReplEval,
DirectReplEval,
ElementMimic
} from '@kui-shell/core'
import { isDisabled, config } from './config'
import { getSessionForTab } from '@kui-shell/plugin-bash-like'
const debug = Debug('plugins/proxy-support/executor')
/** we may want to directly evaluate certain commands in the browser */
const directEvaluator = new DirectReplEval()
function renderDom(content: ElementMimic): HTMLElement {
const dom = document.createElement(content.nodeType || 'span')
if (content.className.length > 0) {
dom.className = content.className
} else if (content.classList.classList.length > 0) {
content.classList.classList.forEach(_ => {
dom.classList.add(_)
})
}
// TODO attrs
if (content.innerText) {
dom.innerText = content.innerText
} else if (content.children && content.children.length > 0) {
content.children.forEach(child => {
dom.appendChild(renderDom(child))
})
}
return dom
}
/**
* A repl.exec implementation that proxies to the packages/proxy container
*
*/
class ProxyEvaluator implements ReplEval {
name = 'ProxyEvaluator'
/**
* The proxy server configuration.
*
*/
private readonly proxyServerConfig = config().then(_ => _.proxyServer)
async apply<T extends KResponse, O extends ParsedOptions>(
command: string,
execOptions: ExecOptions,
evaluator: Evaluator<T, O>,
args: Arguments<O>
): Promise<T> {
debug('apply', evaluator)
debug('execOptions', execOptions)
const proxyServerConfig = await this.proxyServerConfig
if (
isDisabled(proxyServerConfig) ||
(isCommandHandlerWithEvents(evaluator) && evaluator.options && !evaluator.options.requiresLocal)
) {
debug('delegating to direct evaluator')
return directEvaluator.apply(command, execOptions, evaluator, args)
} else {
const execOptionsForInvoke = withLanguage(
Object.assign({}, execOptions, {
block: undefined,
nextBlock: undefined,
isProxied: true,
cwd: process.env.PWD,
env:
process.env && execOptions.env
? { ...process.env, ...execOptions.env }
: execOptions.env
? execOptions.env
: process.env,
tab: undefined, // override execOptions.tab here since the DOM doesn't serialize, see issue: https://github.com/IBM/kui/issues/1649
rawResponse: true // we will post-process the response
})
)
if (command !== 'bash websocket open') {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
const uuid = uuidgen()
debug('delegating to proxy websocket', command, uuid)
const channel = await getSessionForTab(args.tab)
const isStreamingConsumer = execOptions.onInit !== undefined
const msg = {
type: 'request',
cmdline: command,
uuid,
stream: isStreamingConsumer,
cwd: process.env.PWD,
execOptions: execOptionsForInvoke
}
const stdout = execOptions.onInit
? await execOptions.onInit({
write: (data: string) => channel.send(JSON.stringify({ type: 'data', data, uuid })),
xon: () => {
debug('xon requested on streaming proxy exec')
channel.send(JSON.stringify({ type: 'xon', uuid }))
},
xoff: () => {
debug('xoff requested on streaming proxy exec')
channel.send(JSON.stringify({ type: 'xoff', uuid }))
},
abort: () => {
debug('abort requested on streaming proxy exec')
channel.send(JSON.stringify({ type: 'kill', uuid }))
}
})
: undefined
channel.send(JSON.stringify(msg))
const MARKER = '\n'
let raw = ''
const onMessage = (msg: { data: string }) => {
const { data } = msg
// debug('raw', uuid, data)
raw += data
if (data.endsWith(MARKER)) {
try {
const toBeProcessed = raw
raw = ''
toBeProcessed
.split(MARKER)
.filter(_ => _)
.forEach(_ => {
const response:
| { type: 'chunk'; uuid: string; chunk: string }
| {
type: 'object'
uuid: string
response: {
code?: number
statusCode?: number
message?: string
stack?: string
content: string | HTMLElement | ElementMimic
}
} = JSON.parse(_)
if (response.uuid === uuid) {
if (response.type === 'chunk') {
// we got a streaming chunk back
stdout(response.chunk)
return
}
channel.removeEventListener('message', onMessage)
const code = response.response.code || response.response.statusCode
if (execOptions.onExit) {
execOptions.onExit(code)
}
if (code !== undefined && code !== 200) {
if (isUsageError(response.response)) {
// e.g. k get -h
debug('rejecting as usage error', response)
reject(response.response)
} else {
// e.g. k get pod nonExistantName
debug('rejecting as other error', response)
const err: CodedError = new Error(response.response.message)
err.stack = response.response.stack
err.code = code
// see https://github.com/IBM/kui/issues/3318
err.statusCode =
response.response.statusCode !== undefined ? response.response.statusCode : code
err.body = response.response
reject(err)
}
} else if (ElementMimic.isFakeDom(response.response)) {
debug('rendering fakedom', response.response)
resolve(renderDom(response.response) as T)
} else if (ElementMimic.isFakeDom(response.response.content)) {
debug('rendering fakedom content', response.response.content)
response.response.content = renderDom(response.response.content)
resolve(response.response as T)
} else if (response.response.message && response.response.stack) {
const err = new Error(response.response.message)
err.stack = response.response.stack
reject(err)
} else {
debug('response', response)
resolve(response.response as T)
}
}
})
} catch (err) {
console.error('error handling response', raw)
console.error(err)
reject(new Error('Internal Error'))
}
}
}
channel.on('message', onMessage)
})
}
debug('delegating to proxy exec', command)
const body = {
command,
execOptions: execOptionsForInvoke
}
debug('sending body', body)
try {
const proxyHref = /KUI_PROXY_COHOSTED=true/.test(document.cookie)
? `${window.location.pathname.replace(/index\.html/, '')}exec${window.location.search}`
: new URL(proxyServerConfig.url, window.location.origin).href + window.location.search
debug('proxy server url', proxyHref)
const invokeRemote = () =>
new Promise(resolve => {
const xhr = new XMLHttpRequest()
xhr.open('POST', proxyHref)
xhr.responseType = 'json'
xhr.withCredentials = true
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.setRequestHeader('Accept', 'application/json')
xhr.addEventListener('error', () => {
if (xhr.readyState === 4 && xhr.status === 0) {
// this means connection refused or other inability to connect to the proxy server
resolve({
statusCode: 503,
code: 503,
body: 'Connection refused'
})
} else {
console.error('error in xhr', xhr.status, xhr)
resolve(xhr.response || 'Internal Error')
}
})
xhr.addEventListener('load', () => {
if (xhr.status === 401 || xhr.status === 403) {
alert('You do not have access to this resource')
const { homepage } = require('@kui-shell/client/package.json')
if (homepage) {
window.location.href = homepage
} else {
// some default...
window.location.href = 'https://google.com'
}
}
resolve({
statusCode: xhr.status,
body: xhr.response ? xhr.response.response : xhr.statusText
})
})
// proxyServerConfig.needleOptions
xhr.send(JSON.stringify(body))
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const response: { statusCode: number; body: Record<string, any> | string | ElementMimic } = await (window[
'webview-proxy'
]
? window['webview-proxy'](body)
: invokeRemote())
// debug('response', response)
if (response.statusCode !== 200) {
debug('rethrowing non-200 response', response)
// to trigger the catch just below
const err: CodedError = new Error(response.body as string)
err.code = err.statusCode = response.statusCode
err.body = response.body
throw err
} else {
/*
* try to unwind the fakedom for now
* TODO: we need a type guard to prevent fakedom object being passed to the proxy executor
* see related issue: https://github.com/IBM/kui/issues/1687
*
*/
if (ElementMimic.isFakeDom(response.body)) {
debug('catch a fakedom, try to unwind')
if (response.body.innerText) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (response.body.innerText as any) as T
} else {
const err = new Error('Internal Error: Fakedom objects are not accepted by proxy executor')
err['code'] = 500
throw err
}
}
return response.body as T
}
} catch (err) {
debug(
'proxy execution resulted in an error, recasting to local exception',
err.code,
err.message,
err.body,
err
)
if (err.body && isUsageError(err.body)) {
debug('the error is a usage error, rethrowing as such')
throw new UsageError({
message: err.body.raw.message,
usage: err.body.raw.usage,
code: err.body.code,
extra: err.body.extra
})
} else {
const error: CodedError = new Error(
(err.body && err.body.message) ||
(typeof err.body === 'string' ? err.body : err.message || 'Internal error')
)
error.code = error.statusCode = (err.body && err.body.code) || err.code || err.statusCode
debug('using this code', error.code)
throw error
}
}
}
}
}
export default ProxyEvaluator | the_stack |
import Hammer from '@egjs/hammerjs';
import { findNodeHandle } from 'react-native';
import { State } from '../State';
import { EventMap } from './constants';
import * as NodeManager from './NodeManager';
// TODO(TS) Replace with HammerInput if https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438/files is merged
export type HammerInputExt = Omit<HammerInput, 'destroy' | 'handler' | 'init'>;
export type Config = Partial<{
enabled: boolean;
minPointers: number;
maxPointers: number;
minDist: number;
minDistSq: number;
minVelocity: number;
minVelocitySq: number;
maxDist: number;
maxDistSq: number;
failOffsetXStart: number;
failOffsetYStart: number;
failOffsetXEnd: number;
failOffsetYEnd: number;
activeOffsetXStart: number;
activeOffsetXEnd: number;
activeOffsetYStart: number;
activeOffsetYEnd: number;
waitFor: any[] | null;
}>;
type NativeEvent = ReturnType<GestureHandler['transformEventData']>;
let gestureInstances = 0;
abstract class GestureHandler {
public handlerTag: any;
public isGestureRunning = false;
public view: number | null = null;
protected hasCustomActivationCriteria: boolean;
protected hasGestureFailed = false;
protected hammer: HammerManager | null = null;
protected initialRotation: number | null = null;
protected __initialX: any;
protected __initialY: any;
protected config: Config = {};
protected previousState: State = State.UNDETERMINED;
private pendingGestures: Record<string, this> = {};
private oldState: State = State.UNDETERMINED;
private lastSentState: State | null = null;
private gestureInstance: number;
private _stillWaiting: any;
private propsRef: any;
private ref: any;
abstract get name(): string;
get id() {
return `${this.name}${this.gestureInstance}`;
}
get isDiscrete() {
return false;
}
get shouldEnableGestureOnSetup(): boolean {
throw new Error('Must override GestureHandler.shouldEnableGestureOnSetup');
}
constructor() {
this.gestureInstance = gestureInstances++;
this.hasCustomActivationCriteria = false;
}
getConfig() {
return this.config;
}
onWaitingEnded(_gesture: this) {}
removePendingGesture(id: string) {
delete this.pendingGestures[id];
}
addPendingGesture(gesture: this) {
this.pendingGestures[gesture.id] = gesture;
}
isGestureEnabledForEvent(
_config: any,
_recognizer: any,
_event: any
): { failed?: boolean; success?: boolean } {
return { success: true };
}
get NativeGestureClass(): RecognizerStatic {
throw new Error('Must override GestureHandler.NativeGestureClass');
}
updateHasCustomActivationCriteria(_config: Config) {
return true;
}
clearSelfAsPending = () => {
if (Array.isArray(this.config.waitFor)) {
for (const gesture of this.config.waitFor) {
gesture.removePendingGesture(this.id);
}
}
};
updateGestureConfig({ enabled = true, ...props }) {
this.clearSelfAsPending();
this.config = ensureConfig({ enabled, ...props });
this.hasCustomActivationCriteria = this.updateHasCustomActivationCriteria(
this.config
);
if (Array.isArray(this.config.waitFor)) {
for (const gesture of this.config.waitFor) {
gesture.addPendingGesture(this);
}
}
if (this.hammer) {
this.sync();
}
return this.config;
}
destroy = () => {
this.clearSelfAsPending();
if (this.hammer) {
this.hammer.stop(false);
this.hammer.destroy();
}
this.hammer = null;
};
isPointInView = ({ x, y }: { x: number; y: number }) => {
// @ts-ignore FIXME(TS)
const rect = this.view!.getBoundingClientRect();
const pointerInside =
x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
return pointerInside;
};
getState(type: keyof typeof EventMap): State {
// @ts-ignore TODO(TS) check if this is needed
if (type == 0) {
return 0;
}
return EventMap[type];
}
transformEventData(event: HammerInputExt) {
const { eventType, maxPointers: numberOfPointers } = event;
// const direction = DirectionMap[ev.direction];
const changedTouch = event.changedPointers[0];
const pointerInside = this.isPointInView({
x: changedTouch.clientX,
y: changedTouch.clientY,
});
// TODO(TS) Remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50966 is merged.
const state = this.getState(eventType as 1 | 2 | 4 | 8);
if (state !== this.previousState) {
this.oldState = this.previousState;
this.previousState = state;
}
return {
nativeEvent: {
numberOfPointers,
state,
pointerInside,
...this.transformNativeEvent(event),
// onHandlerStateChange only
handlerTag: this.handlerTag,
target: this.ref,
oldState: this.oldState,
},
timeStamp: Date.now(),
};
}
transformNativeEvent(_event: HammerInputExt) {
return {};
}
sendEvent = (nativeEvent: HammerInputExt) => {
const {
onGestureHandlerEvent,
onGestureHandlerStateChange,
} = this.propsRef.current;
const event = this.transformEventData(nativeEvent);
invokeNullableMethod(onGestureHandlerEvent, event);
if (this.lastSentState !== event.nativeEvent.state) {
this.lastSentState = event.nativeEvent.state as State;
invokeNullableMethod(onGestureHandlerStateChange, event);
}
};
cancelPendingGestures(event: HammerInputExt) {
for (const gesture of Object.values(this.pendingGestures)) {
if (gesture && gesture.isGestureRunning) {
gesture.hasGestureFailed = true;
gesture.cancelEvent(event);
}
}
}
notifyPendingGestures() {
for (const gesture of Object.values(this.pendingGestures)) {
if (gesture) {
gesture.onWaitingEnded(this);
}
}
}
// FIXME event is undefined in runtime when firstly invoked (see Draggable example), check other functions taking event as input
onGestureEnded(event: HammerInputExt) {
this.isGestureRunning = false;
this.cancelPendingGestures(event);
}
forceInvalidate(event: HammerInputExt) {
if (this.isGestureRunning) {
this.hasGestureFailed = true;
this.cancelEvent(event);
}
}
cancelEvent(event: HammerInputExt) {
this.notifyPendingGestures();
this.sendEvent({
...event,
eventType: Hammer.INPUT_CANCEL,
isFinal: true,
});
this.onGestureEnded(event);
}
onRawEvent({ isFirst }: HammerInputExt) {
if (isFirst) {
this.hasGestureFailed = false;
}
}
setView(ref: Parameters<typeof findNodeHandle>['0'], propsRef: any) {
if (ref == null) {
this.destroy();
this.view = null;
return;
}
this.propsRef = propsRef;
this.ref = ref;
this.view = findNodeHandle(ref);
this.hammer = new Hammer.Manager(this.view as any);
this.oldState = State.UNDETERMINED;
this.previousState = State.UNDETERMINED;
this.lastSentState = null;
const { NativeGestureClass } = this;
// @ts-ignore TODO(TS)
const gesture = new NativeGestureClass(this.getHammerConfig());
this.hammer.add(gesture);
this.hammer.on('hammer.input', (ev: HammerInput) => {
if (!this.config.enabled) {
this.hasGestureFailed = false;
this.isGestureRunning = false;
return;
}
this.onRawEvent((ev as unknown) as HammerInputExt);
// TODO: Bacon: Check against something other than null
// The isFirst value is not called when the first rotation is calculated.
if (this.initialRotation === null && ev.rotation !== 0) {
this.initialRotation = ev.rotation;
}
if (ev.isFinal) {
// in favor of a willFail otherwise the last frame of the gesture will be captured.
setTimeout(() => {
this.initialRotation = null;
this.hasGestureFailed = false;
});
}
});
this.setupEvents();
this.sync();
}
setupEvents() {
// TODO(TS) Hammer types aren't exactly that what we get in runtime
if (!this.isDiscrete) {
this.hammer!.on(`${this.name}start`, (event: HammerInput) =>
this.onStart((event as unknown) as HammerInputExt)
);
this.hammer!.on(
`${this.name}end ${this.name}cancel`,
(event: HammerInput) => {
this.onGestureEnded((event as unknown) as HammerInputExt);
}
);
}
this.hammer!.on(this.name, (ev: HammerInput) =>
this.onGestureActivated((ev as unknown) as HammerInputExt)
); // TODO(TS) remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438 is merged
}
onStart({ deltaX, deltaY, rotation }: HammerInputExt) {
// Reset the state for the next gesture
this.oldState = State.UNDETERMINED;
this.previousState = State.UNDETERMINED;
this.lastSentState = null;
this.isGestureRunning = true;
this.__initialX = deltaX;
this.__initialY = deltaY;
this.initialRotation = rotation;
}
onGestureActivated(ev: HammerInputExt) {
this.sendEvent(ev);
}
onSuccess() {}
_getPendingGestures() {
if (Array.isArray(this.config.waitFor) && this.config.waitFor.length) {
// Get the list of gestures that this gesture is still waiting for.
// Use `=== false` in case a ref that isn't a gesture handler is used.
const stillWaiting = this.config.waitFor.filter(
({ hasGestureFailed }) => hasGestureFailed === false
);
return stillWaiting;
}
return [];
}
getHammerConfig() {
const pointers =
this.config.minPointers === this.config.maxPointers
? this.config.minPointers
: 0;
return {
pointers,
};
}
sync = () => {
const gesture = this.hammer!.get(this.name);
if (!gesture) return;
const enable = (recognizer: any, inputData: any) => {
if (!this.config.enabled) {
this.isGestureRunning = false;
this.hasGestureFailed = false;
return false;
}
// Prevent events before the system is ready.
if (
!inputData ||
!recognizer.options ||
typeof inputData.maxPointers === 'undefined'
) {
return this.shouldEnableGestureOnSetup;
}
if (this.hasGestureFailed) {
return false;
}
if (!this.isDiscrete) {
if (this.isGestureRunning) {
return true;
}
// The built-in hammer.js "waitFor" doesn't work across multiple views.
// Only process if there are views to wait for.
this._stillWaiting = this._getPendingGestures();
// This gesture should continue waiting.
if (this._stillWaiting.length) {
// Check to see if one of the gestures you're waiting for has started.
// If it has then the gesture should fail.
for (const gesture of this._stillWaiting) {
// When the target gesture has started, this gesture must force fail.
if (!gesture.isDiscrete && gesture.isGestureRunning) {
this.hasGestureFailed = true;
this.isGestureRunning = false;
return false;
}
}
// This gesture shouldn't start until the others have finished.
return false;
}
}
// Use default behaviour
if (!this.hasCustomActivationCriteria) {
return true;
}
const deltaRotation =
this.initialRotation == null
? 0
: inputData.rotation - this.initialRotation;
// @ts-ignore FIXME(TS)
const { success, failed } = this.isGestureEnabledForEvent(
this.getConfig(),
recognizer,
{
...inputData,
deltaRotation,
}
);
if (failed) {
this.simulateCancelEvent(inputData);
this.hasGestureFailed = true;
}
return success;
};
const params = this.getHammerConfig();
// @ts-ignore FIXME(TS)
gesture.set({ ...params, enable });
};
simulateCancelEvent(_inputData: any) {}
}
// TODO(TS) investigate this method
// Used for sending data to a callback or AnimatedEvent
function invokeNullableMethod(
method:
| ((event: NativeEvent) => void)
| { __getHandler: () => (event: NativeEvent) => void }
| { __nodeConfig: { argMapping: any } },
event: NativeEvent
) {
if (method) {
if (typeof method === 'function') {
method(event);
} else {
// For use with reanimated's AnimatedEvent
if (
'__getHandler' in method &&
typeof method.__getHandler === 'function'
) {
const handler = method.__getHandler();
invokeNullableMethod(handler, event);
} else {
if ('__nodeConfig' in method) {
const { argMapping } = method.__nodeConfig;
if (Array.isArray(argMapping)) {
for (const [index, [key, value]] of argMapping.entries()) {
if (key in event.nativeEvent) {
// @ts-ignore fix method type
const nativeValue = event.nativeEvent[key];
if (value && value.setValue) {
// Reanimated API
value.setValue(nativeValue);
} else {
// RN Animated API
method.__nodeConfig.argMapping[index] = [key, nativeValue];
}
}
}
}
}
}
}
}
}
// Validate the props
function ensureConfig(config: Config): Required<Config> {
const props = { ...config };
// TODO(TS) We use ! to assert that if property is present then value is not empty (null, undefined)
if ('minDist' in config) {
props.minDist = config.minDist;
props.minDistSq = props.minDist! * props.minDist!;
}
if ('minVelocity' in config) {
props.minVelocity = config.minVelocity;
props.minVelocitySq = props.minVelocity! * props.minVelocity!;
}
if ('maxDist' in config) {
props.maxDist = config.maxDist;
props.maxDistSq = config.maxDist! * config.maxDist!;
}
if ('waitFor' in config) {
props.waitFor = asArray(config.waitFor)
.map(({ handlerTag }: { handlerTag: number }) =>
NodeManager.getHandler(handlerTag)
)
.filter((v) => v);
} else {
props.waitFor = null;
}
const configProps = [
'minPointers',
'maxPointers',
'minDist',
'maxDist',
'maxDistSq',
'minVelocitySq',
'minDistSq',
'minVelocity',
'failOffsetXStart',
'failOffsetYStart',
'failOffsetXEnd',
'failOffsetYEnd',
'activeOffsetXStart',
'activeOffsetXEnd',
'activeOffsetYStart',
'activeOffsetYEnd',
] as const;
configProps.forEach((prop: typeof configProps[number]) => {
if (typeof props[prop] === 'undefined') {
props[prop] = Number.NaN;
}
});
return props as Required<Config>; // TODO(TS) how to convince TS that props are filled?
}
function asArray<T>(value: T | T[]) {
// TODO(TS) use config.waitFor type
return value == null ? [] : Array.isArray(value) ? value : [value];
}
export default GestureHandler; | the_stack |
import * as parts from "../parts";
import { debugMode } from "../settings";
import { Map } from "../utility/map";
const rules = new Map<string, (parent: ParseNode) => ParseNode>();
/**
* Parses a given string with the specified rule.
*
* @param {string} input The string to be parsed.
* @param {string} rule The rule to parse the string with
* @return {*} The value returned depends on the rule used.
*/
export function parse(input: string, rule: string): any {
/* tslint:disable-next-line:no-use-before-declare */
const { result } = new ParserRun(input, rule);
if (result === null || result.end !== input.length) {
if (debugMode) {
console.error("Parse failed. %s %s %o", rule, input, result);
}
throw new Error("Parse failed.");
}
return result.value;
}
/**
* This class represents a single parse node. It has a start and end position, and an optional value object.
*
* @param {ParseNode} parent The parent of this parse node.
* @param {*=null} value If provided, it is assigned as the value of the node.
*/
class ParseNode {
private _children: ParseNode[] = [];
private _start: number;
private _end: number;
private _value: any;
constructor(private _parent: ParseNode | null, value: any = null) {
if (_parent !== null) {
_parent.children.push(this);
}
this._start = ((_parent !== null) ? _parent.end : 0);
this._end = this._start;
this.value = value;
}
/**
* The start position of this parse node.
*
* @type {number}
*/
get start(): number {
return this._start;
}
/**
* The end position of this parse node.
*
* @type {number}
*/
get end(): number {
return this._end;
}
/**
* @type {ParseNode}
*/
get parent(): ParseNode | null {
return this._parent;
}
/**
* @type {!Array.<!ParseNode>}
*/
get children(): ParseNode[] {
return this._children;
}
/**
* An optional object associated with this parse node.
*
* @type {*}
*/
get value(): any {
return this._value;
}
/**
* An optional object associated with this parse node.
*
* If the value is a string, then the end property is updated to be the length of the string.
*
* @type {*}
*/
set value(newValue: any) {
this._value = newValue;
if (this._value !== null && this._value.constructor === String && this._children.length === 0) {
this._setEnd(this._start + (this._value as string).length);
}
}
/**
* Removes the last child of this node and updates the end position to be end position of the new last child.
*/
pop(): void {
this._children.splice(this._children.length - 1, 1);
if (this._children.length > 0) {
this._setEnd(this._children[this._children.length - 1].end);
}
else {
this._setEnd(this.start);
}
}
/**
* Updates the end property of this node and its parent recursively to the root node.
*
* @param {number} newEnd
*/
private _setEnd(newEnd: number): void {
this._end = newEnd;
if (this._parent !== null && this._parent.end !== this._end) {
this._parent._setEnd(this._end);
}
}
}
/**
* This class represents a single run of the parser.
*
* @param {string} input
* @param {string} rule
*/
class ParserRun {
private _parseTree: ParseNode;
private _result: ParseNode;
constructor(private _input: string, rule: string) {
const ruleFunction = rules.get(rule);
if (ruleFunction === undefined) {
throw new Error(`Could not find parser rule named ${ rule }`);
}
this._parseTree = new ParseNode(null);
this._result = ruleFunction.call(this, this._parseTree);
}
/**
* @type {ParseNode}
*/
get result(): ParseNode | null {
return this._result;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_dialogueParts(parent: ParseNode): ParseNode {
const current = new ParseNode(parent);
current.value = [];
while (this._haveMore()) {
const enclosedTagsNode = this.parse_enclosedTags(current);
if (enclosedTagsNode !== null) {
current.value.push(...enclosedTagsNode.value);
}
else {
const whiteSpaceOrTextNode = this.parse_newline(current) || this.parse_soft_newline(current) || this.parse_hardspace(current) || this.parse_text(current);
if (whiteSpaceOrTextNode.value instanceof parts.Text && current.value[current.value.length - 1] instanceof parts.Text) {
// Merge consecutive text parts into one part
const previousTextPart = current.value[current.value.length - 1] as parts.Text;
current.value[current.value.length - 1] = new parts.Text(previousTextPart.value + (whiteSpaceOrTextNode.value as parts.Text).value);
}
else {
current.value.push(whiteSpaceOrTextNode.value);
}
}
}
let inDrawingMode = false;
current.value.forEach((part: parts.Part, i: number) => {
if (part instanceof parts.DrawingMode) {
inDrawingMode = part.scale !== 0;
}
else if (part instanceof parts.Text && inDrawingMode) {
current.value[i] = new parts.DrawingInstructions(parse(part.value, "drawingInstructions") as parts.drawing.Instruction[]);
}
});
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_enclosedTags(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
current.value = [];
if (this.read(current, "{") === null) {
parent.pop();
return null;
}
for (let next = this._peek(); this._haveMore() && next !== "}"; next = this._peek()) {
let childNode: ParseNode | null = null;
if (this.read(current, "\\") !== null) {
childNode =
this.parse_tag_alpha(current) ||
this.parse_tag_iclip(current) ||
this.parse_tag_xbord(current) ||
this.parse_tag_ybord(current) ||
this.parse_tag_xshad(current) ||
this.parse_tag_yshad(current) ||
this.parse_tag_blur(current) ||
this.parse_tag_bord(current) ||
this.parse_tag_clip(current) ||
this.parse_tag_fade(current) ||
this.parse_tag_fscx(current) ||
this.parse_tag_fscy(current) ||
this.parse_tag_move(current) ||
this.parse_tag_shad(current) ||
this.parse_tag_fad(current) ||
this.parse_tag_fax(current) ||
this.parse_tag_fay(current) ||
this.parse_tag_frx(current) ||
this.parse_tag_fry(current) ||
this.parse_tag_frz(current) ||
this.parse_tag_fsp(current) ||
this.parse_tag_fsplus(current) ||
this.parse_tag_fsminus(current) ||
this.parse_tag_org(current) ||
this.parse_tag_pbo(current) ||
this.parse_tag_pos(current) ||
this.parse_tag_an(current) ||
this.parse_tag_be(current) ||
this.parse_tag_fn(current) ||
this.parse_tag_fr(current) ||
this.parse_tag_fs(current) ||
this.parse_tag_kf(current) ||
this.parse_tag_ko(current) ||
this.parse_tag_1a(current) ||
this.parse_tag_1c(current) ||
this.parse_tag_2a(current) ||
this.parse_tag_2c(current) ||
this.parse_tag_3a(current) ||
this.parse_tag_3c(current) ||
this.parse_tag_4a(current) ||
this.parse_tag_4c(current) ||
this.parse_tag_a(current) ||
this.parse_tag_b(current) ||
this.parse_tag_c(current) ||
this.parse_tag_i(current) ||
this.parse_tag_k(current) ||
this.parse_tag_K(current) ||
this.parse_tag_p(current) ||
this.parse_tag_q(current) ||
this.parse_tag_r(current) ||
this.parse_tag_s(current) ||
this.parse_tag_t(current) ||
this.parse_tag_u(current);
if (childNode === null) {
current.pop(); // Unread backslash
}
}
if (childNode === null) {
childNode = this.parse_comment(current);
}
if (childNode.value instanceof parts.Comment && current.value[current.value.length - 1] instanceof parts.Comment) {
// Merge consecutive comment parts into one part
current.value[current.value.length - 1] =
new parts.Comment(
(current.value[current.value.length - 1] as parts.Comment).value +
(childNode.value as parts.Comment).value,
);
}
else {
current.value.push(childNode.value);
}
}
if (this.read(current, "}") === null) {
parent.pop();
return null;
}
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_newline(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "\\N") === null) {
parent.pop();
return null;
}
current.value = new parts.NewLine();
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_soft_newline(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "\\n") === null) {
parent.pop();
return null;
}
current.value = new parts.SoftNewLine();
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_hardspace(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "\\h") === null) {
parent.pop();
return null;
}
current.value = new parts.Text("\u00A0");
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_text(parent: ParseNode): ParseNode {
const value = this._peek();
const current = new ParseNode(parent);
const valueNode = new ParseNode(current, value);
current.value = new parts.Text(valueNode.value);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_comment(parent: ParseNode): ParseNode {
const value = this._peek();
const current = new ParseNode(parent);
const valueNode = new ParseNode(current, value);
current.value = new parts.Comment(valueNode.value);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_a(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "a") === null) {
parent.pop();
return null;
}
let next = this._peek();
switch (next) {
case "1":
const next2 = this._peek(2);
switch (next2) {
case "10":
case "11":
next = next2;
break;
}
break;
case "2":
case "3":
case "5":
case "6":
case "7":
case "9":
break;
default:
parent.pop();
return null;
}
const valueNode = new ParseNode(current, next);
let value: number = -1;
switch ((valueNode.value)) {
case "1":
value = 1;
break;
case "2":
value = 2;
break;
case "3":
value = 3;
break;
case "5":
value = 7;
break;
case "6":
value = 8;
break;
case "7":
value = 9;
break;
case "9":
value = 4;
break;
case "10":
value = 5;
break;
case "11":
value = 6;
break;
}
current.value = new parts.Alignment(value);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_alpha(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_an(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "an") === null) {
parent.pop();
return null;
}
const next = this._peek();
if (next < "1" || next > "9") {
parent.pop();
return null;
}
const valueNode = new ParseNode(current, next);
current.value = new parts.Alignment(parseInt(valueNode.value));
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_b(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "b") === null) {
parent.pop();
return null;
}
let valueNode: ParseNode | null = null;
let next = this._peek();
if (next >= "1" && next <= "9") {
next = this._peek(3);
if (next.substr(1) === "00") {
valueNode = new ParseNode(current, next);
valueNode.value = parseInt(valueNode.value);
}
}
if (valueNode === null) {
valueNode = this.parse_enableDisable(current);
}
if (valueNode !== null) {
current.value = new parts.Bold(valueNode.value);
}
else {
current.value = new parts.Bold(null);
}
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_be(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_blur(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_bord(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_c(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_clip(parent: ParseNode): ParseNode | null {
return this._parse_tag_clip_or_iclip("clip", parent);
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fad(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "fad") === null) {
parent.pop();
return null;
}
if (this.read(current, "(") === null) {
parent.pop();
return null;
}
const startNode = this.parse_decimal(current);
if (startNode === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const endNode = this.parse_decimal(current);
if (endNode === null) {
parent.pop();
return null;
}
if (this.read(current, ")") === null) {
parent.pop();
return null;
}
current.value = new parts.Fade(startNode.value / 1000, endNode.value / 1000);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fade(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "fade") === null) {
parent.pop();
return null;
}
if (this.read(current, "(") === null) {
parent.pop();
return null;
}
const a1Node = this.parse_decimal(current);
if (a1Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const a2Node = this.parse_decimal(current);
if (a2Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const a3Node = this.parse_decimal(current);
if (a3Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const t1Node = this.parse_decimal(current);
if (t1Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const t2Node = this.parse_decimal(current);
if (t2Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const t3Node = this.parse_decimal(current);
if (t3Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const t4Node = this.parse_decimal(current);
if (t4Node === null) {
parent.pop();
return null;
}
if (this.read(current, ")") === null) {
parent.pop();
return null;
}
current.value =
new parts.ComplexFade(
1 - a1Node.value / 255, 1 - a2Node.value / 255, 1 - a3Node.value / 255,
t1Node.value / 1000, t2Node.value / 1000, t3Node.value / 1000, t4Node.value / 1000,
);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fax(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fay(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fn(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "fn") === null) {
parent.pop();
return null;
}
const valueNode = new ParseNode(current, "");
for (let next = this._peek(); this._haveMore() && next !== "\\" && next !== "}"; next = this._peek()) {
valueNode.value += next;
}
if (valueNode.value.length > 0) {
current.value = new parts.FontName(valueNode.value);
}
else {
current.value = new parts.FontName(null);
}
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fr(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_frx(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fry(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_frz(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fs(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fsplus(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "fs+") === null) {
parent.pop();
return null;
}
const valueNode = this.parse_decimal(current);
if (valueNode === null) {
parent.pop();
return null;
}
current.value = new parts.FontSizePlus(valueNode.value / 10);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fsminus(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "fs-") === null) {
parent.pop();
return null;
}
const valueNode = this.parse_decimal(current);
if (valueNode === null) {
parent.pop();
return null;
}
current.value = new parts.FontSizeMinus(valueNode.value / 10);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fscx(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "fscx") === null) {
parent.pop();
return null;
}
const valueNode = this.parse_decimal(current);
if (valueNode !== null) {
current.value = new parts.FontScaleX(valueNode.value / 100);
}
else {
current.value = new parts.FontScaleX(null);
}
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fscy(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "fscy") === null) {
parent.pop();
return null;
}
const valueNode = this.parse_decimal(current);
if (valueNode !== null) {
current.value = new parts.FontScaleY(valueNode.value / 100);
}
else {
current.value = new parts.FontScaleY(null);
}
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_fsp(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_i(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_iclip(parent: ParseNode): ParseNode | null {
return this._parse_tag_clip_or_iclip("iclip", parent);
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_k(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "k") === null) {
parent.pop();
return null;
}
const valueNode = this.parse_decimal(current);
if (valueNode === null) {
parent.pop();
return null;
}
current.value = new parts.ColorKaraoke(valueNode.value / 100);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_K(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "K") === null) {
parent.pop();
return null;
}
const valueNode = this.parse_decimal(current);
if (valueNode === null) {
parent.pop();
return null;
}
current.value = new parts.SweepingColorKaraoke(valueNode.value / 100);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_kf(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "kf") === null) {
parent.pop();
return null;
}
const valueNode = this.parse_decimal(current);
if (valueNode === null) {
parent.pop();
return null;
}
current.value = new parts.SweepingColorKaraoke(valueNode.value / 100);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_ko(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "ko") === null) {
parent.pop();
return null;
}
const valueNode = this.parse_decimal(current);
if (valueNode === null) {
parent.pop();
return null;
}
current.value = new parts.OutlineKaraoke(valueNode.value / 100);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_move(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "move") === null) {
parent.pop();
return null;
}
if (this.read(current, "(") === null) {
parent.pop();
return null;
}
const x1Node = this.parse_decimal(current);
if (x1Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const y1Node = this.parse_decimal(current);
if (y1Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const x2Node = this.parse_decimal(current);
if (x2Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const y2Node = this.parse_decimal(current);
if (y2Node === null) {
parent.pop();
return null;
}
let t1Node: ParseNode | null = null;
let t2Node: ParseNode | null = null;
if (this.read(current, ",") !== null) {
t1Node = this.parse_decimal(current);
if (t1Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
t2Node = this.parse_decimal(current);
if (t2Node === null) {
parent.pop();
return null;
}
}
if (this.read(current, ")") === null) {
parent.pop();
return null;
}
current.value = new parts.Move(
x1Node.value, y1Node.value, x2Node.value, y2Node.value,
(t1Node !== null) ? (t1Node.value / 1000) : null, (t2Node !== null) ? (t2Node.value / 1000) : null,
);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_org(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "org") === null) {
parent.pop();
return null;
}
if (this.read(current, "(") === null) {
parent.pop();
return null;
}
const xNode = this.parse_decimal(current);
if (xNode === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const yNode = this.parse_decimal(current);
if (yNode === null) {
parent.pop();
return null;
}
if (this.read(current, ")") === null) {
parent.pop();
return null;
}
current.value = new parts.RotationOrigin(xNode.value, yNode.value);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_p(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_pbo(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_pos(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "pos") === null) {
parent.pop();
return null;
}
if (this.read(current, "(") === null) {
parent.pop();
return null;
}
const xNode = this.parse_decimal(current);
if (xNode === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const yNode = this.parse_decimal(current);
if (yNode === null) {
parent.pop();
return null;
}
if (this.read(current, ")") === null) {
parent.pop();
return null;
}
current.value = new parts.Position(xNode.value, yNode.value);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_q(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "q") === null) {
parent.pop();
return null;
}
const next = this._peek();
if (next < "0" || next > "3") {
parent.pop();
return null;
}
const valueNode = new ParseNode(current, next);
current.value = new parts.WrappingStyle(parseInt(valueNode.value));
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_r(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "r") === null) {
parent.pop();
return null;
}
const valueNode = new ParseNode(current, "");
for (let next = this._peek(); this._haveMore() && next !== "\\" && next !== "}"; next = this._peek()) {
valueNode.value += next;
}
if (valueNode.value.length > 0) {
current.value = new parts.Reset(valueNode.value);
}
else {
current.value = new parts.Reset(null);
}
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_s(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_shad(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_t(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, "t") === null) {
parent.pop();
return null;
}
if (this.read(current, "(") === null) {
parent.pop();
return null;
}
let startNode: ParseNode | null = null;
let endNode: ParseNode | null = null;
let accelNode: ParseNode | null = null;
const firstNode = this.parse_decimal(current);
if (firstNode !== null) {
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const secondNode = this.parse_decimal(current);
if (secondNode !== null) {
startNode = firstNode;
endNode = secondNode;
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const thirdNode = this.parse_decimal(current);
if (thirdNode !== null) {
accelNode = thirdNode;
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
}
}
else {
accelNode = firstNode;
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
}
}
const transformTags: parts.Part[] = [];
for (let next = this._peek(); this._haveMore() && next !== ")" && next !== "}"; next = this._peek()) {
let childNode: ParseNode | null = null;
if (this.read(current, "\\") !== null) {
childNode =
this.parse_tag_alpha(current) ||
this.parse_tag_iclip(current) ||
this.parse_tag_xbord(current) ||
this.parse_tag_ybord(current) ||
this.parse_tag_xshad(current) ||
this.parse_tag_yshad(current) ||
this.parse_tag_blur(current) ||
this.parse_tag_bord(current) ||
this.parse_tag_clip(current) ||
this.parse_tag_fscx(current) ||
this.parse_tag_fscy(current) ||
this.parse_tag_shad(current) ||
this.parse_tag_fax(current) ||
this.parse_tag_fay(current) ||
this.parse_tag_frx(current) ||
this.parse_tag_fry(current) ||
this.parse_tag_frz(current) ||
this.parse_tag_fsp(current) ||
this.parse_tag_fsplus(current) ||
this.parse_tag_fsminus(current) ||
this.parse_tag_be(current) ||
this.parse_tag_fr(current) ||
this.parse_tag_fs(current) ||
this.parse_tag_1a(current) ||
this.parse_tag_1c(current) ||
this.parse_tag_2a(current) ||
this.parse_tag_2c(current) ||
this.parse_tag_3a(current) ||
this.parse_tag_3c(current) ||
this.parse_tag_4a(current) ||
this.parse_tag_4c(current) ||
this.parse_tag_c(current);
if (childNode === null) {
current.pop(); // Unread backslash
}
}
if (childNode === null) {
childNode = this.parse_comment(current);
}
if (childNode.value instanceof parts.Comment && transformTags[transformTags.length - 1] instanceof parts.Comment) {
// Merge consecutive comment parts into one part
transformTags[transformTags.length - 1] =
new parts.Comment(
(transformTags[transformTags.length - 1] as parts.Comment).value +
(childNode.value as parts.Comment).value,
);
}
else {
transformTags.push(childNode.value);
}
}
this.read(current, ")");
current.value =
new parts.Transform(
(startNode !== null) ? (startNode.value / 1000) : null,
(endNode !== null) ? (endNode.value / 1000) : null,
(accelNode !== null) ? (accelNode.value / 1000) : null,
transformTags,
);
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_u(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_xbord(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_xshad(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_ybord(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_yshad(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_1a(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_1c(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_2a(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_2c(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_3a(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_3c(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_4a(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_tag_4c(_parent: ParseNode): ParseNode | null {
throw new Error("unreachable");
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_drawingInstructions(parent: ParseNode): ParseNode {
const current = new ParseNode(parent);
let currentType: string | null = null;
const numberParts: ParseNode[] = [];
current.value = [];
while (this._haveMore()) {
while (this.read(current, " ") !== null) { }
if (!this._haveMore()) {
break;
}
if (currentType !== null) {
const numberPart = this.parse_decimal(current);
if (numberPart !== null) {
numberParts.push(numberPart);
if (currentType === "m" && numberParts.length === 2) {
current.value.push(new parts.drawing.MoveInstruction(numberParts[0].value, numberParts[1].value));
numberParts.splice(0, numberParts.length);
}
else if (currentType === "l" && numberParts.length === 2) {
current.value.push(new parts.drawing.LineInstruction(numberParts[0].value, numberParts[1].value));
numberParts.splice(0, numberParts.length);
}
else if (currentType === "b" && numberParts.length === 6) {
current.value.push(new parts.drawing.CubicBezierCurveInstruction(
numberParts[0].value, numberParts[1].value,
numberParts[2].value, numberParts[3].value,
numberParts[4].value, numberParts[5].value));
numberParts.splice(0, numberParts.length);
}
continue;
}
}
const typePart = this.parse_text(current);
const newType = (typePart.value as parts.Text).value;
switch (newType) {
case "m":
case "l":
case "b":
currentType = newType;
numberParts.splice(0, numberParts.length);
break;
}
}
while (this.read(current, " ") !== null) { }
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_decimalInt32(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
const isNegative = this.read(current, "-") !== null;
const numberNode = new ParseNode(current, "");
for (let next = this._peek(); this._haveMore() && next >= "0" && next <= "9"; next = this._peek()) {
numberNode.value += next;
}
if (numberNode.value.length === 0) {
parent.pop();
return null;
}
let value = parseInt(numberNode.value);
if (value >= 0xFFFFFFFF) {
value = 0xFFFFFFFF;
}
else if (isNegative) {
value = -value;
}
current.value = value;
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_hexInt32(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
const isNegative = this.read(current, "-") !== null;
const numberNode = new ParseNode(current, "");
for (
let next = this._peek();
this._haveMore() && (
(next >= "0" && next <= "9") ||
(next >= "a" && next <= "f") ||
(next >= "A" && next <= "F")
);
next = this._peek()) {
numberNode.value += next;
}
if (numberNode.value.length === 0) {
parent.pop();
return null;
}
let value = parseInt(numberNode.value, 16);
if (value >= 0xFFFFFFFF) {
value = 0xFFFFFFFF;
}
else if (isNegative) {
value = -value;
}
current.value = value;
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_decimalOrHexInt32(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
const valueNode =
(this.read(current, "&H") !== null || this.read(current, "&h") !== null) ?
this.parse_hexInt32(current) :
this.parse_decimalInt32(current);
if (valueNode === null) {
parent.pop();
return null;
}
current.value = valueNode.value;
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_decimal(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
const negative = (this.read(current, "-") !== null);
const numericalPart = this.parse_unsignedDecimal(current);
if (numericalPart === null) {
parent.pop();
return null;
}
current.value = numericalPart.value;
if (negative) {
current.value = -current.value;
}
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_unsignedDecimal(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
const characteristicNode = new ParseNode(current, "");
let mantissaNode: ParseNode | null = null;
for (let next = this._peek(); this._haveMore() && next >= "0" && next <= "9"; next = this._peek()) {
characteristicNode.value += next;
}
if (characteristicNode.value.length === 0) {
parent.pop();
return null;
}
if (this.read(current, ".") !== null) {
mantissaNode = new ParseNode(current, "");
for (let next = this._peek(); this._haveMore() && next >= "0" && next <= "9"; next = this._peek()) {
mantissaNode.value += next;
}
if (mantissaNode.value.length === 0) {
parent.pop();
return null;
}
}
current.value = parseFloat((characteristicNode.value as string) + ((mantissaNode !== null) ? ("." + (mantissaNode.value as string)) : ""));
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_enableDisable(parent: ParseNode): ParseNode | null {
const next = this._peek();
if (next === "0" || next === "1") {
const result = new ParseNode(parent, next);
result.value = (result.value === "1");
return result;
}
return null;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_color(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
while (this.read(current, "&") !== null || this.read(current, "H") !== null) { }
const valueNode = this.parse_hexInt32(current);
if (valueNode === null) {
parent.pop();
return null;
}
const value = valueNode.value;
/* tslint:disable:no-bitwise */
current.value = new parts.Color(
value & 0xFF,
(value >> 8) & 0xFF,
(value >> 16) & 0xFF,
);
/* tslint:enable:no-bitwise */
while (this.read(current, "&") !== null || this.read(current, "H") !== null) { }
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_alpha(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
while (this.read(current, "&") !== null || this.read(current, "H") !== null) { }
const valueNode = this.parse_hexInt32(current);
if (valueNode === null) {
parent.pop();
return null;
}
const value = valueNode.value;
/* tslint:disable-next-line:no-bitwise */
current.value = 1 - (value & 0xFF) / 0xFF;
while (this.read(current, "&") !== null || this.read(current, "H") !== null) { }
return current;
}
/**
* @param {!ParseNode} parent
* @return {ParseNode}
*/
parse_colorWithAlpha(parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
const valueNode = this.parse_decimalOrHexInt32(current);
if (valueNode === null) {
parent.pop();
return null;
}
const value = valueNode.value;
/* tslint:disable:no-bitwise */
current.value = new parts.Color(
value & 0xFF,
(value >> 8) & 0xFF,
(value >> 16) & 0xFF,
1 - ((value >> 24) & 0xFF) / 0xFF,
);
/* tslint:enable:no-bitwise */
return current;
}
/**
* @param {!ParseNode} parent
* @param {string} next
* @return {ParseNode}
*/
read(parent: ParseNode, next: string): ParseNode | null {
if (this._peek(next.length) !== next) {
return null;
}
return new ParseNode(parent, next);
}
/**
* @param {number=1} count
* @return {string}
*/
private _peek(count: number = 1): string {
// Fastpath for count === 1. http://jsperf.com/substr-vs-indexer
if (count === 1) { return this._input[this._parseTree.end]; }
return this._input.substr(this._parseTree.end, count);
}
/**
* @return {boolean}
*/
private _haveMore(): boolean {
return this._parseTree.end < this._input.length;
}
/**
* @param {string} tagName One of "clip" and "iclip"
* @param {!ParseNode} parent
* @return {ParseNode}
*/
private _parse_tag_clip_or_iclip(tagName: "clip" | "iclip", parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, tagName) === null) {
parent.pop();
return null;
}
if (this.read(current, "(") === null) {
parent.pop();
return null;
}
let x1Node: ParseNode | null = null;
let x2Node: ParseNode | null = null;
let y1Node: ParseNode | null = null;
let y2Node: ParseNode | null = null;
let scaleNode: ParseNode | null = null;
let commandsNode: ParseNode | null = null;
const firstNode = this.parse_decimal(current);
if (firstNode !== null) {
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
const secondNode = this.parse_decimal(current);
if (secondNode !== null) {
x1Node = firstNode;
y1Node = secondNode;
}
else {
scaleNode = firstNode;
}
}
if (x1Node !== null && y1Node !== null) {
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
x2Node = this.parse_decimal(current);
if (x2Node === null) {
parent.pop();
return null;
}
if (this.read(current, ",") === null) {
parent.pop();
return null;
}
y2Node = this.parse_decimal(current);
if (y2Node === null) {
parent.pop();
return null;
}
current.value = new parts.RectangularClip(x1Node.value, y1Node.value, x2Node.value, y2Node.value, tagName === "clip");
}
else {
commandsNode = new ParseNode(current, "");
for (let next = this._peek(); this._haveMore() && next !== ")" && next !== "}"; next = this._peek()) {
commandsNode.value += next;
}
current.value = new parts.VectorClip((scaleNode !== null) ? scaleNode.value : 1, parse(commandsNode.value, "drawingInstructions") as parts.drawing.Instruction[], tagName === "clip");
}
if (this.read(current, ")") === null) {
parent.pop();
return null;
}
return current;
}
}
/**
* Constructs a simple tag parser function and sets it on the prototype of the {@link ./parser/parse.ParserRun} class.
*
* @param {string} tagName The name of the tag to generate the parser function for
* @param {function(new: !libjass.parts.Part, *)} tagConstructor The type of tag to be returned by the generated parser function
* @param {function(!ParseNode): ParseNode} valueParser The parser for the tag's value
* @param {boolean} required Whether the tag's value is required or optional
*/
function makeTagParserFunction(
tagName: string,
tagConstructor: { new (value: any): parts.Part },
valueParser: (current: ParseNode) => ParseNode | null,
required: boolean,
): void {
(ParserRun.prototype as any)[`parse_tag_${ tagName }`] = function (this: ParserRun, parent: ParseNode): ParseNode | null {
const current = new ParseNode(parent);
if (this.read(current, tagName) === null) {
parent.pop();
return null;
}
const valueNode: ParseNode | null = valueParser.call(this, current);
if (valueNode !== null) {
current.value = new tagConstructor(valueNode.value);
}
else if (!required) {
current.value = new tagConstructor(null);
}
else {
parent.pop();
return null;
}
return current;
};
}
makeTagParserFunction("alpha", parts.Alpha, ParserRun.prototype.parse_alpha, false);
makeTagParserFunction("be", parts.Blur, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("blur", parts.GaussianBlur, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("bord", parts.Border, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("c", parts.PrimaryColor, ParserRun.prototype.parse_color, false);
makeTagParserFunction("fax", parts.SkewX, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("fay", parts.SkewY, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("fr", parts.RotateZ, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("frx", parts.RotateX, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("fry", parts.RotateY, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("frz", parts.RotateZ, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("fs", parts.FontSize, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("fsp", parts.LetterSpacing, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("i", parts.Italic, ParserRun.prototype.parse_enableDisable, false);
makeTagParserFunction("p", parts.DrawingMode, ParserRun.prototype.parse_decimal, true);
makeTagParserFunction("pbo", parts.DrawingBaselineOffset, ParserRun.prototype.parse_decimal, true);
makeTagParserFunction("s", parts.StrikeThrough, ParserRun.prototype.parse_enableDisable, false);
makeTagParserFunction("shad", parts.Shadow, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("u", parts.Underline, ParserRun.prototype.parse_enableDisable, false);
makeTagParserFunction("xbord", parts.BorderX, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("xshad", parts.ShadowX, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("ybord", parts.BorderY, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("yshad", parts.ShadowY, ParserRun.prototype.parse_decimal, false);
makeTagParserFunction("1a", parts.PrimaryAlpha, ParserRun.prototype.parse_alpha, false);
makeTagParserFunction("1c", parts.PrimaryColor, ParserRun.prototype.parse_color, false);
makeTagParserFunction("2a", parts.SecondaryAlpha, ParserRun.prototype.parse_alpha, false);
makeTagParserFunction("2c", parts.SecondaryColor, ParserRun.prototype.parse_color, false);
makeTagParserFunction("3a", parts.OutlineAlpha, ParserRun.prototype.parse_alpha, false);
makeTagParserFunction("3c", parts.OutlineColor, ParserRun.prototype.parse_color, false);
makeTagParserFunction("4a", parts.ShadowAlpha, ParserRun.prototype.parse_alpha, false);
makeTagParserFunction("4c", parts.ShadowColor, ParserRun.prototype.parse_color, false);
for (const key of Object.keys(ParserRun.prototype)) {
if (key.indexOf("parse_") === 0 && typeof (ParserRun.prototype as any)[key] === "function") {
rules.set(key.substr("parse_".length), (ParserRun.prototype as any)[key]);
}
}
import { Promise } from "../utility/promise";
import { WorkerCommands } from "../webworker/commands";
import { registerWorkerCommand } from "../webworker/misc";
registerWorkerCommand(WorkerCommands.Parse, parameters => new Promise<any>(resolve => {
resolve(parse(parameters.input, parameters.rule));
})); | the_stack |
import { testConfig } from 'houdini-common'
import path from 'path'
import fs from 'fs/promises'
import * as typeScriptParser from 'recast/parsers/typescript'
import { ProgramKind } from 'ast-types/gen/kinds'
import * as recast from 'recast'
// local imports
import '../../../../jest.setup'
import { runPipeline } from '../generate'
import { mockCollectedDoc } from '../testUtils'
test('pass argument values to generated fragments', async function () {
const docs = [
mockCollectedDoc(
`
query AllUsers {
...QueryFragment @with(name: "Hello")
}
`
),
mockCollectedDoc(
`
fragment QueryFragment on Query
@arguments(name: {type: "String!"} ) {
users(stringValue: $name) {
id
}
}
`
),
]
// run the pipeline
const config = testConfig()
await runPipeline(config, docs)
const queryContents = await fs.readFile(
path.join(config.artifactPath(docs[0].document)),
'utf-8'
)
expect(queryContents).toBeTruthy()
// parse the contents
const parsedQuery: ProgramKind = recast.parse(queryContents, {
parser: typeScriptParser,
}).program
// verify contents
expect(parsedQuery).toMatchInlineSnapshot(`
module.exports = {
name: "AllUsers",
kind: "HoudiniQuery",
hash: "c346b9eaafaa74d18a267a74706e193e8080b9533d994d6e8489d7e5b534ee41",
raw: \`query AllUsers {
...QueryFragment_10b3uv
}
fragment QueryFragment_10b3uv on Query {
users(stringValue: "Hello") {
id
}
}
\`,
rootType: "Query",
selection: {
users: {
type: "User",
keyRaw: "users(stringValue: \\"Hello\\")",
fields: {
id: {
type: "ID",
keyRaw: "id"
}
}
}
},
policy: "NetworkOnly"
};
`)
})
test("nullable arguments with no values don't show up in the query", async function () {
const docs = [
mockCollectedDoc(
`
query AllUsers {
...QueryFragment
}
`
),
mockCollectedDoc(
`
fragment QueryFragment on Query
@arguments(name: {type: "String"} ) {
users(stringValue: $name) {
id
}
}
`
),
]
// run the pipeline
const config = testConfig()
await runPipeline(config, docs)
const queryContents = await fs.readFile(
path.join(config.artifactPath(docs[0].document)),
'utf-8'
)
expect(queryContents).toBeTruthy()
// parse the contents
const parsedQuery: ProgramKind = recast.parse(queryContents, {
parser: typeScriptParser,
}).program
// verify contents
expect(parsedQuery).toMatchInlineSnapshot(`
module.exports = {
name: "AllUsers",
kind: "HoudiniQuery",
hash: "19b6a6cc9d06ab798cbf4b0a9530e07a3473b78e7d964cc9d6557d8240ed9012",
raw: \`query AllUsers {
...QueryFragment
}
fragment QueryFragment on Query {
users {
id
}
}
\`,
rootType: "Query",
selection: {
users: {
type: "User",
keyRaw: "users",
fields: {
id: {
type: "ID",
keyRaw: "id"
}
}
}
},
policy: "NetworkOnly"
};
`)
})
test("fragment arguments with default values don't rename the fragment", async function () {
const docs = [
mockCollectedDoc(
`
query AllUsers {
...QueryFragment
}
`
),
mockCollectedDoc(
`
fragment QueryFragment on Query
@arguments(name: {type: "String", default: "Hello"}) {
users(stringValue: $name) {
id
}
}
`
),
]
// run the pipeline
const config = testConfig()
await runPipeline(config, docs)
const queryContents = await fs.readFile(
path.join(config.artifactPath(docs[0].document)),
'utf-8'
)
expect(queryContents).toBeTruthy()
// parse the contents
const parsedQuery: ProgramKind = recast.parse(queryContents, {
parser: typeScriptParser,
}).program
// verify contents
expect(parsedQuery).toMatchInlineSnapshot(`
module.exports = {
name: "AllUsers",
kind: "HoudiniQuery",
hash: "3835ee68277547d738cc8fd5051fe98799b5bd470516146906fa0f134a2b3891",
raw: \`query AllUsers {
...QueryFragment
}
fragment QueryFragment on Query {
users(stringValue: "Hello") {
id
}
}
\`,
rootType: "Query",
selection: {
users: {
type: "User",
keyRaw: "users(stringValue: \\"Hello\\")",
fields: {
id: {
type: "ID",
keyRaw: "id"
}
}
}
},
policy: "NetworkOnly"
};
`)
})
test('thread query variables to inner fragments', async function () {
const docs = [
mockCollectedDoc(
`
query AllUsers($name: String!) {
...QueryFragment @with(name: $name)
}
`
),
mockCollectedDoc(
`
fragment QueryFragment on Query
@arguments(name: {type: "String", default: "Hello"}) {
...InnerFragment @with(name: $name)
}
`
),
mockCollectedDoc(
`
fragment InnerFragment on Query
@arguments(name: {type: "String", default: "Hello"}) {
users(stringValue: $name) {
id
}
}
`
),
]
// run the pipeline
const config = testConfig()
await runPipeline(config, docs)
const queryContents = await fs.readFile(
path.join(config.artifactPath(docs[0].document)),
'utf-8'
)
expect(queryContents).toBeTruthy()
// parse the contents
const parsedQuery: ProgramKind = recast.parse(queryContents, {
parser: typeScriptParser,
}).program
// verify contents
expect(parsedQuery).toMatchInlineSnapshot(`
module.exports = {
name: "AllUsers",
kind: "HoudiniQuery",
hash: "8fa4273ab75455c901e7de893f72a28af4c001afbf204ceca2fd7ab30b7ff372",
raw: \`query AllUsers($name: String!) {
...QueryFragment_VDHGm
}
fragment QueryFragment_VDHGm on Query {
...InnerFragment_VDHGm
}
fragment InnerFragment_VDHGm on Query {
users(stringValue: $name) {
id
}
}
\`,
rootType: "Query",
selection: {
users: {
type: "User",
keyRaw: "users(stringValue: $name)",
fields: {
id: {
type: "ID",
keyRaw: "id"
}
}
}
},
input: {
fields: {
name: "String"
},
types: {}
},
policy: "NetworkOnly"
};
`)
})
test('inner fragment with intermediate default value', async function () {
const docs = [
mockCollectedDoc(
`
query AllUsers {
...QueryFragment
}
`
),
mockCollectedDoc(
`
fragment QueryFragment on Query
@arguments(name: {type: "String", default: "Hello"}) {
...InnerFragment @with(name: $name)
}
`
),
mockCollectedDoc(
`
fragment InnerFragment on Query
@arguments(name: {type: "String", default: "Goodbye"}, age: {type: "Int", default: 2}) {
users(stringValue: $name, intValue: $age) {
id
}
}
`
),
]
// run the pipeline
const config = testConfig()
await runPipeline(config, docs)
const queryContents = await fs.readFile(
path.join(config.artifactPath(docs[0].document)),
'utf-8'
)
expect(queryContents).toBeTruthy()
// parse the contents
const parsedQuery: ProgramKind = recast.parse(queryContents, {
parser: typeScriptParser,
}).program
// verify contents
expect(parsedQuery).toMatchInlineSnapshot(`
module.exports = {
name: "AllUsers",
kind: "HoudiniQuery",
hash: "d5753a3cae56b8133c72527cdccdd0c001effb48104b98806ac62dd9afeeb259",
raw: \`query AllUsers {
...QueryFragment
}
fragment QueryFragment on Query {
...InnerFragment_10b3uv
}
fragment InnerFragment_10b3uv on Query {
users(stringValue: "Hello", intValue: 2) {
id
}
}
\`,
rootType: "Query",
selection: {
users: {
type: "User",
keyRaw: "users(stringValue: \\"Hello\\", intValue: 2)",
fields: {
id: {
type: "ID",
keyRaw: "id"
}
}
}
},
policy: "NetworkOnly"
};
`)
})
test("default values don't overwrite unless explicitly passed", async function () {
const docs = [
mockCollectedDoc(
`
query AllUsers {
...QueryFragment
}
`
),
mockCollectedDoc(
`
fragment QueryFragment on Query
@arguments(name: {type: "Int", default: 10}) {
...InnerFragment @with(other: $name)
}
`
),
mockCollectedDoc(
`
fragment InnerFragment on Query
@arguments(name: {type: "String", default: "Goodbye"}, other: { type: "Int"}) {
users(stringValue: $name, intValue: $other) {
id
}
}
`
),
]
// run the pipeline
const config = testConfig()
await runPipeline(config, docs)
const queryContents = await fs.readFile(
path.join(config.artifactPath(docs[0].document)),
'utf-8'
)
expect(queryContents).toBeTruthy()
// parse the contents
const parsedQuery: ProgramKind = recast.parse(queryContents, {
parser: typeScriptParser,
}).program
// verify contents
expect(parsedQuery).toMatchInlineSnapshot(`
module.exports = {
name: "AllUsers",
kind: "HoudiniQuery",
hash: "b155b401cdbdfe0f63dd47575fbcfb2aa90678e7530b93476c4efe559405cf4f",
raw: \`query AllUsers {
...QueryFragment
}
fragment QueryFragment on Query {
...InnerFragment_2geNXY
}
fragment InnerFragment_2geNXY on Query {
users(stringValue: "Goodbye", intValue: 10) {
id
}
}
\`,
rootType: "Query",
selection: {
users: {
type: "User",
keyRaw: "users(stringValue: \\"Goodbye\\", intValue: 10)",
fields: {
id: {
type: "ID",
keyRaw: "id"
}
}
}
},
policy: "NetworkOnly"
};
`)
})
test('default arguments', async function () {
const docs = [
mockCollectedDoc(
`
query AllUsers {
...QueryFragment
}
`
),
mockCollectedDoc(
`
fragment QueryFragment on Query
@arguments(name: {type: "String", default: "Hello"}, cool: {type: "Boolean", default: true}) {
users(boolValue: $cool, stringValue: $name) {
id
}
}
`
),
]
// run the pipeline
const config = testConfig()
await runPipeline(config, docs)
const queryContents = await fs.readFile(
path.join(config.artifactPath(docs[0].document)),
'utf-8'
)
expect(queryContents).toBeTruthy()
// parse the contents
const parsedQuery: ProgramKind = recast.parse(queryContents, {
parser: typeScriptParser,
}).program
// verify contents
expect(parsedQuery).toMatchInlineSnapshot(`
module.exports = {
name: "AllUsers",
kind: "HoudiniQuery",
hash: "5c4a8d1fe2e117286ecdfbd273bf1beb2f71a0a3fd9ea6bc84fe97c394c1a836",
raw: \`query AllUsers {
...QueryFragment
}
fragment QueryFragment on Query {
users(boolValue: true, stringValue: "Hello") {
id
}
}
\`,
rootType: "Query",
selection: {
users: {
type: "User",
keyRaw: "users(boolValue: true, stringValue: \\"Hello\\")",
fields: {
id: {
type: "ID",
keyRaw: "id"
}
}
}
},
policy: "NetworkOnly"
};
`)
})
test('multiple with directives - no overlap', async function () {
const docs = [
mockCollectedDoc(
`
query AllUsers {
...QueryFragment @with(name: "Goodbye") @with(cool: false)
}
`
),
mockCollectedDoc(
`
fragment QueryFragment on Query
@arguments(name: {type: "String", default: "Hello"}, cool: {type: "Boolean", default: true}) {
users(boolValue: $cool, stringValue: $name) {
id
}
}
`
),
]
// run the pipeline
const config = testConfig()
await runPipeline(config, docs)
const queryContents = await fs.readFile(
path.join(config.artifactPath(docs[0].document)),
'utf-8'
)
expect(queryContents).toBeTruthy()
// parse the contents
const parsedQuery: ProgramKind = recast.parse(queryContents, {
parser: typeScriptParser,
}).program
// verify contents
expect(parsedQuery).toMatchInlineSnapshot(`
module.exports = {
name: "AllUsers",
kind: "HoudiniQuery",
hash: "7327e6f7f6c8339feebb640b995c3e25efe1b25de29b1f43cb55c2a0566f713f",
raw: \`query AllUsers {
...QueryFragment_2prn0K
}
fragment QueryFragment_2prn0K on Query {
users(boolValue: false, stringValue: "Goodbye") {
id
}
}
\`,
rootType: "Query",
selection: {
users: {
type: "User",
keyRaw: "users(boolValue: false, stringValue: \\"Goodbye\\")",
fields: {
id: {
type: "ID",
keyRaw: "id"
}
}
}
},
policy: "NetworkOnly"
};
`)
}) | the_stack |
import { toHexString } from 'src/utils/strings';
/**
* Encodes a string to UTF-8.
*
* @param input The string to be encoded.
* @param byteOrderMark Whether or not a byte order marker (BOM) should be added
* to the start of the encoding. (default `true`)
* @returns A Uint8Array containing the UTF-8 encoding of the input string.
*
* -----------------------------------------------------------------------------
*
* JavaScript strings are composed of Unicode code points. Code points are
* integers in the range 0 to 1,114,111 (0x10FFFF). When serializing a string,
* it must be encoded as a sequence of words. A word is typically 8, 16, or 32
* bytes in size. As such, Unicode defines three encoding forms: UTF-8, UTF-16,
* and UTF-32. These encoding forms are described in the Unicode standard [1].
* This function implements the UTF-8 encoding form.
*
* -----------------------------------------------------------------------------
*
* In UTF-8, each code point is mapped to a sequence of 1, 2, 3, or 4 bytes.
* Note that the logic which defines this mapping is slightly convoluted, and
* not as straightforward as the mapping logic for UTF-16 or UTF-32. The UTF-8
* mapping logic is as follows [2]:
*
* • If a code point is in the range U+0000..U+007F, then view it as a 7-bit
* integer: 0bxxxxxxx. Map the code point to 1 byte with the first high order
* bit set to 0:
*
* b1=0b0xxxxxxx
*
* • If a code point is in the range U+0080..U+07FF, then view it as an 11-bit
* integer: 0byyyyyxxxxxx. Map the code point to 2 bytes with the first 5 bits
* of the code point stored in the first byte, and the last 6 bits stored in
* the second byte:
*
* b1=0b110yyyyy b2=0b10xxxxxx
*
* • If a code point is in the range U+0800..U+FFFF, then view it as a 16-bit
* integer, 0bzzzzyyyyyyxxxxxx. Map the code point to 3 bytes with the first
* 4 bits stored in the first byte, the next 6 bits stored in the second byte,
* and the last 6 bits in the third byte:
*
* b1=0b1110zzzz b2=0b10yyyyyy b3=0b10xxxxxx
*
* • If a code point is in the range U+10000...U+10FFFF, then view it as a
* 21-bit integer, 0bvvvzzzzzzyyyyyyxxxxxx. Map the code point to 4 bytes with
* the first 3 bits stored in the first byte, the next 6 bits stored in the
* second byte, the next 6 bits stored in the third byte, and the last 6 bits
* stored in the fourth byte:
*
* b1=0b11110xxx b2=0b10zzzzzz b3=0b10yyyyyy b4=0b10xxxxxx
*
* -----------------------------------------------------------------------------
*
* It is important to note, when iterating through the code points of a string
* in JavaScript, that if a character is encoded as a surrogate pair it will
* increase the string's length by 2 instead of 1 [4]. For example:
*
* ```
* > 'a'.length
* 1
* > '💩'.length
* 2
* > '語'.length
* 1
* > 'a💩語'.length
* 4
* ```
*
* The results of the above example are explained by the fact that the
* characters 'a' and '語' are not represented by surrogate pairs, but '💩' is.
*
* Because of this idiosyncrasy in JavaScript's string implementation and APIs,
* we must "jump" an extra index after encoding a character as a surrogate
* pair. In practice, this means we must increment the index of our for loop by
* 2 if we encode a surrogate pair, and 1 in all other cases.
*
* -----------------------------------------------------------------------------
*
* References:
* - [1] https://www.unicode.org/versions/Unicode12.0.0/UnicodeStandard-12.0.pdf
* 3.9 Unicode Encoding Forms - UTF-8
* - [2] http://www.herongyang.com/Unicode/UTF-8-UTF-8-Encoding.html
* - [3] http://www.herongyang.com/Unicode/UTF-8-UTF-8-Encoding-Algorithm.html
* - [4] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#Description
*
*/
export const utf8Encode = (input: string, byteOrderMark = true): Uint8Array => {
const encoded = [];
if (byteOrderMark) encoded.push(0xef, 0xbb, 0xbf);
for (let idx = 0, len = input.length; idx < len; ) {
const codePoint = input.codePointAt(idx)!;
// One byte encoding
if (codePoint < 0x80) {
const byte1 = codePoint & 0x7f;
encoded.push(byte1);
idx += 1;
}
// Two byte encoding
else if (codePoint < 0x0800) {
const byte1 = ((codePoint >> 6) & 0x1f) | 0xc0;
const byte2 = (codePoint & 0x3f) | 0x80;
encoded.push(byte1, byte2);
idx += 1;
}
// Three byte encoding
else if (codePoint < 0x010000) {
const byte1 = ((codePoint >> 12) & 0x0f) | 0xe0;
const byte2 = ((codePoint >> 6) & 0x3f) | 0x80;
const byte3 = (codePoint & 0x3f) | 0x80;
encoded.push(byte1, byte2, byte3);
idx += 1;
}
// Four byte encoding (surrogate pair)
else if (codePoint < 0x110000) {
const byte1 = ((codePoint >> 18) & 0x07) | 0xf0;
const byte2 = ((codePoint >> 12) & 0x3f) | 0x80;
const byte3 = ((codePoint >> 6) & 0x3f) | 0x80;
const byte4 = ((codePoint >> 0) & 0x3f) | 0x80;
encoded.push(byte1, byte2, byte3, byte4);
idx += 2;
}
// Should never reach this case
else throw new Error(`Invalid code point: 0x${toHexString(codePoint)}`);
}
return new Uint8Array(encoded);
};
/**
* Encodes a string to UTF-16.
*
* @param input The string to be encoded.
* @param byteOrderMark Whether or not a byte order marker (BOM) should be added
* to the start of the encoding. (default `true`)
* @returns A Uint16Array containing the UTF-16 encoding of the input string.
*
* -----------------------------------------------------------------------------
*
* JavaScript strings are composed of Unicode code points. Code points are
* integers in the range 0 to 1,114,111 (0x10FFFF). When serializing a string,
* it must be encoded as a sequence of words. A word is typically 8, 16, or 32
* bytes in size. As such, Unicode defines three encoding forms: UTF-8, UTF-16,
* and UTF-32. These encoding forms are described in the Unicode standard [1].
* This function implements the UTF-16 encoding form.
*
* -----------------------------------------------------------------------------
*
* In UTF-16, each code point is mapped to one or two 16-bit integers. The
* UTF-16 mapping logic is as follows [2]:
*
* • If a code point is in the range U+0000..U+FFFF, then map the code point to
* a 16-bit integer with the most significant byte first.
*
* • If a code point is in the range U+10000..U+10000, then map the code point
* to two 16-bit integers. The first integer should contain the high surrogate
* and the second integer should contain the low surrogate. Both surrogates
* should be written with the most significant byte first.
*
* -----------------------------------------------------------------------------
*
* It is important to note, when iterating through the code points of a string
* in JavaScript, that if a character is encoded as a surrogate pair it will
* increase the string's length by 2 instead of 1 [4]. For example:
*
* ```
* > 'a'.length
* 1
* > '💩'.length
* 2
* > '語'.length
* 1
* > 'a💩語'.length
* 4
* ```
*
* The results of the above example are explained by the fact that the
* characters 'a' and '語' are not represented by surrogate pairs, but '💩' is.
*
* Because of this idiosyncrasy in JavaScript's string implementation and APIs,
* we must "jump" an extra index after encoding a character as a surrogate
* pair. In practice, this means we must increment the index of our for loop by
* 2 if we encode a surrogate pair, and 1 in all other cases.
*
* -----------------------------------------------------------------------------
*
* References:
* - [1] https://www.unicode.org/versions/Unicode12.0.0/UnicodeStandard-12.0.pdf
* 3.9 Unicode Encoding Forms - UTF-8
* - [2] http://www.herongyang.com/Unicode/UTF-16-UTF-16-Encoding.html
* - [3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#Description
*
*/
export const utf16Encode = (
input: string,
byteOrderMark = true,
): Uint16Array => {
const encoded = [];
if (byteOrderMark) encoded.push(0xfeff);
for (let idx = 0, len = input.length; idx < len; ) {
const codePoint = input.codePointAt(idx)!;
// Two byte encoding
if (codePoint < 0x010000) {
encoded.push(codePoint);
idx += 1;
}
// Four byte encoding (surrogate pair)
else if (codePoint < 0x110000) {
encoded.push(highSurrogate(codePoint), lowSurrogate(codePoint));
idx += 2;
}
// Should never reach this case
else throw new Error(`Invalid code point: 0x${toHexString(codePoint)}`);
}
return new Uint16Array(encoded);
};
/**
* Returns `true` if the `codePoint` is within the
* Basic Multilingual Plane (BMP). Code points inside the BMP are not encoded
* with surrogate pairs.
* @param codePoint The code point to be evaluated.
*
* Reference: https://en.wikipedia.org/wiki/UTF-16#Description
*/
export const isWithinBMP = (codePoint: number) =>
codePoint >= 0 && codePoint <= 0xffff;
/**
* Returns `true` if the given `codePoint` is valid and must be represented
* with a surrogate pair when encoded.
* @param codePoint The code point to be evaluated.
*
* Reference: https://en.wikipedia.org/wiki/UTF-16#Description
*/
export const hasSurrogates = (codePoint: number) =>
codePoint >= 0x010000 && codePoint <= 0x10ffff;
// From Unicode 3.0 spec, section 3.7:
// http://unicode.org/versions/Unicode3.0.0/ch03.pdf
export const highSurrogate = (codePoint: number) =>
Math.floor((codePoint - 0x10000) / 0x400) + 0xd800;
// From Unicode 3.0 spec, section 3.7:
// http://unicode.org/versions/Unicode3.0.0/ch03.pdf
export const lowSurrogate = (codePoint: number) =>
((codePoint - 0x10000) % 0x400) + 0xdc00;
enum ByteOrder {
BigEndian = 'BigEndian',
LittleEndian = 'LittleEndian',
}
const REPLACEMENT = '�'.codePointAt(0)!;
/**
* Decodes a Uint8Array of data to a string using UTF-16.
*
* Note that this function attempts to recover from erronous input by
* inserting the replacement character (�) to mark invalid code points
* and surrogate pairs.
*
* @param input A Uint8Array containing UTF-16 encoded data
* @param byteOrderMark Whether or not a byte order marker (BOM) should be read
* at the start of the encoding. (default `true`)
* @returns The decoded string.
*/
export const utf16Decode = (
input: Uint8Array,
byteOrderMark = true,
): string => {
// Need at least 2 bytes of data in UTF-16 encodings
if (input.length <= 1) return String.fromCodePoint(REPLACEMENT);
const byteOrder = byteOrderMark ? readBOM(input) : ByteOrder.BigEndian;
// Skip byte order mark if needed
let idx = byteOrderMark ? 2 : 0;
const codePoints: number[] = [];
while (input.length - idx >= 2) {
const first = decodeValues(input[idx++], input[idx++], byteOrder);
if (isHighSurrogate(first)) {
if (input.length - idx < 2) {
// Need at least 2 bytes left for the low surrogate that is required
codePoints.push(REPLACEMENT);
} else {
const second = decodeValues(input[idx++], input[idx++], byteOrder);
if (isLowSurrogate(second)) {
codePoints.push(first, second);
} else {
// Low surrogates should always follow high surrogates
codePoints.push(REPLACEMENT);
}
}
} else if (isLowSurrogate(first)) {
// High surrogates should always come first since `decodeValues()`
// accounts for the byte ordering
idx += 2;
codePoints.push(REPLACEMENT);
} else {
codePoints.push(first);
}
}
// There shouldn't be extra byte(s) left over
if (idx < input.length) codePoints.push(REPLACEMENT);
return String.fromCodePoint(...codePoints);
};
/**
* Returns `true` if the given `codePoint` is a high surrogate.
* @param codePoint The code point to be evaluated.
*
* Reference: https://en.wikipedia.org/wiki/UTF-16#Description
*/
const isHighSurrogate = (codePoint: number) =>
codePoint >= 0xd800 && codePoint <= 0xdbff;
/**
* Returns `true` if the given `codePoint` is a low surrogate.
* @param codePoint The code point to be evaluated.
*
* Reference: https://en.wikipedia.org/wiki/UTF-16#Description
*/
const isLowSurrogate = (codePoint: number) =>
codePoint >= 0xdc00 && codePoint <= 0xdfff;
/**
* Decodes the given utf-16 values first and second using the specified
* byte order.
* @param first The first byte of the encoding.
* @param second The second byte of the encoding.
* @param byteOrder The byte order of the encoding.
* Reference: https://en.wikipedia.org/wiki/UTF-16#Examples
*/
const decodeValues = (first: number, second: number, byteOrder: ByteOrder) => {
// Append the binary representation of the preceding byte by shifting the
// first one 8 to the left and than applying a bitwise or-operator to append
// the second one.
if (byteOrder === ByteOrder.LittleEndian) return (second << 8) | first;
if (byteOrder === ByteOrder.BigEndian) return (first << 8) | second;
throw new Error(`Invalid byteOrder: ${byteOrder}`);
};
/**
* Returns whether the given array contains a byte order mark for the
* UTF-16BE or UTF-16LE encoding. If it has neither, BigEndian is assumed.
*
* Reference: https://en.wikipedia.org/wiki/Byte_order_mark#UTF-16
*
* @param bytes The byte array to be evaluated.
*/
// prettier-ignore
const readBOM = (bytes: Uint8Array): ByteOrder => (
hasUtf16BigEndianBOM(bytes) ? ByteOrder.BigEndian
: hasUtf16LittleEndianBOM(bytes) ? ByteOrder.LittleEndian
: ByteOrder.BigEndian
);
const hasUtf16BigEndianBOM = (bytes: Uint8Array) =>
bytes[0] === 0xfe && bytes[1] === 0xff;
const hasUtf16LittleEndianBOM = (bytes: Uint8Array) =>
bytes[0] === 0xff && bytes[1] === 0xfe;
export const hasUtf16BOM = (bytes: Uint8Array) =>
hasUtf16BigEndianBOM(bytes) || hasUtf16LittleEndianBOM(bytes); | the_stack |
import * as path from "path";
import * as vscode from "vscode";
import * as assert from "assert";
import {
Connection,
Server,
WebSocketTransport
} from "vscode-cdp-proxy";
import { convertWindowsPathToUnixOne } from "../testUtils";
import { generateRandomPortNumber, delay } from "../../src/utils/extensionHelper";
import { CordovaCDPProxy } from "../../src/debugger/cdp-proxy/cordovaCDPProxy";
import { ProjectType } from "../../src/utils/cordovaProjectHelper";
import { ICordovaAttachRequestArgs } from "../../src/debugger/requestArgs";
import { CDPMessageHandlerCreator } from "../../src/debugger/cdp-proxy/CDPMessageHandlers/CDPMessageHandlerCreator";
import { CDPMessageHandlerBase } from "../../src/debugger/cdp-proxy/CDPMessageHandlers/abstraction/CDPMessageHandlerBase";
import { CDP_API_NAMES } from "../../src/debugger/cdp-proxy/CDPMessageHandlers/CDPAPINames";
import { SourcemapPathTransformer } from "../../src/debugger/cdp-proxy/sourcemapPathTransformer";
import { LogLevel } from "../../src/utils/log/logHelper";
import { DebuggerEndpointHelper } from "../../src/debugger/cdp-proxy/debuggerEndpointHelper";
interface ICDPProxyInternalEntities {
attachArgs: ICordovaAttachRequestArgs;
projectType: ProjectType;
sourcemapPathTransformer: SourcemapPathTransformer;
cdpMessageHandler: CDPMessageHandlerBase;
}
suite("cordovaCDPProxy", function () {
const cdpProxyHostAddress = "127.0.0.1"; // localhost
const cdpProxyPort = generateRandomPortNumber();
const cdpProxyLogLevel = LogLevel.Custom;
const testProjectPath = process.platform === "win32" ?
convertWindowsPathToUnixOne(path.join(__dirname, "..", "resources", "testCordovaProject")) :
path.join(__dirname, "..", "resources", "testCordovaProject");
let proxy: CordovaCDPProxy;
let cancellationTokenSource: vscode.CancellationTokenSource = new vscode.CancellationTokenSource();
let wsTargetPort = generateRandomPortNumber();
let wsTargetServer: Server | null;
let targetConnection: Connection | null;
let debugConnection: Connection | null;
// For all hooks and tests set a time limit
this.timeout(5000);
async function cleanUp() {
cancellationTokenSource.dispose();
if (targetConnection) {
await targetConnection.close();
targetConnection = null;
}
if (debugConnection) {
await debugConnection.close();
debugConnection = null;
}
await proxy.stopServer();
if (wsTargetServer) {
await wsTargetServer.dispose();
wsTargetServer = null;
}
}
function prepareCDPProxyInternalEntities(debugType: "ionic" | "cordova" | "simulate", cdpHandlerType: "chrome" | "safari"): ICDPProxyInternalEntities {
let attachArgs: ICordovaAttachRequestArgs;
let projectType: ProjectType;
let sourcemapPathTransformer: SourcemapPathTransformer;
let cdpMessageHandler: CDPMessageHandlerBase;
projectType = new ProjectType(
false, // isMeteor
false, // isMobilefirst
false, // isPhonegap
true, // isCordova
);
attachArgs = {
cwd: path.resolve(__dirname, "..", "resources", "testCordovaProject"),
platform: "android",
ionicLiveReload: false,
request: "attach",
port: 9222,
};
switch (debugType) {
case "ionic":
projectType.ionicMajorVersion = 5;
break;
case "cordova":
break;
case "simulate":
attachArgs.simulatePort = 8000;
break;
}
if (cdpHandlerType === "chrome") {
sourcemapPathTransformer = new SourcemapPathTransformer(attachArgs, projectType);
cdpMessageHandler = CDPMessageHandlerCreator.create(sourcemapPathTransformer, projectType, attachArgs, true);
} else {
attachArgs.platform = "ios";
sourcemapPathTransformer = new SourcemapPathTransformer(attachArgs, projectType);
cdpMessageHandler = CDPMessageHandlerCreator.create(sourcemapPathTransformer, projectType, attachArgs, false);
}
return {
attachArgs,
projectType,
sourcemapPathTransformer,
cdpMessageHandler,
};
}
suiteSetup(async () => {
let cdpProxyInternalEntities = prepareCDPProxyInternalEntities("cordova", "chrome");
proxy = new CordovaCDPProxy(
cdpProxyHostAddress,
cdpProxyPort,
cdpProxyInternalEntities.sourcemapPathTransformer,
cdpProxyInternalEntities.projectType,
cdpProxyInternalEntities.attachArgs
);
proxy.setApplicationTargetPort(wsTargetPort);
await proxy.createServer(cdpProxyLogLevel, cancellationTokenSource.token);
await Server.create({ host: "localhost", port: wsTargetPort })
.then((server: Server) => {
wsTargetServer = server;
server.onConnection(([connection, request]: [Connection, any]) => {
targetConnection = connection;
});
});
const proxyUri = await new DebuggerEndpointHelper().getWSEndpoint(`http://${cdpProxyHostAddress}:${cdpProxyPort}`);
debugConnection = new Connection(await WebSocketTransport.create(proxyUri));
// Due to the time limit, sooner or later this cycle will end
while (!targetConnection) {
await delay(1000);
}
});
suiteTeardown(async () => {
await cleanUp();
});
suite("MessageHandlers", () => {
suite("ChromeCDPMessageHandler", () => {
suite("Pure Cordova", () => {
suiteSetup(() => {
let cdpProxyInternalEntities = prepareCDPProxyInternalEntities("cordova", "chrome");
Object.assign(proxy, { CDPMessageHandler: cdpProxyInternalEntities.cdpMessageHandler });
});
test("Messages should be delivered correctly with ChromeCDPMessageHandler", async () => {
const targetMessageStart = { method: "Target.start", params: { reason: "test" } };
const debuggerMessageStart = { method: "Debugger.start", params: { reason: "test" } };
const messageFromTarget = await new Promise((resolve) => {
targetConnection?.send(targetMessageStart);
debugConnection?.onCommand((evt: any) => {
resolve(evt);
});
});
const messageFromDebugger = await new Promise((resolve) => {
debugConnection?.send(debuggerMessageStart);
targetConnection?.onCommand((evt: any) => {
resolve(evt);
});
});
assert.deepStrictEqual(messageFromTarget, targetMessageStart);
assert.deepStrictEqual(messageFromDebugger, debuggerMessageStart);
});
suite("Simulate", () => {
suiteSetup(() => {
let cdpProxyInternalEntities = prepareCDPProxyInternalEntities("simulate", "chrome");
Object.assign(proxy, { CDPMessageHandler: cdpProxyInternalEntities.cdpMessageHandler });
});
test(`Message from the target with ${CDP_API_NAMES.DEBUGGER_SCRIPT_PARSED} should replace the "url" prop with the correct absolute path for the source`, async () => {
const processedMessageRef = {
method: CDP_API_NAMES.DEBUGGER_SCRIPT_PARSED,
params: {
url: `file://${process.platform === "win32" ? "/" + testProjectPath : testProjectPath}/www/js/index.js`,
},
};
const targetMessageTest = {
method: CDP_API_NAMES.DEBUGGER_SCRIPT_PARSED,
params: {
url: "http://localhost:8000/js/index.js",
},
};
const processedMessage = await new Promise((resolve) => {
targetConnection?.send(targetMessageTest);
debugConnection?.onCommand((evt: any) => {
resolve(evt);
});
});
assert.deepStrictEqual(processedMessageRef, processedMessage);
});
});
});
suite("Ionic", () => {
suiteSetup(() => {
let cdpProxyInternalEntities = prepareCDPProxyInternalEntities("ionic", "chrome");
Object.assign(proxy, { CDPMessageHandler: cdpProxyInternalEntities.cdpMessageHandler });
});
test(`Message from the target with ${CDP_API_NAMES.DEBUGGER_SCRIPT_PARSED} should replace the "url" prop with the correct absolute path for the source`, async () => {
const processedMessageRef = {
method: CDP_API_NAMES.DEBUGGER_SCRIPT_PARSED,
params: {
url: `file://${process.platform === "win32" ? "/" + testProjectPath : testProjectPath}/www/main.js`,
},
};
const targetMessageTest = {
method: CDP_API_NAMES.DEBUGGER_SCRIPT_PARSED,
params: {
url: "http://localhost/main.js",
},
};
const processedMessage = await new Promise((resolve) => {
targetConnection?.send(targetMessageTest);
debugConnection?.onCommand((evt: any) => {
resolve(evt);
});
});
assert.deepStrictEqual(processedMessageRef, processedMessage);
});
test(`Message from the debugger with ${CDP_API_NAMES.DEBUGGER_SET_BREAKPOINT_BY_URL} should replace the "urlRegex" prop with the correct one`, async () => {
const processedMessageRef = {
method: CDP_API_NAMES.DEBUGGER_SET_BREAKPOINT_BY_URL,
params: {
urlRegex: `http:\\/\\/localhost\\/${process.platform === "win32" ? "[mM][aA][iI][nN]\\.[jJ][sS]" : "main\\.js"}`,
},
};
let testUrlRegex;
if (process.platform === "win32") {
const testPathRegex = `${testProjectPath.replace(/([\/\.])/g, "\\$1")}\\\\[wW][wW][wW]\\\\[mM][aA][iI][nN]\\.[jJ][sS]`;
testUrlRegex = `[fF][iI][lL][eE]:\\/\\/${testPathRegex}|${testPathRegex}`;
} else {
const testPathRegex = `${testProjectPath}/www/main.js`.replace(/([\/\.])/g, "\\$1");
testUrlRegex = `file:\\/\\/${testPathRegex}|${testPathRegex}`;
}
const debuggerMessageTest = {
method: CDP_API_NAMES.DEBUGGER_SET_BREAKPOINT_BY_URL,
params: {
urlRegex: testUrlRegex,
},
};
const processedMessage = await new Promise((resolve) => {
debugConnection?.send(debuggerMessageTest);
targetConnection?.onCommand((evt: any) => {
resolve(evt);
});
});
assert.deepStrictEqual(processedMessageRef, processedMessage);
});
});
});
suite("SafariCDPMessageHandler", () => {
suite("Ionic", () => {
const targetPageId = "page-7";
suiteSetup(() => {
let cdpProxyInternalEntities = prepareCDPProxyInternalEntities("ionic", "safari");
(cdpProxyInternalEntities.cdpMessageHandler as any).targetId = targetPageId;
Object.assign(proxy, { CDPMessageHandler: cdpProxyInternalEntities.cdpMessageHandler });
});
test("Messages should be wrapped in the Target form", async () => {
const debuggerMessageTest = {
id: 1002,
method: "Debugger.enable",
params: {},
};
const processedMessageRef = {
id: debuggerMessageTest.id,
method: CDP_API_NAMES.TARGET_SEND_MESSAGE_TO_TARGET,
params: {
id: debuggerMessageTest.id,
message: JSON.stringify(debuggerMessageTest),
targetId: targetPageId,
},
};
const processedMessage = await new Promise((resolve) => {
debugConnection?.send(debuggerMessageTest);
targetConnection?.onReply((evt: any) => {
resolve(evt);
});
});
assert.deepStrictEqual(processedMessageRef, processedMessage);
});
});
});
});
}); | the_stack |
/// <reference types="jquery"/>
declare function Sammy(): Sammy.Application;
declare function Sammy(selector: string): Sammy.Application;
declare function Sammy(handler: Function): Sammy.Application;
declare function Sammy(selector: string, handler: Function): Sammy.Application;
declare namespace Sammy {
interface SammyFunc {
(): Sammy.Application;
(selector: string): Sammy.Application;
(handler: Function): Sammy.Application;
(selector: string, handler: Function): Sammy.Application;
}
export function Cache(app: any, options: any): any;
export function DataCacheProxy(initial: any, $element: any): any;
export var DataLocationProxy:DataLocationProxy;
export function DefaultLocationProxy(app: any, run_interval_every: any): any;
export function EJS(app: any, method_alias: any): any;
export function Exceptional(app: any, errorReporter: any): any;
export function Flash(app: any): any;
export var FormBuilder: FormBuilder;
export function Form(app: any): any; // formFor ( name, object, content_callback )
export function Haml(app: any, method_alias: any): any;
export function Handlebars(app: any, method_alias: any): any;
export function Hogan(app: any, method_alias: any): any;
export function Hoptoad(app: any, errorReporter: any): any;
export function JSON(app: any): any;
export function Meld(app: any, method_alias: any): any;
export function MemoryCacheProxy(initial: any): any;
export function Mustache(app: any, method_alias: any): any;
export function NestedParams(app: any): any;
export function OAuth2(app: any): any;
export function PathLocationProxy(app: any): any;
export function Pure(app: any, method_alias: any): any;
export function PushLocationProxy(app: any): any;
export function Session(app: any, options: any): any;
export function Storage(app: any): any;
export var Store: Store;
export function Title(): any;
export function Template(app: any, method_alias: any): any;
export function Tmpl(app: any, method_alias: any): any;
export function addLogger(logger: any): any;
export function log(...args:any[]): any;
export class Object {
constructor(obj: any);
escapeHTML(s: string): string;
h(s: string): string;
has(key: string): boolean;
join(...args: any[]): string;
keys(attributes_only?: boolean): string[];
log(...args: any[]): void;
toHTML(): string;
toHash(): any;
toString(include_functions?: boolean): string;
}
export interface Application extends Object {
ROUTE_VERBS: string[];
APP_EVENTS: string[];
(appFn: Function): any;
$element(selector?: string): JQuery;
after(callback: Function): Application;
any(verb: string, path: string, callback: Function): void;
around(callback: Function): Application;
before(callback: Function): Application;
before(options: any, callback: Function): Application;
bind(name: string, callback: Function): Application;
bind(name: string, data: any, callback: Function): Application;
bindToAllEvents(callback: Function): Application;
clearTemplateCache(): any;
contextMatchesOptions(context: any, match_options: any, positive?: boolean): boolean;
del(path: string, callback: Function): Application;
del(path: RegExp, callback: Function): Application;
destroy(): Application;
error(message: string, original_error: Error): void;
eventNamespace(): string;
get(path: string, callback: Function): Application;
get(path: RegExp, callback: Function): Application;
getLocation(): string;
helper(name: string, method: Function): any; // Behaviour similar to _.extend
helpers(extensions: any): any; // Behaviour similar to _.extend
isRunning(): boolean;
log(...params: any[]): void;
lookupRoute(verb: string, path: string): any;
mapRoutes(route_array: any[]): Application;
notFound(verb: string, path: string): any;
post(path: string, callback: Function): Application;
post(path: RegExp, callback: Function): Application;
put(path: string, callback: Function): Application;
put(path: RegExp, callback: Function): Application;
refresh(): Application;
routablePath(path: string): string;
route(verb: string, path: string, callback: Function): Application;
route(verb: string, path: RegExp, callback: Function): Application;
run(start_url?: string): Application;
runRoute(verb: string, path?: string, params?: any, target?: any): any;
send(...params: any[]): any;
setLocation(new_location: string): string;
setLocationProxy(new_proxy: DataLocationProxy): void;
swap(content: any, callback: Function): any;
templateCache(key: string, value: any): any;
toString(): string;
trigger(name: string, data?: any): Application;
unload(): Application;
use(...params: any[]): void;
last_location: string[];
// Features provided by oauth2 plugin
oauthorize: string;
requireOAuth(): any;
requireOAuth(path?:string): any;
requireOAuth(callback?: Function): any;
}
export interface DataLocationProxy {
new (app: any, run_interval_every?: any): DataLocationProxy;
new (app: any, data_name: any, href_attribute: any): DataLocationProxy;
fullPath(location_obj: any): string;
bind(): void;
unbind(): void;
setLocation(new_location: string): string;
_startPolling(every: number): void;
}
export interface EventContext extends Object {
new (app: any, verb: any, path: any, params: any, target: any): any;
$element(): JQuery;
engineFor(engine: any): any;
eventNamespace(): string;
interpolate(content: any, data: any, engine: any, partials?: any): EventContext;
json(str: any): any;
json(str: string): any;
load(location: any, options?: any, callback?: Function): any;
loadPartials(partials?: any): any;
notFound(): any;
partial(location: string, data?: any, callback?: Function, partials?: any): RenderContext;
partials: any;
params: any;
redirect(...params: any[]): void;
render(location: string, data?: any, callback?: Function, partials?: any): RenderContext;
renderEach(location: any, data?: { name: string;data?:any}[],callback?: Function): RenderContext;
send(...params: any[]): RenderContext;
swap(contents: any, callback: Function): string;
toString(): string;
trigger(name: string, data?: any): EventContext;
// Provided by common sammy modules:
name: any;
title: any;
}
export interface FormBuilder {
new (name: any, object: any): any;
checkbox(keypath: string, value: any, ...attributes: any[]): string;
close(): string;
hidden(keypath: string, ...attributes: any[]): string;
label(keypath: string, content: any, ...attributes: any[]): string;
open(...attributes: any[]): any;
password(keypath: string, ...attributes: any[]): string;
radio(keypath: string, value: any, ...attributes: any[]): string;
select(keypath: string, options: any, ...attributes: any[]): string;
submit(...attributes: any[]): string;
text(keypath: string, ...attributes: any[]): string;
textarea(keypath: string, ...attributes: any[]): string;
}
export interface Form {
formFor(name: string, object: any, content_callback: Function): FormBuilder;
}
export interface GoogleAnalytics {
new (app: any, tracker: any): any;
noTrack(): any;
track(path: any): any;
}
export interface Haml extends EventContext { }
export interface Handlebars extends EventContext { }
export interface Hogan extends EventContext { }
export interface JSON extends EventContext { }
export interface Mustache extends EventContext { }
export interface RenderContext extends Object {
new (event_context: any): any;
appendTo(selector: string): RenderContext;
collect(array: any[], callback: Function, now?: boolean): RenderContext;
interpolate(data: any, engine?: any, retain?: boolean): RenderContext;
load(location: string, options?: any, callback?: Function): RenderContext;
loadPartials(partials?: any): RenderContext;
next(content: any): void;
partial(location: string, callback: Function, partials: any): RenderContext;
partial(location: string, data: any, callback: Function, partials: any): RenderContext;
prependTo(selector: string): RenderContext;
render(callback: Function): RenderContext;
render(location: string, data: any): RenderContext;
render(location: string, callback: Function, partials?: any): RenderContext;
render(location: string, data: any, callback: Function): RenderContext;
render(location: string, data: any, callback: Function, partials: any): RenderContext;
renderEach(location: string, name?: string, data?: any, callback?: Function): RenderContext;
replace(selector: string): RenderContext;
send(...params: any[]): RenderContext;
swap(callback?: Function): RenderContext;
then(callback: Function): RenderContext;
trigger(name: any, data: any): any;
wait(): void;
}
export interface StoreOptions {
name?: string;
element?: string;
type?: string;
memory?: any;
data?: any;
cookie?: any;
local?: any;
session?: any;
}
export interface Store {
stores: any;
new (options?:any): any;
clear(key: string): any;
clearAll(): void;
each(callback: Function): boolean;
exists(key: string): boolean;
fetch(key: string, callback: Function): any;
filter(callback: Function): boolean;
first(callback: Function): boolean;
get(key: string): any;
isAvailable(): boolean;
keys(): string[];
load(key: string, path: string, callback: Function): void;
set(key: string, value: any): any;
Cookie(name: any, element: any, options: any): any;
Data(name: any, element: any): any;
LocalStorage(name: any, element: any): any;
Memory(name: any, element: any): any;
SessionStorage(name: any, element: any): any;
isAvailable(type: any): any;
Template(app: any, method_alias: any): any;
}
}
declare module "sammy" {
export = Sammy;
}
interface JQueryStatic {
sammy: Sammy.SammyFunc;
log: Function;
} | the_stack |
import {
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { ICommandPalette } from '@jupyterlab/apputils';
import { IMainMenu } from '@jupyterlab/mainmenu';
import { INotebookTracker } from '@jupyterlab/notebook';
import { IEditorTracker } from '@jupyterlab/fileeditor';
import { IStateDB } from '@jupyterlab/statedb';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { Terminal } from '@jupyterlab/terminal';
import { Cell } from '@jupyterlab/cells';
import { CodeMirrorEditor } from '@jupyterlab/codemirror';
import * as CodeMirror from 'codemirror';
// CSS
import '../style/index.css';
// extension id
const id = 'jupyterlab-flake8';
class Preferences {
toggled = true; // turn on/off linter
lint_on_change = true; // lint on notebook/editor change
logging = false; // turn on/off logging
highlight_color = 'var(--jp-warn-color3)'; // color of highlights
gutter_color = 'var(--jp-error-color0)'; // color of gutter icons
term_timeout = 5000; // seconds before the temrinal times out if it has not received a message
conda_env = 'base'; // conda environment
terminal_name = 'flake8term'; // persistent terminal to share between session
configuration_file = ''; // global flake8 configuration file
}
interface IProcessMark {
(line: number, ch: number): any;
}
/**
* Linter
*/
class Linter {
app: JupyterFrontEnd;
notebookTracker: INotebookTracker;
editorTracker: IEditorTracker;
palette: ICommandPalette;
mainMenu: IMainMenu;
state: IStateDB;
term: Terminal;
prefsKey = `${id}:preferences`;
settingsKey = `${id}:plugin`;
// Default Options
prefs = new Preferences();
// flags
loaded = false; // flag if flake8 is available
linting = false; // flag if the linter is processing
termTimeoutHandle: number; // flag if the linter is processing
// notebook
cell_text: Array<string>; // current nb cells
cells: Array<any>; // widgets from notebook
notebook: any; // current nb cells
lookup: any; // lookup of line index
// editor
editor: any; // current file editor widget
editortext: any; // current file editor text
gutter_id = 'CodeMirror-lintgutter'; // gutter element id
// cache
marks: Array<CodeMirror.TextMarker> = []; // text marker objects currently active
bookmarks: Array<any> = []; // text marker objects in editor // --- Temporary fix since gutter doesn't work in editor
docs: Array<any> = []; // text marker objects currently active
text = ''; // current nb text
process_mark: IProcessMark; // default line marker processor
os = ''; // operating system
settingRegistry: ISettingRegistry; // settings
constructor(
app: JupyterFrontEnd,
notebookTracker: INotebookTracker,
editorTracker: IEditorTracker,
palette: ICommandPalette,
mainMenu: IMainMenu,
state: IStateDB,
settingRegistry: ISettingRegistry
) {
this.app = app;
this.mainMenu = mainMenu;
this.notebookTracker = notebookTracker;
this.editorTracker = editorTracker;
this.palette = palette;
this.state = state;
this.settingRegistry = settingRegistry;
// load settings from the registry
Promise.all([
this.settingRegistry.load(this.settingsKey),
app.restored
]).then(([settings]) => {
this.update_settings(settings, true);
// callback to update settings on changes
settings.changed.connect((settings: ISettingRegistry.ISettings) => {
this.update_settings(settings);
});
// on first load, if linter enabled, start it up
if (this.prefs.toggled) {
this.load_linter();
}
});
// activate function when cell changes
this.notebookTracker.currentChanged.connect(
this.onActiveNotebookChanged,
this
);
// activate when editor changes
this.editorTracker.currentChanged.connect(this.onActiveEditorChanged, this);
// add menu item
this.add_commands();
}
/**
* Update settings callback
* @param {ISettingRegistry.ISettings} settings
*/
private update_settings(
settings: ISettingRegistry.ISettings,
first_load = false
) {
const old = JSON.parse(JSON.stringify(this.prefs)); // copy old prefs
// set settings to prefs object
Object.keys(settings.composite).forEach((key: string) => {
(<any>this.prefs)[key] = (<any>settings.composite)[key];
});
this.log(`loaded settings ${JSON.stringify(this.prefs)}`);
// toggle linter
if (!first_load && old.toggled !== this.prefs.toggled) {
this.toggle_linter();
}
}
/**
* Load terminal session and flake8
*/
private async load_linter() {
// Bail if there are no terminals available.
if (!this.app.serviceManager.terminals.isAvailable()) {
this.log(
'Disabling jupyterlab-flake8 plugin because it cant access terminal'
);
this.loaded = false;
this.prefs.toggled = false;
return;
}
// try to connect to previous terminal, if not start a new one
// TODO: still can't set the name of a terminal, so for now saving the "new"
// terminal name in the settings (#16)
let session;
try {
session = await this.app.serviceManager.terminals.connectTo({
model: { name: this.prefs.terminal_name }
});
} catch (e) {
this.log('starting new terminal session');
session = await this.app.serviceManager.terminals.startNew();
}
// save terminal name
this.setPreference('terminal_name', session.name);
// start a new terminal session
this.log(`set terminal_name to ${session.name}`);
this.term = new Terminal(session);
// flush on load
function _flush_on_load(sender: any, msg: any) {
return;
}
// this gets rid of any messages that might get sent on load
// may fix #28 or #31
this.term.session.messageReceived.connect(_flush_on_load, this);
// get OS
const _get_OS = (sender: any, msg: any) => {
if (msg.content) {
const message: string = msg.content[0] as string;
// throw away non-strings
if (typeof message !== 'string') {
return;
}
if (message.indexOf('command not found') > -1) {
this.log('python command failed on this machine');
this.term.session.messageReceived.disconnect(_get_OS, this);
this.finish_load();
}
// set OS
if (message.indexOf('posix') > -1) {
this.os = 'posix';
} else if (
message.indexOf('nt(') === -1 &&
message.indexOf('int') === -1 &&
message.indexOf('nt') > -1
) {
this.os = 'nt';
} else {
return;
}
this.log(`os: ${this.os}`);
// disconnect the os listener and connect empty listener
this.term.session.messageReceived.disconnect(_get_OS, this);
// setup stage
this.setup_terminal();
}
};
// wait a moment for terminal to load and then ask for OS
setTimeout(() => {
// disconnect flush
this.term.session.messageReceived.disconnect(_flush_on_load, this);
// ask for the OS
this.term.session.messageReceived.connect(_get_OS, this);
this.term.session.send({
type: 'stdin',
content: ['python -c "import os; print(os.name)"\r']
});
}, 1500);
}
private setup_terminal() {
if (this.os === 'posix') {
this.term.session.send({ type: 'stdin', content: ['HISTFILE= ;\r'] });
}
// custom conda-env
if (this.prefs.conda_env !== 'base') {
this.set_env();
} else {
this.finish_load();
}
}
// activate specific conda environment
private set_env() {
this.log(`conda env: ${this.prefs.conda_env}`);
if (this.os === 'posix') {
this.term.session.send({
type: 'stdin',
content: [`conda activate ${this.prefs.conda_env}\r`]
});
} else if (this.os !== 'posix') {
this.term.session.send({
type: 'stdin',
content: [`source activate ${this.prefs.conda_env}\r`]
});
}
this.finish_load();
}
private finish_load() {
try {
// wait a moment for terminal to get initial commands out of its system
setTimeout(() => {
this.loaded = true;
this.activate_flake8();
}, 500);
} catch (e) {
this.loaded = false;
this.prefs.toggled = false;
this.term.dispose();
}
}
/**
* Activate flake8 terminal reader
*/
private activate_flake8() {
// listen for stdout in onLintMessage
this.term.session.messageReceived.connect(this.onLintMessage, this);
}
/**
* Dispose of the terminal used to lint
*/
private dispose_linter() {
this.log('disposing flake8 and terminal');
this.lint_cleanup();
this.clear_marks();
if (this.term) {
this.term.session.messageReceived.disconnect(this.onLintMessage, this);
this.term.dispose();
}
}
/**
* load linter when notebook changes
*/
private onActiveNotebookChanged(): void {
// return if file is being closed
if (!this.notebookTracker.currentWidget) {
return;
}
// select the notebook
this.notebook = this.notebookTracker.currentWidget.content;
this.checkNotebookGutters();
// run on cell changing
this.notebookTracker.activeCellChanged.disconnect(
this.onActiveCellChanged,
this
);
this.notebookTracker.activeCellChanged.connect(
this.onActiveCellChanged,
this
);
// run on stateChanged
this.notebook.model.stateChanged.disconnect(this.onActiveCellChanged, this);
this.notebook.model.stateChanged.connect(this.onActiveCellChanged, this);
}
/**
* Run linter when active cell changes
*/
private onActiveCellChanged(): void {
this.checkNotebookGutters();
// note this check must be here, not in the parent onActive function
if (this.loaded && this.prefs.toggled && this.prefs.lint_on_change) {
if (!this.linting) {
this.lint_notebook();
} else {
this.log('flake8 is already running onActiveCellChanged');
}
}
}
/**
* load linter when active editor loads
*/
private onActiveEditorChanged(): void {
// return if file is being closed
if (!this.editorTracker.currentWidget) {
return;
}
// select the editor
this.editor = this.editorTracker.currentWidget.content;
this.checkEditorGutters();
// run on stateChanged
this.editor.model.stateChanged.disconnect(this.onActiveEditorChanges, this);
this.editor.model.stateChanged.connect(this.onActiveEditorChanges, this);
}
/**
* Run linter on active editor changes
*/
private onActiveEditorChanges(): void {
this.checkEditorGutters();
// note this check must be here, not in the parent onActive function
if (this.loaded && this.prefs.toggled && this.prefs.lint_on_change) {
if (!this.linting) {
this.lint_editor();
} else {
this.log('flake8 is already running onEditorChanged');
}
}
}
private checkNotebookGutters(): void {
this.notebook.widgets.forEach((widget: any) => {
const editor = widget.inputArea.editor;
const lineNumbers = editor._config.lineNumbers;
const codeFolding = editor._config.codeFolding;
const gutters = [
lineNumbers && 'CodeMirror-linenumbers',
codeFolding && 'CodeMirror-foldgutter',
this.gutter_id
].filter(d => d);
editor.editor.setOption('gutters', gutters);
});
}
private checkEditorGutters(): void {
// let editor = this.editorTracker.currentWidget.content;
// let editorWidget = this.editorTracker.currentWidget;
const editor = this.editor.editor;
const lineNumbers = editor._config.lineNumbers;
const codeFolding = editor._config.codeFolding;
const gutters = [
lineNumbers && 'CodeMirror-linenumbers',
codeFolding && 'CodeMirror-foldgutter',
this.gutter_id
].filter(d => d);
editor.setOption('gutters', gutters);
}
/**
* Generate lint command
*
* @param {string} contents - contents of the notebook ready to be linted
* @return {string} [description]
*/
private lint_cmd(contents: string): string {
// escaped characters common to powershell and unix
let escaped = contents.replace(/[`\\]/g, '\\$&');
// escaped characters speciic to shell
if (this.os === 'nt') {
escaped = contents.replace(/["]/g, '`$&'); // powershell
} else {
escaped = contents.replace(/["]/g, '\\$&'); // unix
}
escaped = escaped.replace('\r', ''); // replace carriage returns
// ignore magics by commenting
escaped = escaped
.split('\n')
// handle ipy magics %% and %
.map((line: string) => {
if (line.startsWith('%%')) {
return `# ${line}`;
} else {
return line;
}
})
.map((line: string) => {
if (line.startsWith('%')) {
return `# ${line}`;
} else {
return line;
}
})
.join(this.newline());
// remove final \n (#20)
if (escaped.endsWith(this.newline())) {
if (this.os === 'nt') {
escaped = escaped.slice(0, -2); // powershell
} else {
escaped = escaped.slice(0, -1); // unix
}
}
let config_option = '';
if (
this.prefs.configuration_file !== null &&
this.prefs.configuration_file !== ''
) {
config_option = `--config="${this.prefs.configuration_file}"`;
}
if (this.os === 'nt') {
// powershell
return `echo "${escaped}" | flake8 ${config_option} --exit-zero - ; if($?) {echo "@jupyterlab-flake8 finished linting"} ; if (-not $?) {echo "@jupyterlab-flake8 finished linting failed"} `;
} else {
// unix
return `(echo "${escaped}" | flake8 ${config_option} --exit-zero - && echo "@jupyterlab-flake8 finished linting" ) || (echo "@jupyterlab-flake8 finished linting failed")`;
}
}
/**
* Determine new line character based on platform
*/
private newline() {
// powershell by default on windows
if (this.os === 'nt') {
return '`n';
// otherwise unix
} else {
return '\n';
}
}
/**
* Determine if text is input
* @param {string} text [description]
*/
private text_exists(text: string) {
return text;
// return text && text !== '\n' && text !== '\n\n';
}
/**
* Clear all current marks from code mirror
*/
private clear_marks() {
// clear marks
this.marks.forEach((mark: CodeMirror.TextMarker) => {
mark.clear();
});
this.marks = [];
// --- Temporary fix since gutter doesn't work in editor
// clear error messages in editor
this.clear_error_messages();
// clear gutter
this.docs.forEach((doc: any) => {
doc.cm.clearGutter(this.gutter_id);
});
this.docs = [];
}
/**
* Lint the CodeMirror Editor
*/
private lint_editor() {
this.linting = true; // no way to turn this off yet
this.process_mark = this.mark_editor;
// catch if file is not a .py file
if (
this.editor.context.path.indexOf('.py') > -1 ||
this.editor.model._defaultLang === 'python'
) {
this.log('getting editor text from python file');
} else {
this.log('not python default lang');
this.lint_cleanup();
return;
}
const pytext = this.editor.model.value.text;
this.lint(pytext);
}
/**
* mark the editor pane
* @param {number} line [description]
* @param {number} ch [description]
*/
private mark_editor(line: number, ch: number) {
this.log('marking editor');
line = line - 1; // 0 index
ch = ch - 1; // not sure
// get lines
const from = { line: line, ch: ch };
const to = { line: line, ch: ch + 1 };
// get code mirror editor
const doc = this.editor.editorWidget.editor.doc;
return { context: 'editor', doc, from, to };
}
/**
* Run flake8 linting on notebook cells
*/
private lint_notebook() {
this.linting = true; // no way to turn this off yet
this.process_mark = this.mark_notebook;
// load notebook
this.cells = this.notebook.widgets;
this.log('getting notebook text');
// return text from each cell if its a code cell
this.cell_text = this.cells.map(
(cell: any, cell_idx: number, cell_arr: any[]) => {
if (
cell.model.type === 'code' &&
this.text_exists(cell.model.value.text)
) {
// append \n\n if its not the last cell
if (cell_idx !== cell_arr.length - 1) {
return `${cell.model.value.text}\n\n`;
} else {
return cell.model.value.text;
}
} else {
return '';
}
}
);
// create dictionary of lines
this.lookup = {};
let line = 1;
this.cell_text.map((cell: any, cell_idx: number, cell_arr: any[]) => {
// if there is text in the cell,
if (this.text_exists(cell)) {
const lines = cell.split('\n');
for (let idx = 0; idx < lines.length - 1; idx++) {
this.lookup[line] = {
cell: cell_idx,
line: idx
};
line += 1;
}
}
// if its the last cell in the notebook and its empty
else if (cell_idx === cell_arr.length - 1) {
this.lookup[line] = {
cell: cell_idx,
line: 0
};
}
});
// ignore other languages (#32)
// this seems to be all %%magic commands except %%capture
this.cell_text = this.cell_text.map(
(cell: any, cell_idx: number, cell_arr: any[]) => {
const firstline = cell.split('\n')[0];
if (
firstline &&
firstline.startsWith('%%') &&
!(firstline.indexOf('%%capture') > -1)
) {
return cell
.split('\n')
.map((t: string) => (t !== '' ? `# ${t}` : ''))
.join('\n');
} else {
return cell;
}
}
);
// join cells with text with two new lines
const pytext = this.cell_text.join('');
// run linter
this.lint(pytext);
}
/**
* mark the line of the cell
* @param {number} line the line # returned by flake8
* @param {number} ch the character # returned by flake 8
*/
private mark_notebook(line: number, ch: number) {
const loc = this.lookup[line];
ch = ch - 1; // make character 0 indexed
if (!loc) {
return;
}
const from = { line: loc.line, ch: ch };
const to = { line: loc.line, ch: ch + 1 };
// get cell instance
const cell: Cell = this.notebook.widgets[loc.cell];
// get cell's code mirror editor
const editor: CodeMirrorEditor = cell.inputArea.editorWidget
.editor as CodeMirrorEditor;
const doc = editor.doc;
return { context: 'notebook', doc, from, to };
}
/**
* Lint a python text message and callback marking function with line and character
* @param {string} pytext [description]
*/
private lint(pytext: string) {
// cache pytext on text
if (pytext !== this.text) {
this.text = pytext;
} else {
// text has not changed
this.log('text unchanged');
this.lint_cleanup();
return;
}
// TODO: handle if text is empty (any combination of '' and \n)
if (!this.text_exists(this.text)) {
this.log('text empty');
this.lint_cleanup();
return;
}
// clean current marks
this.clear_marks();
// get lint command to run in terminal and send to terminal
this.log('preparing lint command');
const lint_cmd = this.lint_cmd(pytext);
this.log('sending lint command');
this.term.session.send({ type: 'stdin', content: [`${lint_cmd}\r`] });
this.termTimeoutHandle = setTimeout(() => {
if (this.linting) {
this.log('lint command timed out');
alert(
'jupyterlab-flake8 ran into an issue connecting with the terminal. Please try reloading the browser or re-installing the jupyterlab-flake8 extension.'
);
this.lint_cleanup();
this.dispose_linter();
this.prefs.toggled = false;
}
}, this.prefs.term_timeout);
}
/**
* Handle terminal message during linting
* TODO: import ISession and IMessage types for sender and msg
* @param {any} sender [description]
* @param {any} msg [description]
*/
private onLintMessage(sender: any, msg: any): void {
clearTimeout(this.termTimeoutHandle);
if (msg.content) {
const message: string = msg.content[0] as string;
// catch non-strings
if (typeof message !== 'string') {
return;
}
// log message
this.log(`terminal message: ${message}`);
// if message a is a reflection of the command, return
if (message.indexOf('Traceback') > -1) {
alert(
`Flake8 encountered a python error. Make sure flake8 is installed and on the system path. \n\nTraceback: ${message}`
);
this.lint_cleanup();
return;
}
// if message a is a reflection of the command, return
if (message.indexOf('command not found') > -1) {
alert(
"Flake8 was not found in this python environment. \n\nIf you are using a conda environment, set the 'conda_env' setting in the Advanced Settings menu and reload the Jupyter Lab window.\n\nIf you are not using a conda environment, Install Flake8 with 'pip install flake8' or 'conda install flake8' and reload the Jupyter Lab window"
);
this.lint_cleanup();
return;
}
message.split(/(?:\n|\[)/).forEach(m => {
if (m.includes('stdin:')) {
const idxs = m.split(':');
const line = parseInt(idxs[1]);
const ch = parseInt(idxs[2]);
this.log(idxs[3]);
this.get_mark(line, ch, idxs[3].slice(0, -1));
}
});
if (message.indexOf('jupyterlab-flake8 finished linting') > -1) {
this.lint_cleanup();
}
}
}
/**
* Mark a line in notebook or editor
* @param {number} line [description]
* @param {number} ch [description]
* @param {string} message [description]
*/
private get_mark(line: number, ch: number, message: string) {
try {
if (this.process_mark && typeof this.process_mark === 'function') {
const { doc, from, to, context } = this.process_mark(line, ch);
if (!doc || !from || !to) {
this.log('mark location not fully defined');
return;
}
this.mark_line(doc, from, to, message, context);
}
} catch (e) {
this.log('failed to run process_mark');
return;
}
}
/**
* Mark line in document
* @param {any} doc [description]
* @param {any} from [description]
* @param {any} to [description]
* @param {string} message [description]
*/
private mark_line(
doc: any,
from: any,
to: any,
message: string,
context: 'editor' | 'notebook'
) {
const gutter_color = this.prefs.gutter_color;
// gutter marker - this doesn't work in the editor
function makeMarker() {
const marker = document.createElement('div');
marker.innerHTML = `<div class='jupyterlab-flake8-lint-gutter-container' style='color: ${gutter_color}''>
<div>◉</div><div class='jupyterlab-flake8-lint-gutter-message'>${message}</div>
</div>`;
return marker;
}
// store gutter marks for later
doc.cm.setGutterMarker(from.line, this.gutter_id, makeMarker());
this.docs.push(doc);
// --- Temporary fix since gutters don't show up in editor
// show error message in editor
if (context === 'editor') {
const lint_alert = document.createElement('span');
const lint_message = document.createTextNode(`------ ${message}`);
lint_alert.appendChild(lint_message);
lint_alert.className = 'jupyterlab-flake8-lint-message-inline';
// add error alert node to the 'to' location
this.bookmarks.push((<any>doc).addLineWidget(from.line, lint_alert));
}
// mark the text position with highlight
this.marks.push(
doc.markText(from, to, {
// replacedWith: selected_char_node,
className: 'jupyterlab-flake8-lint-message',
css: `
background-color: ${this.prefs.highlight_color}
`
})
);
}
/**
* // --- Temporary fix since gutters don't show up in editor
* Clear all error messages
*/
private clear_error_messages() {
this.bookmarks.forEach((bookmark: any) => {
bookmark.clear();
});
}
/**
* Tear down lint fixtures
*/
private lint_cleanup() {
this.linting = false;
// this.process_mark = undefined;
}
/**
* Show browser logs
* @param {any} msg [description]
*/
private log(msg: any) {
// return if prefs.logging is not enabled
if (!this.prefs.logging) {
return;
}
// convert object messages to strings
if (typeof msg === 'object') {
msg = JSON.stringify(msg);
}
// prepend name
const output = `jupyterlab-flake8: ${msg}`;
console.log(output);
}
/**
* Create menu / command items
*/
add_commands() {
const category = 'Flake8';
// define all commands
const commands: any = {
'flake8:toggle': {
label: 'Enable Flake8',
isEnabled: () => {
return this.loaded;
},
isToggled: () => {
return this.prefs.toggled;
},
execute: async () => {
this.setPreference('toggled', !this.prefs.toggled);
}
},
'flake8:lint_on_change': {
label: 'Run Flake8 on notebook/editor change',
isEnabled: () => {
return this.loaded && this.prefs.toggled;
},
isToggled: () => {
return this.prefs.lint_on_change;
},
execute: () => {
this.setPreference('lint_on_change', !this.prefs.lint_on_change);
}
},
'flake8:run_lint_notebook': {
label: 'Lint active notebook',
isEnabled: () => {
return this.loaded && this.prefs.toggled;
},
execute: () => {
if (!(this.loaded && this.prefs.toggled)) {
return;
}
// return if undefined
if (!this.notebookTracker.currentWidget) {
return;
}
// select the notebook
this.notebook = this.notebookTracker.currentWidget.content;
this.checkNotebookGutters();
this.lint_notebook();
}
},
'flake8:run_lint_editor': {
label: 'Lint active editor',
isEnabled: () => {
return this.loaded && this.prefs.toggled;
},
execute: () => {
if (!(this.loaded && this.prefs.toggled)) {
return;
}
// return if file is being closed
if (!this.editorTracker.currentWidget) {
return;
}
// select the editor
this.editor = this.editorTracker.currentWidget.content;
this.checkEditorGutters();
this.lint_editor();
}
}
};
// add commands to menus and palette
for (const key in commands) {
this.app.commands.addCommand(key, commands[key]);
this.palette.addItem({ command: key, category: category });
}
// add to view Menu
this.mainMenu.viewMenu.addGroup(
Object.keys(commands)
.filter(
key => ['flake8:toggle', 'flake8:lint_on_change'].indexOf(key) > -1
)
.map(key => {
return { command: key };
}),
30
);
}
/**
* Turn linting on/off
*/
private toggle_linter() {
if (this.prefs.toggled) {
this.load_linter();
} else {
this.dispose_linter();
}
}
/**
* Save state preferences
*/
private async setPreference(key: string, val: any) {
await Promise.all([
this.settingRegistry.load(this.settingsKey),
this.app.restored
]).then(([settings]) => {
settings.set(key, val); // will automatically call update
});
}
}
/**
* Activate extension
*/
function activate(
app: JupyterFrontEnd,
notebookTracker: INotebookTracker,
editorTracker: IEditorTracker,
palette: ICommandPalette,
mainMenu: IMainMenu,
state: IStateDB,
settingRegistry: ISettingRegistry
): void {
new Linter(
app,
notebookTracker,
editorTracker,
palette,
mainMenu,
state,
settingRegistry
);
}
/**
* Initialization data for the jupyterlab-flake8 extension.
*/
const plugin: JupyterFrontEndPlugin<void> = {
id: 'jupyterlab-flake8',
autoStart: true,
activate: activate,
requires: [
INotebookTracker,
IEditorTracker,
ICommandPalette,
IMainMenu,
IStateDB,
ISettingRegistry
]
};
export default plugin; | the_stack |
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojNBox<K, D> extends dvtBaseComponent<ojNBoxSettableProperties<K, D>> {
animationOnDataChange: 'auto' | 'none';
animationOnDisplay: 'auto' | 'none';
as: string;
cellContent: 'counts' | 'auto';
cellMaximize: 'off' | 'on';
cells: Promise<ojNBox.Cell[]> | null;
columns: Promise<ojNBox.Column[]> | null;
columnsTitle: string;
countLabel: ((context: ojNBox.CountLabelContext) => (string | null));
data: DataProvider<K, D> | null;
groupAttributes: 'color' | 'indicatorColor' | 'indicatorIconColor' | 'indicatorIconPattern' | 'indicatorIconShape';
groupBehavior: 'acrossCells' | 'none' | 'withinCell';
hiddenCategories: string[];
highlightMatch: 'any' | 'all';
highlightedCategories: string[];
hoverBehavior: 'dim' | 'none';
labelTruncation: 'ifRequired' | 'on';
maximizedColumn: string;
maximizedRow: string;
otherColor: string;
otherThreshold: number;
rows: Promise<ojNBox.Row[]> | null;
rowsTitle: string;
selection: K[];
selectionMode: 'none' | 'single' | 'multiple';
styleDefaults: {
animationDuration: number;
cellDefaults: {
labelHalign: 'center' | 'end' | 'start';
labelStyle: object;
maximizedSvgStyle: object;
minimizedSvgStyle: object;
showCount: 'on' | 'off' | 'auto';
svgStyle: object;
};
columnLabelStyle: object;
columnsTitleStyle: object;
hoverBehaviorDelay: number;
nodeDefaults: {
borderColor: string;
borderWidth: number;
color: string;
iconDefaults: {
borderColor: string;
borderRadius: string;
borderWidth: number;
color: string;
height: number;
opacity: number;
pattern: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shape: 'circle' | 'ellipse' | 'square' | 'plus' | 'diamond' | 'triangleUp' | 'triangleDown' | 'human' | 'rectangle' | 'star';
source: string;
width: number;
};
indicatorColor: string;
indicatorIconDefaults: {
borderColor: string;
borderRadius: string;
borderWidth: number;
color: string;
height: number;
opacity: number;
pattern: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shape: 'circle' | 'ellipse' | 'square' | 'plus' | 'diamond' | 'triangleUp' | 'triangleDown' | 'human' | 'rectangle' | 'star';
source: string;
width: number;
};
labelStyle: object;
secondaryLabelStyle: object;
};
rowLabelStyle: object;
rowsTitleStyle: object;
};
tooltip: {
renderer: ((context: ojNBox.TooltipContext<K>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
})) | null;
};
touchResponse: 'touchStart' | 'auto';
translations: {
componentName?: string;
highlightedCount?: string;
labelAdditionalData?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelGroup?: string;
labelInvalidData?: string;
labelNoData?: string;
labelOther?: string;
labelSize?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
onAnimationOnDataChangeChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["animationOnDataChange"]>) => any) | null;
onAnimationOnDisplayChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["animationOnDisplay"]>) => any) | null;
onAsChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["as"]>) => any) | null;
onCellContentChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["cellContent"]>) => any) | null;
onCellMaximizeChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["cellMaximize"]>) => any) | null;
onCellsChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["cells"]>) => any) | null;
onColumnsChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["columns"]>) => any) | null;
onColumnsTitleChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["columnsTitle"]>) => any) | null;
onCountLabelChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["countLabel"]>) => any) | null;
onDataChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["data"]>) => any) | null;
onGroupAttributesChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["groupAttributes"]>) => any) | null;
onGroupBehaviorChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["groupBehavior"]>) => any) | null;
onHiddenCategoriesChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["hiddenCategories"]>) => any) | null;
onHighlightMatchChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["highlightMatch"]>) => any) | null;
onHighlightedCategoriesChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["highlightedCategories"]>) => any) | null;
onHoverBehaviorChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["hoverBehavior"]>) => any) | null;
onLabelTruncationChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["labelTruncation"]>) => any) | null;
onMaximizedColumnChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["maximizedColumn"]>) => any) | null;
onMaximizedRowChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["maximizedRow"]>) => any) | null;
onOtherColorChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["otherColor"]>) => any) | null;
onOtherThresholdChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["otherThreshold"]>) => any) | null;
onRowsChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["rows"]>) => any) | null;
onRowsTitleChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["rowsTitle"]>) => any) | null;
onSelectionChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["selection"]>) => any) | null;
onSelectionModeChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["selectionMode"]>) => any) | null;
onStyleDefaultsChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["styleDefaults"]>) => any) | null;
onTooltipChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["tooltip"]>) => any) | null;
onTouchResponseChanged: ((event: JetElementCustomEvent<ojNBox<K, D>["touchResponse"]>) => any) | null;
addEventListener<T extends keyof ojNBoxEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojNBoxEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojNBoxSettableProperties<K, D>>(property: T): ojNBox<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojNBoxSettableProperties<K, D>>(property: T, value: ojNBoxSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojNBoxSettableProperties<K, D>>): void;
setProperties(properties: ojNBoxSettablePropertiesLenient<K, D>): void;
getCell(rowValue: string, columnValue: string): object | null;
getColumn(columnValue: string): object | null;
getColumnCount(): number;
getColumnsTitle(): string;
getContextByNode(node: Element): object | null;
getDialog(): object | null;
getGroupBehavior(): string;
getGroupNode(groupCategory: string): object | null;
getRow(rowValue: string): object | null;
getRowCount(): number;
getRowsTitle(): string;
}
export interface ojNBoxEventMap<K, D> extends dvtBaseComponentEventMap<ojNBoxSettableProperties<K, D>> {
'animationOnDataChangeChanged': JetElementCustomEvent<ojNBox<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojNBox<K, D>["animationOnDisplay"]>;
'asChanged': JetElementCustomEvent<ojNBox<K, D>["as"]>;
'cellContentChanged': JetElementCustomEvent<ojNBox<K, D>["cellContent"]>;
'cellMaximizeChanged': JetElementCustomEvent<ojNBox<K, D>["cellMaximize"]>;
'cellsChanged': JetElementCustomEvent<ojNBox<K, D>["cells"]>;
'columnsChanged': JetElementCustomEvent<ojNBox<K, D>["columns"]>;
'columnsTitleChanged': JetElementCustomEvent<ojNBox<K, D>["columnsTitle"]>;
'countLabelChanged': JetElementCustomEvent<ojNBox<K, D>["countLabel"]>;
'dataChanged': JetElementCustomEvent<ojNBox<K, D>["data"]>;
'groupAttributesChanged': JetElementCustomEvent<ojNBox<K, D>["groupAttributes"]>;
'groupBehaviorChanged': JetElementCustomEvent<ojNBox<K, D>["groupBehavior"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojNBox<K, D>["hiddenCategories"]>;
'highlightMatchChanged': JetElementCustomEvent<ojNBox<K, D>["highlightMatch"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojNBox<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojNBox<K, D>["hoverBehavior"]>;
'labelTruncationChanged': JetElementCustomEvent<ojNBox<K, D>["labelTruncation"]>;
'maximizedColumnChanged': JetElementCustomEvent<ojNBox<K, D>["maximizedColumn"]>;
'maximizedRowChanged': JetElementCustomEvent<ojNBox<K, D>["maximizedRow"]>;
'otherColorChanged': JetElementCustomEvent<ojNBox<K, D>["otherColor"]>;
'otherThresholdChanged': JetElementCustomEvent<ojNBox<K, D>["otherThreshold"]>;
'rowsChanged': JetElementCustomEvent<ojNBox<K, D>["rows"]>;
'rowsTitleChanged': JetElementCustomEvent<ojNBox<K, D>["rowsTitle"]>;
'selectionChanged': JetElementCustomEvent<ojNBox<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojNBox<K, D>["selectionMode"]>;
'styleDefaultsChanged': JetElementCustomEvent<ojNBox<K, D>["styleDefaults"]>;
'tooltipChanged': JetElementCustomEvent<ojNBox<K, D>["tooltip"]>;
'touchResponseChanged': JetElementCustomEvent<ojNBox<K, D>["touchResponse"]>;
}
export interface ojNBoxSettableProperties<K, D> extends dvtBaseComponentSettableProperties {
animationOnDataChange: 'auto' | 'none';
animationOnDisplay: 'auto' | 'none';
as: string;
cellContent: 'counts' | 'auto';
cellMaximize: 'off' | 'on';
cells: ojNBox.Cell[] | Promise<ojNBox.Cell[]> | null;
columns: ojNBox.Column[] | Promise<ojNBox.Column[]> | null;
columnsTitle: string;
countLabel: ((context: ojNBox.CountLabelContext) => (string | null));
data: DataProvider<K, D> | null;
groupAttributes: 'color' | 'indicatorColor' | 'indicatorIconColor' | 'indicatorIconPattern' | 'indicatorIconShape';
groupBehavior: 'acrossCells' | 'none' | 'withinCell';
hiddenCategories: string[];
highlightMatch: 'any' | 'all';
highlightedCategories: string[];
hoverBehavior: 'dim' | 'none';
labelTruncation: 'ifRequired' | 'on';
maximizedColumn: string;
maximizedRow: string;
otherColor: string;
otherThreshold: number;
rows: ojNBox.Row[] | Promise<ojNBox.Row[]> | null;
rowsTitle: string;
selection: K[];
selectionMode: 'none' | 'single' | 'multiple';
styleDefaults: {
animationDuration: number;
cellDefaults: {
labelHalign: 'center' | 'end' | 'start';
labelStyle: object;
maximizedSvgStyle: object;
minimizedSvgStyle: object;
showCount: 'on' | 'off' | 'auto';
svgStyle: object;
};
columnLabelStyle: object;
columnsTitleStyle: object;
hoverBehaviorDelay: number;
nodeDefaults: {
borderColor: string;
borderWidth: number;
color: string;
iconDefaults: {
borderColor: string;
borderRadius: string;
borderWidth: number;
color: string;
height: number;
opacity: number;
pattern: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shape: 'circle' | 'ellipse' | 'square' | 'plus' | 'diamond' | 'triangleUp' | 'triangleDown' | 'human' | 'rectangle' | 'star';
source: string;
width: number;
};
indicatorColor: string;
indicatorIconDefaults: {
borderColor: string;
borderRadius: string;
borderWidth: number;
color: string;
height: number;
opacity: number;
pattern: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shape: 'circle' | 'ellipse' | 'square' | 'plus' | 'diamond' | 'triangleUp' | 'triangleDown' | 'human' | 'rectangle' | 'star';
source: string;
width: number;
};
labelStyle: object;
secondaryLabelStyle: object;
};
rowLabelStyle: object;
rowsTitleStyle: object;
};
tooltip: {
renderer: ((context: ojNBox.TooltipContext<K>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
})) | null;
};
touchResponse: 'touchStart' | 'auto';
translations: {
componentName?: string;
highlightedCount?: string;
labelAdditionalData?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelGroup?: string;
labelInvalidData?: string;
labelNoData?: string;
labelOther?: string;
labelSize?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
}
export interface ojNBoxSettablePropertiesLenient<K, D> extends Partial<ojNBoxSettableProperties<K, D>> {
[key: string]: any;
}
export namespace ojNBox {
// tslint:disable-next-line interface-over-type-literal
type Cell = {
label?: string;
column: string;
labelHalign?: string;
labelStyle?: object;
svgClassName?: string;
svgStyle?: object;
maximizedSvgStyle?: object;
maximizedSvgClassName?: string;
minimizedSvgStyle?: object;
minimizedSvgClassName?: string;
row: string;
showCount?: 'on' | 'off' | 'auto' | string;
shortDesc?: string;
};
// tslint:disable-next-line interface-over-type-literal
type Column = {
id: string;
label?: string;
labelStyle?: object;
};
// tslint:disable-next-line interface-over-type-literal
type CountLabelContext = {
row: string;
column: string;
nodeCount: number;
totalNodeCount: number;
highlightedNodeCount: number;
};
// tslint:disable-next-line interface-over-type-literal
type Row = {
id: string;
label?: string;
labelStyle?: object;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K> = {
parentElement: Element;
id: K;
label: string;
secondaryLabel: string;
row: string;
column: string;
color: string;
indicatorColor: string;
componentElement: Element;
};
}
export interface ojNBoxNode extends JetElement<ojNBoxNodeSettableProperties> {
borderColor: string;
borderWidth: number;
categories: string[];
color?: string;
column: string;
groupCategory?: string;
icon?: {
borderColor?: string;
borderRadius?: string;
borderWidth: number;
color?: string;
height?: number | null;
opacity: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'mallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string;
svgClassName: string;
svgStyle?: object;
width?: number | null;
};
indicatorColor?: string;
indicatorIcon?: {
borderColor?: string;
borderRadius?: string;
borderWidth: number;
color?: string;
height?: number | null;
opacity: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string | null;
svgClassName: string;
svgStyle?: object | null;
width?: number | null;
};
label: string;
row: string;
secondaryLabel: string;
shortDesc: string;
svgClassName: string;
svgStyle: object | null;
xPercentage?: number | null;
yPercentage?: number | null;
onBorderColorChanged: ((event: JetElementCustomEvent<ojNBoxNode["borderColor"]>) => any) | null;
onBorderWidthChanged: ((event: JetElementCustomEvent<ojNBoxNode["borderWidth"]>) => any) | null;
onCategoriesChanged: ((event: JetElementCustomEvent<ojNBoxNode["categories"]>) => any) | null;
onColorChanged: ((event: JetElementCustomEvent<ojNBoxNode["color"]>) => any) | null;
onColumnChanged: ((event: JetElementCustomEvent<ojNBoxNode["column"]>) => any) | null;
onGroupCategoryChanged: ((event: JetElementCustomEvent<ojNBoxNode["groupCategory"]>) => any) | null;
onIconChanged: ((event: JetElementCustomEvent<ojNBoxNode["icon"]>) => any) | null;
onIndicatorColorChanged: ((event: JetElementCustomEvent<ojNBoxNode["indicatorColor"]>) => any) | null;
onIndicatorIconChanged: ((event: JetElementCustomEvent<ojNBoxNode["indicatorIcon"]>) => any) | null;
onLabelChanged: ((event: JetElementCustomEvent<ojNBoxNode["label"]>) => any) | null;
onRowChanged: ((event: JetElementCustomEvent<ojNBoxNode["row"]>) => any) | null;
onSecondaryLabelChanged: ((event: JetElementCustomEvent<ojNBoxNode["secondaryLabel"]>) => any) | null;
onShortDescChanged: ((event: JetElementCustomEvent<ojNBoxNode["shortDesc"]>) => any) | null;
onSvgClassNameChanged: ((event: JetElementCustomEvent<ojNBoxNode["svgClassName"]>) => any) | null;
onSvgStyleChanged: ((event: JetElementCustomEvent<ojNBoxNode["svgStyle"]>) => any) | null;
onXPercentageChanged: ((event: JetElementCustomEvent<ojNBoxNode["xPercentage"]>) => any) | null;
onYPercentageChanged: ((event: JetElementCustomEvent<ojNBoxNode["yPercentage"]>) => any) | null;
addEventListener<T extends keyof ojNBoxNodeEventMap>(type: T, listener: (this: HTMLElement, ev: ojNBoxNodeEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojNBoxNodeSettableProperties>(property: T): ojNBoxNode[T];
getProperty(property: string): any;
setProperty<T extends keyof ojNBoxNodeSettableProperties>(property: T, value: ojNBoxNodeSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojNBoxNodeSettableProperties>): void;
setProperties(properties: ojNBoxNodeSettablePropertiesLenient): void;
}
export interface ojNBoxNodeEventMap extends HTMLElementEventMap {
'borderColorChanged': JetElementCustomEvent<ojNBoxNode["borderColor"]>;
'borderWidthChanged': JetElementCustomEvent<ojNBoxNode["borderWidth"]>;
'categoriesChanged': JetElementCustomEvent<ojNBoxNode["categories"]>;
'colorChanged': JetElementCustomEvent<ojNBoxNode["color"]>;
'columnChanged': JetElementCustomEvent<ojNBoxNode["column"]>;
'groupCategoryChanged': JetElementCustomEvent<ojNBoxNode["groupCategory"]>;
'iconChanged': JetElementCustomEvent<ojNBoxNode["icon"]>;
'indicatorColorChanged': JetElementCustomEvent<ojNBoxNode["indicatorColor"]>;
'indicatorIconChanged': JetElementCustomEvent<ojNBoxNode["indicatorIcon"]>;
'labelChanged': JetElementCustomEvent<ojNBoxNode["label"]>;
'rowChanged': JetElementCustomEvent<ojNBoxNode["row"]>;
'secondaryLabelChanged': JetElementCustomEvent<ojNBoxNode["secondaryLabel"]>;
'shortDescChanged': JetElementCustomEvent<ojNBoxNode["shortDesc"]>;
'svgClassNameChanged': JetElementCustomEvent<ojNBoxNode["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojNBoxNode["svgStyle"]>;
'xPercentageChanged': JetElementCustomEvent<ojNBoxNode["xPercentage"]>;
'yPercentageChanged': JetElementCustomEvent<ojNBoxNode["yPercentage"]>;
}
export interface ojNBoxNodeSettableProperties extends JetSettableProperties {
borderColor: string;
borderWidth: number;
categories: string[];
color?: string;
column: string;
groupCategory?: string;
icon?: {
borderColor?: string;
borderRadius?: string;
borderWidth: number;
color?: string;
height?: number | null;
opacity: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'mallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string;
svgClassName: string;
svgStyle?: object;
width?: number | null;
};
indicatorColor?: string;
indicatorIcon?: {
borderColor?: string;
borderRadius?: string;
borderWidth: number;
color?: string;
height?: number | null;
opacity: number;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
source?: string | null;
svgClassName: string;
svgStyle?: object | null;
width?: number | null;
};
label: string;
row: string;
secondaryLabel: string;
shortDesc: string;
svgClassName: string;
svgStyle: object | null;
xPercentage?: number | null;
yPercentage?: number | null;
}
export interface ojNBoxNodeSettablePropertiesLenient extends Partial<ojNBoxNodeSettableProperties> {
[key: string]: any;
} | the_stack |
import { Orbit, Assertion } from '@orbit/core';
import {
RequestOptions,
pullable,
pushable,
queryable,
updatable,
TransformNotAllowed,
QueryNotAllowed,
FullResponse,
DefaultRequestOptions
} from '@orbit/data';
import {
RecordSource,
RecordSourceSettings,
RecordPullable,
RecordPushable,
RecordQueryable,
RecordUpdatable,
RecordOperation,
RecordTransform,
RecordQuery,
RecordQueryExpressionResult,
RecordOperationResult,
RecordQueryResult,
RecordTransformResult,
RecordSourceQueryOptions,
RecordQueryBuilder,
RecordTransformBuilder
} from '@orbit/records';
import {
JSONAPIRequestProcessor,
JSONAPIRequestProcessorSettings,
FetchSettings
} from './jsonapi-request-processor';
import {
JSONAPISerializer,
JSONAPISerializerSettings
} from './jsonapi-serializer';
import {
JSONAPIURLBuilder,
JSONAPIURLBuilderSettings
} from './jsonapi-url-builder';
import {
QueryRequestProcessor,
QueryRequestProcessors,
RecordQueryRequest,
getQueryRequests,
QueryRequestProcessorResponse
} from './lib/query-requests';
import {
TransformRequestProcessor,
TransformRequestProcessors,
RecordTransformRequest,
getTransformRequests,
TransformRequestProcessorResponse
} from './lib/transform-requests';
import {
SerializerClassForFn,
SerializerSettingsForFn,
SerializerForFn
} from '@orbit/serializers';
import { JSONAPIResponse } from './jsonapi-response';
const { deprecate } = Orbit;
interface JSONAPISharedRequestOptions {
maxRequests?: number;
parallelRequests?: boolean;
}
export interface JSONAPIQueryOptions
extends RecordSourceQueryOptions,
JSONAPISharedRequestOptions {}
export interface JSONAPITransformOptions
extends RequestOptions,
JSONAPISharedRequestOptions {}
export interface JSONAPISourceSettings<
QO extends JSONAPIQueryOptions = JSONAPIQueryOptions,
TO extends JSONAPITransformOptions = JSONAPITransformOptions,
QB = RecordQueryBuilder,
TB = RecordTransformBuilder
> extends RecordSourceSettings<QO, TO, QB, TB> {
/**
* Deprecated in favor of `defaultTransformOptions.maxRequests`
*
* @deprecated since v0.17, remove in v0.18
*/
maxRequestsPerTransform?: number;
/**
* Deprecated in favor of `defaultQueryOptions.maxRequests`
*
* @deprecated since v0.17, remove in v0.18
*/
maxRequestsPerQuery?: number;
name?: string;
namespace?: string;
host?: string;
defaultFetchSettings?: FetchSettings;
allowedContentTypes?: string[];
serializerFor?: SerializerForFn;
serializerClassFor?: SerializerClassForFn;
serializerSettingsFor?: SerializerSettingsForFn;
SerializerClass?: new (
settings: JSONAPISerializerSettings
) => JSONAPISerializer;
RequestProcessorClass?: new (
settings: JSONAPIRequestProcessorSettings
) => JSONAPIRequestProcessor;
URLBuilderClass?: new (
settings: JSONAPIURLBuilderSettings
) => JSONAPIURLBuilder;
}
export interface JSONAPISource<
QO extends JSONAPIQueryOptions = JSONAPIQueryOptions,
TO extends JSONAPITransformOptions = JSONAPITransformOptions,
QB = RecordQueryBuilder,
TB = RecordTransformBuilder
> extends RecordSource<QO, TO, QB, TB>,
RecordPullable<JSONAPIResponse[]>,
RecordPushable<JSONAPIResponse[]>,
RecordQueryable<JSONAPIResponse[], QB, QO>,
RecordUpdatable<JSONAPIResponse[], TB, TO> {}
/**
Source for accessing a JSON API compliant RESTful API with a network fetch
request.
If a single transform or query requires more than one fetch request,
requests will be performed sequentially and resolved together. From the
perspective of Orbit, these operations will all succeed or fail together. The
`maxRequestsPerTransform` and `maxRequestsPerQuery` settings allow limits to be
set on this behavior. These settings should be set to `1` if your client/server
configuration is unable to resolve partially successful transforms / queries.
@class JSONAPISource
@extends Source
*/
@pullable
@pushable
@queryable
@updatable
export class JSONAPISource<
QO extends JSONAPIQueryOptions = JSONAPIQueryOptions,
TO extends JSONAPITransformOptions = JSONAPITransformOptions,
QB = RecordQueryBuilder,
TB = RecordTransformBuilder
>
extends RecordSource<QO, TO, QB, TB>
implements
RecordPullable<JSONAPIResponse[]>,
RecordPushable<JSONAPIResponse[]>,
RecordQueryable<JSONAPIResponse[], QB, QO>,
RecordUpdatable<JSONAPIResponse[], TB, TO> {
requestProcessor: JSONAPIRequestProcessor;
constructor(settings: JSONAPISourceSettings<QO, TO, QB, TB>) {
settings.name = settings.name || 'jsonapi';
super(settings);
let {
name,
maxRequestsPerTransform,
maxRequestsPerQuery,
namespace,
host,
defaultFetchSettings,
allowedContentTypes,
serializerFor,
serializerClassFor,
serializerSettingsFor,
SerializerClass,
RequestProcessorClass,
URLBuilderClass,
keyMap
} = settings;
if (this.schema === undefined) {
throw new Assertion(
"JSONAPISource's `schema` must be specified in the `settings` passed to its constructor"
);
}
if (this._defaultQueryOptions === undefined) {
this._defaultQueryOptions = {} as DefaultRequestOptions<QO>;
}
if (this._defaultTransformOptions === undefined) {
this._defaultTransformOptions = {} as DefaultRequestOptions<TO>;
}
// Parallelize query requests by default (but not transform requests)
if (this._defaultQueryOptions.parallelRequests === undefined) {
this._defaultQueryOptions.parallelRequests = true;
}
if (maxRequestsPerTransform !== undefined) {
deprecate(
"The 'maxRequestsPerTransform' setting for 'JSONAPSource' has been deprecated in favor of 'defaultTransformOptions.maxRequests'."
);
this._defaultTransformOptions.maxRequests = maxRequestsPerTransform;
}
if (maxRequestsPerQuery !== undefined) {
deprecate(
"The 'maxRequestsPerQuery' setting for 'JSONAPSource' has been deprecated in favor of 'defaultQueryOptions.maxRequests'."
);
this._defaultQueryOptions.maxRequests = maxRequestsPerQuery;
}
RequestProcessorClass = RequestProcessorClass || JSONAPIRequestProcessor;
this.requestProcessor = new RequestProcessorClass({
sourceName: name,
serializerFor,
serializerClassFor,
serializerSettingsFor,
SerializerClass,
URLBuilderClass: URLBuilderClass || JSONAPIURLBuilder,
allowedContentTypes,
defaultFetchSettings,
namespace,
host,
schema: this.schema,
keyMap
});
}
/**
* Deprecated in favor of `defaultTransformOptions.maxRequests`
*
* @deprecated since v0.17, remove in v0.18
*/
get maxRequestsPerTransform(): number | undefined {
deprecate(
"The 'maxRequestsPerTransform' property for 'JSONAPSource' has been deprecated in favor of 'defaultTransformOptions.maxRequests'."
);
return this._defaultTransformOptions?.maxRequests;
}
/**
* Deprecated in favor of `defaultTransformOptions.maxRequests`
*
* @deprecated since v0.17, remove in v0.18
*/
set maxRequestsPerTransform(val: number | undefined) {
deprecate(
"The 'maxRequestsPerTransform' property for 'JSONAPSource' has been deprecated in favor of 'defaultTransformOptions.maxRequests'."
);
if (this._defaultTransformOptions === undefined) {
this._defaultTransformOptions = {} as DefaultRequestOptions<TO>;
}
this._defaultTransformOptions.maxRequests = val;
}
/**
* Deprecated in favor of `defaultQueryOptions.maxRequests`
*
* @deprecated since v0.17, remove in v0.18
*/
get maxRequestsPerQuery(): number | undefined {
deprecate(
"The 'maxRequestsPerQuery' property for 'JSONAPSource' has been deprecated in favor of 'defaultQueryOptions.maxRequests'."
);
return this._defaultQueryOptions?.maxRequests;
}
/**
* Deprecated in favor of `defaultQueryOptions.maxRequests`
*
* @deprecated since v0.17, remove in v0.18
*/
set maxRequestsPerQuery(val: number | undefined) {
deprecate(
"The 'maxRequestsPerQuery' property for 'JSONAPSource' has been deprecated in favor of 'defaultQueryOptions.maxRequests'."
);
if (this._defaultQueryOptions === undefined) {
this._defaultQueryOptions = {} as DefaultRequestOptions<QO>;
}
this._defaultQueryOptions.maxRequests = val;
}
/////////////////////////////////////////////////////////////////////////////
// Pushable interface implementation
/////////////////////////////////////////////////////////////////////////////
async _push(
transform: RecordTransform
): Promise<FullResponse<undefined, JSONAPIResponse[], RecordOperation>> {
if (this.transformLog.contains(transform.id)) {
return {};
}
const responses = await this.processTransformRequests(transform);
const details: JSONAPIResponse[] = [];
const transforms: RecordTransform[] = [];
for (let response of responses) {
if (response.transforms) {
Array.prototype.push.apply(transforms, response.transforms);
}
if (response.details) {
details.push(response.details);
}
}
return {
transforms: [transform, ...transforms],
details
};
}
/////////////////////////////////////////////////////////////////////////////
// Pullable interface implementation
/////////////////////////////////////////////////////////////////////////////
async _pull(
query: RecordQuery
): Promise<FullResponse<undefined, JSONAPIResponse[], RecordOperation>> {
const responses = await this.processQueryRequests(query);
const details: JSONAPIResponse[] = [];
const transforms: RecordTransform[] = [];
for (let response of responses) {
if (response.transforms) {
Array.prototype.push.apply(transforms, response.transforms);
}
if (response.details) {
details.push(response.details);
}
}
return {
transforms,
details
};
}
/////////////////////////////////////////////////////////////////////////////
// Queryable interface implementation
/////////////////////////////////////////////////////////////////////////////
async _query(
query: RecordQuery
): Promise<
FullResponse<RecordQueryResult, JSONAPIResponse[], RecordOperation>
> {
const responses = await this.processQueryRequests(query);
const details: JSONAPIResponse[] = [];
const transforms: RecordTransform[] = [];
const data: RecordQueryExpressionResult[] = [];
for (let response of responses) {
if (response.transforms) {
Array.prototype.push.apply(transforms, response.transforms);
}
if (response.details) {
details.push(response.details);
}
data.push(response.data);
}
return {
data: Array.isArray(query.expressions) ? data : data[0],
details,
transforms
};
}
/////////////////////////////////////////////////////////////////////////////
// Updatable interface implementation
/////////////////////////////////////////////////////////////////////////////
async _update(
transform: RecordTransform
): Promise<
FullResponse<RecordTransformResult, JSONAPIResponse[], RecordOperation>
> {
if (this.transformLog.contains(transform.id)) {
return {};
}
const responses = await this.processTransformRequests(transform);
const details: JSONAPIResponse[] = [];
const transforms: RecordTransform[] = [];
const data: RecordOperationResult[] = [];
for (let response of responses) {
if (response.transforms) {
Array.prototype.push.apply(transforms, response.transforms);
}
if (response.details) {
details.push(response.details);
}
data.push(response.data);
}
return {
data: Array.isArray(transform.operations) ? data : data[0],
details,
transforms: [transform, ...transforms]
};
}
protected getQueryRequestProcessor(
request: RecordQueryRequest
): QueryRequestProcessor {
return QueryRequestProcessors[request.op];
}
protected getTransformRequestProcessor(
request: RecordTransformRequest
): TransformRequestProcessor {
return TransformRequestProcessors[request.op];
}
protected async processQueryRequests(
query: RecordQuery
): Promise<QueryRequestProcessorResponse[]> {
const options = this.getQueryOptions(query);
const requests = getQueryRequests(this.requestProcessor, query);
if (
options?.maxRequests !== undefined &&
requests.length > options.maxRequests
) {
throw new QueryNotAllowed(
`This query requires ${requests.length} requests, which exceeds the specified limit of ${options.maxRequests} requests per query.`,
query
);
}
if (options?.parallelRequests) {
return Promise.all(
requests.map((request) => {
const processor = this.getQueryRequestProcessor(request);
return processor(this.requestProcessor, request);
})
);
} else {
const responses = [];
for (let request of requests) {
const processor = this.getQueryRequestProcessor(request);
responses.push(await processor(this.requestProcessor, request));
}
return responses;
}
}
protected async processTransformRequests(
transform: RecordTransform
): Promise<TransformRequestProcessorResponse[]> {
const options = this.getTransformOptions(transform);
const requests = getTransformRequests(this.requestProcessor, transform);
if (
options?.maxRequests !== undefined &&
requests.length > options.maxRequests
) {
throw new TransformNotAllowed(
`This transform requires ${requests.length} requests, which exceeds the specified limit of ${options.maxRequests} requests per transform.`,
transform
);
}
if (options?.parallelRequests) {
return Promise.all(
requests.map((request) => {
const processor = this.getTransformRequestProcessor(request);
return processor(this.requestProcessor, request);
})
);
} else {
const responses = [];
for (let request of requests) {
const processor = this.getTransformRequestProcessor(request);
responses.push(await processor(this.requestProcessor, request));
}
return responses;
}
}
} | the_stack |
export const AWS_CDK_METADATA = new Set([
'us-east-2',
'us-east-1',
'us-west-1',
'us-west-2',
// 'us-gov-east-1',
// 'us-gov-west-1',
// 'us-iso-east-1',
// 'us-isob-east-1',
'af-south-1',
'ap-south-1',
'ap-east-1',
// 'ap-northeast-3',
'ap-northeast-2',
'ap-southeast-1',
'ap-southeast-2',
'ap-northeast-1',
'ca-central-1',
'cn-north-1',
'cn-northwest-1',
'eu-central-1',
'eu-west-1',
'eu-west-2',
'eu-west-3',
'eu-north-1',
'eu-south-1',
'me-south-1',
'sa-east-1',
]);
/**
* The hosted zone Id if using an alias record in Route53.
*
* @see https://docs.aws.amazon.com/general/latest/gr/s3.html#s3_region
*/
export const ROUTE_53_BUCKET_WEBSITE_ZONE_IDS: { [region: string]: string } = {
'af-south-1': 'Z11KHD8FBVPUYU',
'ap-east-1': 'ZNB98KWMFR0R6',
'ap-northeast-1': 'Z2M4EHUR26P7ZW',
'ap-northeast-2': 'Z3W03O7B5YMIYP',
'ap-northeast-3': 'Z2YQB5RD63NC85',
'ap-south-1': 'Z11RGJOFQNVJUP',
'ap-southeast-1': 'Z3O0J2DXBE1FTB',
'ap-southeast-2': 'Z1WCIGYICN2BYD',
'ap-southeast-3': 'Z01613992JD795ZI93075',
'ca-central-1': 'Z1QDHH18159H29',
'cn-northwest-1': 'Z282HJ1KT0DH03',
'eu-central-1': 'Z21DNDUVLTQW6Q',
'eu-north-1': 'Z3BAZG2TWCNX0D',
'eu-south-1': 'Z3IXVV8C73GIO3',
'eu-west-1': 'Z1BKCTXD74EZPE',
'eu-west-2': 'Z3GKZC51ZF0DB4',
'eu-west-3': 'Z3R1K369G5AVDG',
'me-south-1': 'Z1MPMWCPA7YB62',
'sa-east-1': 'Z7KQH4QJS55SO',
'us-east-1': 'Z3AQBSTGFYJSTF',
'us-east-2': 'Z2O1EMRO9K5GLX',
'us-gov-east-1': 'Z2NIFVYYW2VKV1',
'us-gov-west-1': 'Z31GFT0UA1I2HV',
'us-west-1': 'Z2F56UZL2M1ACD',
'us-west-2': 'Z3BJ6K6RIION7M',
};
/**
* The hosted zone Id of the Elastic Beanstalk environment.
*
* @see https://docs.aws.amazon.com/general/latest/gr/elasticbeanstalk.html
*/
export const EBS_ENV_ENDPOINT_HOSTED_ZONE_IDS: { [region: string]: string } = {
'af-south-1': 'Z1EI3BVKMKK4AM',
'ap-east-1': 'ZPWYUBWRU171A',
'ap-northeast-1': 'Z1R25G3KIG2GBW',
'ap-northeast-2': 'Z3JE5OI70TWKCP',
'ap-northeast-3': 'ZNE5GEY1TIAGY',
'ap-south-1': 'Z18NTBI3Y7N9TZ',
'ap-southeast-1': 'Z16FZ9L249IFLT',
'ap-southeast-2': 'Z2PCDNR3VC2G1N',
'ca-central-1': 'ZJFCZL7SSZB5I',
'eu-central-1': 'Z1FRNW7UH4DEZJ',
'eu-north-1': 'Z23GO28BZ5AETM',
'eu-south-1': 'Z10VDYYOA2JFKM',
'eu-west-1': 'Z2NYPWQ7DFZAZH',
'eu-west-2': 'Z1GKAAAUGATPF1',
'eu-west-3': 'Z5WN6GAYWG5OB',
'me-south-1': 'Z2BBTEKR2I36N2',
'sa-east-1': 'Z10X7K2B4QSOFV',
'us-east-1': 'Z117KPS5GTRQ2G',
'us-east-2': 'Z14LCN19Q5QHIC',
'us-gov-east-1': 'Z35TSARG0EJ4VU',
'us-gov-west-1': 'Z4KAURWC4UUUG',
'us-west-1': 'Z1LQECGX5PH1X',
'us-west-2': 'Z38NKT9BP95V3O',
};
interface Region { partition: string, domainSuffix: string }
export const PARTITION_MAP: { [region: string]: Region } = {
'default': { partition: 'aws', domainSuffix: 'amazonaws.com' },
'cn-': { partition: 'aws-cn', domainSuffix: 'amazonaws.com.cn' },
'us-gov-': { partition: 'aws-us-gov', domainSuffix: 'amazonaws.com' },
'us-iso-': { partition: 'aws-iso', domainSuffix: 'c2s.ic.gov' },
'us-isob-': { partition: 'aws-iso-b', domainSuffix: 'sc2s.sgov.gov' },
};
// https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-logging-bucket-permissions
// https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-access-logs.html#attach-bucket-policy
export const ELBV2_ACCOUNTS: { [region: string]: string } = {
'af-south-1': '098369216593',
'ap-east-1': '754344448648',
'ap-northeast-1': '582318560864',
'ap-northeast-2': '600734575887',
'ap-northeast-3': '383597477331',
'ap-south-1': '718504428378',
'ap-southeast-1': '114774131450',
'ap-southeast-2': '783225319266',
'ap-southeast-3': '589379963580',
'ca-central-1': '985666609251',
'cn-north-1': '638102146993',
'cn-northwest-1': '037604701340',
'eu-central-1': '054676820928',
'eu-north-1': '897822967062',
'eu-south-1': '635631232127',
'eu-west-1': '156460612806',
'eu-west-2': '652711504416',
'eu-west-3': '009996457667',
'me-south-1': '076674570225',
'sa-east-1': '507241528517',
'us-east-1': '127311923021',
'us-east-2': '033677994240',
'us-gov-east-1': '190560391635',
'us-gov-west-1': '048591011584',
'us-west-1': '027434742980',
'us-west-2': '797873946194',
};
// https://aws.amazon.com/releasenotes/available-deep-learning-containers-images
export const DLC_REPOSITORY_ACCOUNTS: { [region: string]: string } = {
'ap-east-1': '871362719292',
'ap-northeast-1': '763104351884',
'ap-northeast-2': '763104351884',
'ap-south-1': '763104351884',
'ap-southeast-1': '763104351884',
'ap-southeast-2': '763104351884',
'ca-central-1': '763104351884',
'cn-north-1': '727897471807',
'cn-northwest-1': '727897471807',
'eu-central-1': '763104351884',
'eu-north-1': '763104351884',
'eu-west-1': '763104351884',
'eu-west-2': '763104351884',
'eu-west-3': '763104351884',
'me-south-1': '217643126080',
'sa-east-1': '763104351884',
'us-east-1': '763104351884',
'us-east-2': '763104351884',
'us-west-1': '763104351884',
'us-west-2': '763104351884',
};
// https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html
// https://docs.amazonaws.cn/app-mesh/latest/userguide/envoy.html
export const APPMESH_ECR_ACCOUNTS: { [region: string]: string } = {
'af-south-1': '924023996002',
'ap-east-1': '856666278305',
'ap-northeast-1': '840364872350',
'ap-northeast-2': '840364872350',
'ap-northeast-3': '840364872350',
'ap-south-1': '840364872350',
'ap-southeast-1': '840364872350',
'ap-southeast-2': '840364872350',
'ca-central-1': '840364872350',
'cn-north-1': '919366029133',
'cn-northwest-1': '919830735681',
'eu-central-1': '840364872350',
'eu-north-1': '840364872350',
'eu-south-1': '422531588944',
'eu-west-1': '840364872350',
'eu-west-2': '840364872350',
'eu-west-3': '840364872350',
'me-south-1': '772975370895',
'sa-east-1': '840364872350',
'us-east-1': '840364872350',
'us-east-2': '840364872350',
'us-west-1': '840364872350',
'us-west-2': '840364872350',
};
// https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights-extension-versions.html
export const CLOUDWATCH_LAMBDA_INSIGHTS_ARNS: { [key: string]: any } = {
'1.0.135.0': {
arm64: {
// US East (N. Virginia)
'us-east-1': 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// US East (Ohio)
'us-east-2': 'arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// US West (Oregon)
'us-west-2': 'arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// Asia Pacific (Mumbai)
'ap-south-1': 'arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// Asia Pacific (Singapore)
'ap-southeast-1': 'arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// Asia Pacific (Sydney)
'ap-southeast-2': 'arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// Asia Pacific (Tokyo)
'ap-northeast-1': 'arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// Europe (Frankfurt)
'eu-central-1': 'arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// Europe (Ireland)
'eu-west-1': 'arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:2',
// Europe (London)
'eu-west-2': 'arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:2',
},
x86_64: {
// US East (N. Virginia)
'us-east-1': 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:18',
// US East (Ohio)
'us-east-2': 'arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:18',
// US West (N. California)
'us-west-1': 'arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:18',
// US West (Oregon)
'us-west-2': 'arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:18',
// Africa (Cape Town)
'af-south-1': 'arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:11',
// Asia Pacific (Hong Kong)
'ap-east-1': 'arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:11',
// Asia Pacific (Mumbai)
'ap-south-1': 'arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:18',
// Asia Pacific (Oskaka)
'ap-northeast-3': 'arn:aws:lambda:ap-northeast-3:194566237122:layer:LambdaInsightsExtension:1',
// Asia Pacific (Seoul)
'ap-northeast-2': 'arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:18',
// Asia Pacific (Singapore)
'ap-southeast-1': 'arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:18',
// Asia Pacific (Sydney)
'ap-southeast-2': 'arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:18',
// Asia Pacific (Tokyo)
'ap-northeast-1': 'arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:25',
// Canada (Central)
'ca-central-1': 'arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:18',
// China (Beijing)
'cn-north-1': 'arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:11',
// China (Ningxia)
'cn-northwest-1': 'arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:11',
// Europe (Frankfurt)
'eu-central-1': 'arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:18',
// Europe (Ireland)
'eu-west-1': 'arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:18',
// Europe (London)
'eu-west-2': 'arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:18',
// Europe (Milan)
'eu-south-1': 'arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:11',
// Europe (Paris)
'eu-west-3': 'arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:18',
// Europe (Stockholm)
'eu-north-1': 'arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:18',
// Middle East (Bahrain)
'me-south-1': 'arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:11',
// South America (Sao Paulo)
'sa-east-1': 'arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:18',
},
},
'1.0.119.0': {
arm64: {
// US East (N. Virginia)
'us-east-1': 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// US East (Ohio)
'us-east-2': 'arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// US West (Oregon)
'us-west-2': 'arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// Asia Pacific (Mumbai)
'ap-south-1': 'arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// Asia Pacific (Singapore)
'ap-southeast-1': 'arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// Asia Pacific (Sydney)
'ap-southeast-2': 'arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// Asia Pacific (Tokyo)
'ap-northeast-1': 'arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// Europe (Frankfurt)
'eu-central-1': 'arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// Europe (Ireland)
'eu-west-1': 'arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension-Arm64:1',
// Europe (London)
'eu-west-2': 'arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension-Arm64:1',
},
x86_64: {
// US East (N. Virginia)
'us-east-1': 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:16',
// US East (Ohio)
'us-east-2': 'arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:16',
// US West (N. California)
'us-west-1': 'arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:16',
// US West (Oregon)
'us-west-2': 'arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:16',
// Africa (Cape Town)
'af-south-1': 'arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:9',
// Asia Pacific (Hong Kong)
'ap-east-1': 'arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:9',
// Asia Pacific (Mumbai)
'ap-south-1': 'arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:16',
// Asia Pacific (Seoul)
'ap-northeast-2': 'arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:16',
// Asia Pacific (Singapore)
'ap-southeast-1': 'arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:16',
// Asia Pacific (Sydney)
'ap-southeast-2': 'arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:16',
// Asia Pacific (Tokyo)
'ap-northeast-1': 'arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:23',
// Canada (Central)
'ca-central-1': 'arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:16',
// China (Beijing)
'cn-north-1': 'arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:9',
// China (Ningxia)
'cn-northwest-1': 'arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:9',
// Europe (Frankfurt)
'eu-central-1': 'arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:16',
// Europe (Ireland)
'eu-west-1': 'arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:16',
// Europe (London)
'eu-west-2': 'arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:16',
// Europe (Milan)
'eu-south-1': 'arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:9',
// Europe (Paris)
'eu-west-3': 'arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:16',
// Europe (Stockholm)
'eu-north-1': 'arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:16',
// Middle East (Bahrain)
'me-south-1': 'arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:9',
// South America (Sao Paulo)
'sa-east-1': 'arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:16',
},
},
'1.0.98.0': {
x86_64: {
'us-east-1': 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14',
'us-east-2': 'arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:14',
'us-west-1': 'arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:14',
'us-west-2': 'arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:14',
'af-south-1': 'arn:aws:lambda:af-south-1:012438385374:layer:LambdaInsightsExtension:8',
'ap-east-1': 'arn:aws:lambda:ap-east-1:519774774795:layer:LambdaInsightsExtension:8',
'ap-south-1': 'arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:14',
'ap-northeast-2': 'arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:14',
'ap-southeast-1': 'arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:14',
'ap-southeast-2': 'arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:14',
'ap-northeast-1': 'arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:14',
'ca-central-1': 'arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:14',
'cn-north-1': 'arn:aws-cn:lambda:cn-north-1:488211338238:layer:LambdaInsightsExtension:8',
'cn-northwest-1': 'arn:aws-cn:lambda:cn-northwest-1:488211338238:layer:LambdaInsightsExtension:8',
'eu-central-1': 'arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:14',
'eu-west-1': 'arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:14',
'eu-west-2': 'arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:14',
'eu-south-1': 'arn:aws:lambda:eu-south-1:339249233099:layer:LambdaInsightsExtension:8',
'eu-west-3': 'arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:14',
'eu-north-1': 'arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:14',
'me-south-1': 'arn:aws:lambda:me-south-1:285320876703:layer:LambdaInsightsExtension:8',
'sa-east-1': 'arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:14',
},
},
'1.0.89.0': {
x86_64: {
'us-east-1': 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:12',
'us-east-2': 'arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:12',
'us-west-1': 'arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:12',
'us-west-2': 'arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:12',
'ap-south-1': 'arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:12',
'ap-northeast-2': 'arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:12',
'ap-southeast-1': 'arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:12',
'ap-southeast-2': 'arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:12',
'ap-northeast-1': 'arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:12',
'ca-central-1': 'arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:12',
'eu-central-1': 'arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:12',
'eu-west-1': 'arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:12',
'eu-west-2': 'arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:12',
'eu-west-3': 'arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:12',
'eu-north-1': 'arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:12',
'sa-east-1': 'arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:12',
},
},
'1.0.86.0': {
x86_64: {
'us-east-1': 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:11',
'us-east-2': 'arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:11',
'us-west-1': 'arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:11',
'us-west-2': 'arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:11',
'ap-south-1': 'arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:11',
'ap-northeast-2': 'arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:11',
'ap-southeast-1': 'arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:11',
'ap-southeast-2': 'arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:11',
'ap-northeast-1': 'arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:11',
'ca-central-1': 'arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:11',
'eu-central-1': 'arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:11',
'eu-west-1': 'arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:11',
'eu-west-2': 'arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:11',
'eu-west-3': 'arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:11',
'eu-north-1': 'arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:11',
'sa-east-1': 'arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:11',
},
},
'1.0.54.0': {
x86_64: {
'us-east-1': 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:2',
'us-east-2': 'arn:aws:lambda:us-east-2:580247275435:layer:LambdaInsightsExtension:2',
'us-west-1': 'arn:aws:lambda:us-west-1:580247275435:layer:LambdaInsightsExtension:2',
'us-west-2': 'arn:aws:lambda:us-west-2:580247275435:layer:LambdaInsightsExtension:2',
'ap-south-1': 'arn:aws:lambda:ap-south-1:580247275435:layer:LambdaInsightsExtension:2',
'ap-northeast-2': 'arn:aws:lambda:ap-northeast-2:580247275435:layer:LambdaInsightsExtension:2',
'ap-southeast-1': 'arn:aws:lambda:ap-southeast-1:580247275435:layer:LambdaInsightsExtension:2',
'ap-southeast-2': 'arn:aws:lambda:ap-southeast-2:580247275435:layer:LambdaInsightsExtension:2',
'ap-northeast-1': 'arn:aws:lambda:ap-northeast-1:580247275435:layer:LambdaInsightsExtension:2',
'ca-central-1': 'arn:aws:lambda:ca-central-1:580247275435:layer:LambdaInsightsExtension:2',
'eu-central-1': 'arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:2',
'eu-west-1': 'arn:aws:lambda:eu-west-1:580247275435:layer:LambdaInsightsExtension:2',
'eu-west-2': 'arn:aws:lambda:eu-west-2:580247275435:layer:LambdaInsightsExtension:2',
'eu-west-3': 'arn:aws:lambda:eu-west-3:580247275435:layer:LambdaInsightsExtension:2',
'eu-north-1': 'arn:aws:lambda:eu-north-1:580247275435:layer:LambdaInsightsExtension:2',
'sa-east-1': 'arn:aws:lambda:sa-east-1:580247275435:layer:LambdaInsightsExtension:2',
},
},
};
// https://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-rs-vpc
export const FIREHOSE_CIDR_BLOCKS: { [region: string]: string } = {
'af-south-1': '13.244.121.224',
'ap-east-1': '18.162.221.32',
'ap-northeast-1': '13.113.196.224',
'ap-northeast-2': '13.209.1.64',
'ap-northeast-3': '13.208.177.192',
'ap-south-1': '13.232.67.32',
'ap-southeast-1': '13.228.64.192',
'ap-southeast-2': '13.210.67.224',
'ca-central-1': '35.183.92.128',
'cn-north-1': '52.81.151.32',
'cn-northwest-1': '161.189.23.64',
'eu-central-1': '35.158.127.160',
'eu-north-1': '13.53.63.224',
'eu-south-1': '15.161.135.128',
'eu-west-1': '52.19.239.192',
'eu-west-2': '18.130.1.96',
'eu-west-3': '35.180.1.96',
'me-south-1': '15.185.91.0',
'sa-east-1': '18.228.1.128',
'us-east-1': '52.70.63.192',
'us-east-2': '13.58.135.96',
'us-gov-east-1': '18.253.138.96',
'us-gov-west-1': '52.61.204.160',
'us-west-1': '13.57.135.192',
'us-west-2': '52.89.255.224',
}; | the_stack |
import * as React from "react";
/**
* Attribute definitions
*/
type Attribute =
| "boolean"
| "date"
| "datetime"
| "enum"
| "multienum"
| "html"
| "string"
| "stringlist"
| "integer"
| "float"
| "binary"
| "link"
| "linklist"
| "reference"
| "referencelist"
| "widgetlist";
interface AttributeOptions {
values?: string[] | undefined;
only?: string | string[] | undefined;
}
type AttributeWithOptions = [Attribute, AttributeOptions];
interface OptimizeFor {
width?: number | string | undefined;
height?: number | string | undefined;
}
interface OptimizeForFit extends OptimizeFor {
fit: "crop";
crop: "center" | "top" | "left" | "right" | "bottom";
}
interface OptimizeForResize extends OptimizeFor {
fit: "resize";
}
type OptimizeDefinition = OptimizeForFit | OptimizeForResize;
/**
* Binary definitions
*/
interface UploadOptions {
filename: string;
contentType?: string | undefined;
}
export class Binary {
private constructor();
static upload(source: Blob | File, options: UploadOptions): FutureBinary;
contentLength(): number;
contentType(): string;
copy(options?: { filename?: string | undefined; contentType?: string | undefined }): FutureBinary;
filename(): string;
isPrivate(): boolean;
metadata(): MetadataCollection;
optimizeFor(definition: OptimizeDefinition): Binary;
original(): Binary;
raw(): Binary;
url(): string;
}
export class FutureBinary {
private constructor();
into(target: Obj): Promise<Binary>;
}
/**
* Component definitions
*/
interface CSSImageStyleBackgroundProps {
image: Obj | Binary | string;
attachment?: React.CSSProperties["backgroundAttachment"] | undefined;
clip?: React.CSSProperties["backgroundClip"] | undefined;
color?: React.CSSProperties["backgroundColor"] | undefined;
origin?: React.CSSProperties["backgroundOrigin"] | undefined;
position?: React.CSSProperties["backgroundPosition"] | undefined;
repeat?: React.CSSProperties["backgroundRepeat"] | undefined;
size?: React.CSSProperties["backgroundSize"] | undefined;
}
type CSSPropsWithoutBackground = Omit<
React.CSSProperties,
| "background"
| "backgroundAttachment"
| "backgroundClip"
| "backgroundColor"
| "backgroundPosition"
| "backgroundRepeat"
| "backgroundSize"
>;
interface BackgroundImageBackgroundProp {
background: CSSImageStyleBackgroundProps | CSSImageStyleBackgroundProps[];
}
interface BackgroundImageTagProps {
tag?: string | undefined;
style: CSSPropsWithoutBackground & BackgroundImageBackgroundProp;
className?: string | undefined;
}
export class BackgroundImageTag extends React.Component<BackgroundImageTagProps, any> {}
interface ChildListTagProps {
parent?: Obj | undefined;
tag?: string | undefined;
renderChild?: ((child: Obj) => React.ReactElement) | undefined;
className?: string | undefined;
}
export class ChildListTag extends React.Component<ChildListTagProps, any> {}
interface ContentTagProps extends Omit<React.AllHTMLAttributes<any>, "content"> {
attribute: string;
content?: Obj | Widget | undefined;
tag?: string | undefined;
page?: any;
widgetProps?: object | undefined;
}
export class ContentTag extends React.Component<ContentTagProps, any> {}
export class CurrentPage extends React.Component<{}, any> {}
interface ImageTagProps extends React.HTMLAttributes<HTMLImageElement> {
attribute?: string | undefined;
content: Binary | Obj | Widget;
alt?: string | undefined;
}
export class ImageTag extends React.Component<ImageTagProps, any> {}
export class InPlaceEditingOff extends React.Component<any, any> {}
interface LinkTagProps extends React.HTMLAttributes<HTMLAnchorElement> {
to: Obj | Link;
params?: object | undefined;
onClick?: ((event: React.MouseEvent) => void) | undefined;
}
export class LinkTag extends React.Component<LinkTagProps, any> {}
export class NotFoundErrorPage extends React.Component<{}, any> {}
export class RestoreInPlaceEditing extends React.Component<{}, any> {}
interface WidgetTagProps extends React.HTMLAttributes<any> {
tag?: string | undefined;
[key: string]: any;
}
export class WidgetTag extends React.Component<WidgetTagProps, any> {}
type Priority = "foreground" | "background";
/**
* Config definitions
*/
interface ConfigOptions {
tenant: string;
homepage?: (() => Obj | null) | undefined;
origin?: string | undefined;
routingBasePath?: string | undefined;
visitorAuthentication?: boolean | undefined;
// Hard to type
constraintsValidation?: ((constraints: any) => any) | undefined;
endpoint?: string | undefined;
priority?: Priority | undefined;
adoptUi?: boolean | undefined;
baseUrlForSite?: ((siteId: string) => string | undefined) | undefined;
siteForUrl?: ((url: string) => { siteId: string; baseUrl: string } | undefined) | undefined;
}
/**
* EditingConfig definitions
*/
interface AttributeValue {
value: string;
title: string;
}
interface AttributeProps {
title?: string | undefined;
description?: string | undefined;
values?: AttributeValue[] | undefined;
options?: {
toolbar: string[];
} | undefined;
}
interface EditingConfigAttributes {
[key: string]: AttributeProps;
}
// TODO talk about this with krishan
interface PropertiesGroup {
title: string;
component?: string | undefined;
properties?: string[] | undefined;
}
export type ValidationReturnType = { message: string; severity: string } | string | undefined;
type AttributeValidationCallback = (
current: any,
options?: { obj?: Obj | undefined; widget?: Widget | undefined; content: any; name: string },
) => ValidationReturnType;
export type AttributeBasedValidation = [string, AttributeValidationCallback];
export type ClassBasedValidation = (target: Widget | Obj) => ValidationReturnType;
export type Validation = AttributeBasedValidation | ClassBasedValidation;
interface EditingConfig {
title?: string | undefined;
thumbnail?: string | undefined;
description?: string | undefined;
titleForContent?: ((instance: Obj | Widget) => string | void) | undefined;
descriptionForContent?: ((instance: Obj | Widget) => string) | undefined;
attributes?: EditingConfigAttributes | undefined;
properties?: string[] | undefined;
propertiesGroups?: PropertiesGroup[] | undefined;
hideInSelectionDialogs?: boolean | undefined;
initialContent?: Record<string, any> | undefined;
initialize?: ((instance: Obj) => void) | undefined;
initializeCopy?: ((originalInstance: Obj) => void) | undefined;
validations?: Validation[] | undefined;
}
/**
* Link definitions
*/
interface InternalLinkAttributes {
hash?: string | undefined;
obj: Obj;
query?: string | undefined;
rel?: string | undefined;
target?: string | undefined;
title?: string | undefined;
}
interface ExternalLinkAttributes {
rel?: string | undefined;
target?: string | undefined;
title?: string | undefined;
url: string;
}
// Less guarantees
export class Link extends __Link {
constructor(attributes: InternalLinkAttributes | ExternalLinkAttributes);
hash(): string | null;
obj(): Obj | null;
query(): string | null;
url(): string | null;
}
declare class __Link {
copy(attributes: InternalLinkAttributes): InternalLink;
copy(attributes: ExternalLinkAttributes): ExternalLink;
isExternal(): boolean;
isInternal(): boolean;
queryParamters(): any;
rel(): string | null;
target(): string | null;
title(): string | null;
}
// There are just interfaces and not newable
interface InternalLink extends __Link {
hash(): string;
obj(): Obj;
query(): string;
}
interface ExternalLink extends __Link {
url(): string;
}
/**
* MetadataCollection definitions
*/
export class MetadataCollection {
private constructor();
get(name: string): string | string[] | number | Date | null;
}
interface CreateAttributes {
[key: string]: any;
}
type ObjSearchOperator =
| "equals"
| "contains"
| "containsPrefix"
| "equals"
| "startsWith"
| "isLessThan"
| "isGreaterThan"
| "linksTo"
| "refersTo";
type ObjSearchSingleAttribute =
| "*"
| "id"
| "_createdAt"
| "_lastChanged"
| "_objClass"
| "_path"
| "_permalink"
| "_restriction"
| "MetadataCollection"
| string;
type ObjSearchValue = string | Date | number | Obj | any[];
type ObjSearchAttribute = ObjSearchSingleAttribute | ObjSearchSingleAttribute[];
interface ObjSearchAttributeBasedBoost {
[key: string]: number;
}
type OrderParam = ObjSearchSingleAttribute | [ObjSearchSingleAttribute, "asc" | "desc"];
interface ObjFacetValue {
count: () => number;
includedObjs(): Obj[];
name: () => string;
}
export interface ObjSearch {
and: (
attribute: ObjSearchAttribute,
operator: ObjSearchOperator,
value: ObjSearchValue,
boost?: ObjSearchAttributeBasedBoost,
) => ObjSearch;
andNot: (
attribute: ObjSearchAttribute,
operator: Extract<ObjSearchOperator, "equals" | "startsWith" | "isGreaterThan" | "isLessThan">,
value: ObjSearchValue,
) => ObjSearch;
boost: (
attribute: ObjSearchAttribute,
operator: ObjSearchOperator,
value: ObjSearchValue,
factor: number,
) => ObjSearch;
count: () => number;
facet: (attribute: ObjSearchSingleAttribute, option?: { limit: number; includeObjs: number }) => ObjFacetValue;
first: () => Obj | null;
offset: (offSet: number) => ObjSearch;
order: (attributeOrAttributes: OrderParam | OrderParam[], direction: "asc" | "desc") => ObjSearch;
suggest: (prefix: string, options?: { limit: number; attributes: ObjSearchSingleAttribute[] }) => string[];
take: (count?: number) => Obj[];
toArray: () => Obj[];
}
export class Obj {
private constructor(arg: object);
private readonly _createdAt: Date;
private readonly _firstPublishedAt: Date;
private readonly _lastChanged: Date;
private readonly _objClass: string;
private readonly _path: string;
private readonly _permalink: string;
private readonly _publishedAt: Date;
private readonly _siteId: string | null;
private readonly _language: string;
// Static methods
static all(): ObjSearch;
static create(attributes?: CreateAttributes): Obj;
static createFromFile(file: File, attributes: CreateAttributes): Promise<Obj>;
static get(id: string): Obj | null;
static getByPath(path: string): Obj | null;
static getByPermalink(permalink: string): Obj | null;
static root(): Obj | null;
static where(
attribute: ObjSearchSingleAttribute,
operator: ObjSearchOperator,
value: ObjSearchValue,
boost?: any,
): ObjSearch;
static onSite(siteId: string): SiteContext;
static onAllSites(): SiteContext;
// Instance methods
id(): string;
ancestors(): Obj[];
backlinks(): Obj[];
children(): Obj[];
contentLength(): number;
contentType(): string;
contentUrl(): string;
copy(): Promise<Obj>;
createdAt(): Date;
destroy(): void;
firstPublishedAt(): Date | null;
get(attributeName: string): any;
isBinary(): boolean;
isRestricted(): boolean;
lastChanged(): Date | null;
metadata(): MetadataCollection;
modification(): null | "new" | "edited" | "deleted";
objClass(): string;
parent(): Obj | null;
path(): string | null;
permalink(): string | null;
publishedAt(): Date | null;
restrict(): void;
slug(): string;
unrestrict(): void;
update(attributes: any): void;
widget(id: string): Widget | null;
widgets(): Widget[];
updateReferences(mapping: (refId: string) => string | undefined): Promise<void>;
finishSaving(): Promise<void>;
onAllSites(): SiteContext;
onSite(siteId: string): SiteContext;
siteId(): string | null;
language(): string | null;
}
type ExtractableTextAttributes = "string" | "html" | "widgetlist" | "blob:text";
interface SiteContext {
all(): ObjSearch;
create(attributes: object): Obj;
createFromFile(file: File, attributes: object): Promise<void>;
get(id: string): Obj | null;
getByPath(path: string): Obj | null;
getByPermalink(permalink: string): Obj | null;
root(): Obj | null;
where(attribute: ObjSearchSingleAttribute, operator: ObjSearchOperator, value: string, boost?: any): ObjSearch;
}
interface ObjClassOptions {
attributes: Record<string, Attribute | AttributeWithOptions>;
extractTextAttributes?: string[] | undefined;
extend?: ObjClass | undefined;
onlyChildren: string | string[];
onlyInside: string | string[];
}
export type ObjClass = typeof Obj;
declare abstract class AbstractObjClass {}
/**
* Widget definitions
*/
export class Widget {
constructor(arg: object);
private readonly _id: string;
private _objClass: string;
// Instace methods
container(): Obj | Widget;
copy(): void;
destroy(): void;
get(attributeName: string): any;
id(): string;
obj(): Obj;
objClass(): string;
update(attributes: any): void;
}
interface WidgetClassOptions {
attributes: Record<string, Attribute | AttributeWithOptions>;
extractTextAttributes?: string[] | undefined;
extend?: WidgetClass | undefined;
onlyInside?: string | string[] | undefined;
}
type WidgetClass = typeof Widget;
declare abstract class AbstractWidgetClass {}
/**
* scrivito top-level definitions
*/
interface WidgetComponentProps {
widget: Widget;
[key: string]: any;
}
interface ObjComponentProps {
page: Obj;
params: {};
[key: string]: any;
}
type WidgetComponent = React.ComponentType<WidgetComponentProps>;
type ObjComponent = React.ComponentType<ObjComponentProps>;
export interface AuthGroupsOptions {
[groupName: string]: string;
}
export class Editor {
private constructor();
id(): string;
name(): string;
teams(): Team[];
}
export class Team {
private constructor();
description(): string;
id(): string;
name(): string;
}
interface MenuPosition {
before: string;
after: string;
}
interface MenuInsertParameters {
id: string;
title: string;
icon?: string | undefined;
description?: string | undefined;
position?: MenuPosition | undefined;
group?: string | undefined;
onClick: () => void;
enabled?: boolean | undefined;
}
type MenuModifyParameters = Pick<MenuInsertParameters, "id" | "group" | "icon" | "position" | "title">;
interface Menu {
insert: (params: MenuInsertParameters) => void;
remove: (id: string) => void;
modify: (params: MenuModifyParameters) => void;
}
export type ValidationResultSeverity = "error" | "warning" | "info";
export interface ValidationResult {
message: string;
severity: ValidationResultSeverity;
}
declare class Workspace {
private constructor();
id(): string;
title(): string;
}
export function canWrite(): boolean;
export function configure(options: ConfigOptions): void;
export function configureContentBrowser(options: any): void;
export function connect<C extends React.ComponentType<any>>(component: C): C;
export function currentPage(): Obj;
export function currentPageParams(): any;
export function extendMenu(menuCallback: (menu: Menu) => void): void;
export function extractText(obj: Obj, options: { length: number }): string;
export function finishLoading(): Promise<{}>;
export function getClass(name: string): ObjClass | WidgetClass | null;
export function isEditorLoggedIn(): boolean;
export function isInPlaceEditingActive(): boolean;
export function load<T>(functionToLoad: () => T): Promise<T>;
export function navigateTo(target: (() => Obj | Link) | Obj | Link, options?: { hash?: string | undefined; params?: any }): void;
export function openDialog(name: string): void;
export function preload(preloadDump: any): Promise<{ dumpLoaded: boolean }>;
export function provideComponent(className: string, component: WidgetComponent | ObjComponent): void;
export function provideEditingConfig(name: string, editingConfig: EditingConfig): void;
export function provideAuthGroups(options: AuthGroupsOptions): void;
export function createObjClass(options: ObjClassOptions): Obj;
export function createWidgetClass(options: WidgetClassOptions): AbstractWidgetClass;
export function provideObjClass(name: string, contentClassOrOptions: ObjClassOptions | AbstractObjClass): ObjClass;
export function provideWidgetClass(
name: string,
contentClassOrOptions: WidgetClassOptions | AbstractWidgetClass,
): WidgetClass;
export function registerComponent(name: string, component: WidgetComponent | ObjComponent): void;
export function renderPage(page: Obj, renderFunction: () => void): Promise<{ result: Obj; preloadDump: any }>;
export function setVisitorIdToken(idToken: string): void;
export function updateContent(): void;
export function updateMenuExtensions(): void;
export function urlFor(target: Obj | Binary | Link, options?: { query?: string | undefined; hash?: string | undefined }): string;
export function useHistory(history: History): void;
export function validationResultsFor(model: Obj | Widget, attribute: string): ValidationResult[];
export function isComparisonActive(): boolean;
export function currentWorkspaceId(): string;
export function currentWorkspace(): Workspace;
export function currentEditor(): Editor | null;
export function configureObjClassForContentType(mapping?: { [key: string]: string }): void;
// utility types
type AttributeKeys<T extends WidgetClassOptions | ObjClassOptions> = {
[Property in keyof T["attributes"]]: any;
};
export type {
AttributeOptions,
AttributeProps,
AttributeValue,
AttributeKeys,
BackgroundImageBackgroundProp,
BackgroundImageTagProps,
ChildListTagProps,
ConfigOptions,
ContentTagProps,
CreateAttributes,
CSSImageStyleBackgroundProps,
EditingConfig,
EditingConfigAttributes,
ExternalLink,
ExternalLinkAttributes,
ImageTagProps,
InternalLink,
InternalLinkAttributes,
LinkTagProps,
ObjClassOptions,
ObjComponentProps,
OptimizeDefinition,
PropertiesGroup,
WidgetClassOptions,
WidgetComponentProps,
WidgetTagProps,
SiteContext,
};
// Disables automatic exports
export {}; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { ManagementLocks } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ManagementLockClient } from "../managementLockClient";
import {
ManagementLockObject,
ManagementLocksListAtResourceGroupLevelNextOptionalParams,
ManagementLocksListAtResourceGroupLevelOptionalParams,
ManagementLocksListAtResourceLevelNextOptionalParams,
ManagementLocksListAtResourceLevelOptionalParams,
ManagementLocksListAtSubscriptionLevelNextOptionalParams,
ManagementLocksListAtSubscriptionLevelOptionalParams,
ManagementLocksListByScopeNextOptionalParams,
ManagementLocksListByScopeOptionalParams,
ManagementLocksCreateOrUpdateAtResourceGroupLevelOptionalParams,
ManagementLocksCreateOrUpdateAtResourceGroupLevelResponse,
ManagementLocksDeleteAtResourceGroupLevelOptionalParams,
ManagementLocksGetAtResourceGroupLevelOptionalParams,
ManagementLocksGetAtResourceGroupLevelResponse,
ManagementLocksCreateOrUpdateByScopeOptionalParams,
ManagementLocksCreateOrUpdateByScopeResponse,
ManagementLocksDeleteByScopeOptionalParams,
ManagementLocksGetByScopeOptionalParams,
ManagementLocksGetByScopeResponse,
ManagementLocksCreateOrUpdateAtResourceLevelOptionalParams,
ManagementLocksCreateOrUpdateAtResourceLevelResponse,
ManagementLocksDeleteAtResourceLevelOptionalParams,
ManagementLocksGetAtResourceLevelOptionalParams,
ManagementLocksGetAtResourceLevelResponse,
ManagementLocksCreateOrUpdateAtSubscriptionLevelOptionalParams,
ManagementLocksCreateOrUpdateAtSubscriptionLevelResponse,
ManagementLocksDeleteAtSubscriptionLevelOptionalParams,
ManagementLocksGetAtSubscriptionLevelOptionalParams,
ManagementLocksGetAtSubscriptionLevelResponse,
ManagementLocksListAtResourceGroupLevelResponse,
ManagementLocksListAtResourceLevelResponse,
ManagementLocksListAtSubscriptionLevelResponse,
ManagementLocksListByScopeResponse,
ManagementLocksListAtResourceGroupLevelNextResponse,
ManagementLocksListAtResourceLevelNextResponse,
ManagementLocksListAtSubscriptionLevelNextResponse,
ManagementLocksListByScopeNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing ManagementLocks operations. */
export class ManagementLocksImpl implements ManagementLocks {
private readonly client: ManagementLockClient;
/**
* Initialize a new instance of the class ManagementLocks class.
* @param client Reference to the service client
*/
constructor(client: ManagementLockClient) {
this.client = client;
}
/**
* Gets all the management locks for a resource group.
* @param resourceGroupName The name of the resource group containing the locks to get.
* @param options The options parameters.
*/
public listAtResourceGroupLevel(
resourceGroupName: string,
options?: ManagementLocksListAtResourceGroupLevelOptionalParams
): PagedAsyncIterableIterator<ManagementLockObject> {
const iter = this.listAtResourceGroupLevelPagingAll(
resourceGroupName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listAtResourceGroupLevelPagingPage(
resourceGroupName,
options
);
}
};
}
private async *listAtResourceGroupLevelPagingPage(
resourceGroupName: string,
options?: ManagementLocksListAtResourceGroupLevelOptionalParams
): AsyncIterableIterator<ManagementLockObject[]> {
let result = await this._listAtResourceGroupLevel(
resourceGroupName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listAtResourceGroupLevelNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listAtResourceGroupLevelPagingAll(
resourceGroupName: string,
options?: ManagementLocksListAtResourceGroupLevelOptionalParams
): AsyncIterableIterator<ManagementLockObject> {
for await (const page of this.listAtResourceGroupLevelPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Gets all the management locks for a resource or any level below resource.
* @param resourceGroupName The name of the resource group containing the locked resource. The name is
* case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param parentResourcePath The parent resource identity.
* @param resourceType The resource type of the locked resource.
* @param resourceName The name of the locked resource.
* @param options The options parameters.
*/
public listAtResourceLevel(
resourceGroupName: string,
resourceProviderNamespace: string,
parentResourcePath: string,
resourceType: string,
resourceName: string,
options?: ManagementLocksListAtResourceLevelOptionalParams
): PagedAsyncIterableIterator<ManagementLockObject> {
const iter = this.listAtResourceLevelPagingAll(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listAtResourceLevelPagingPage(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
options
);
}
};
}
private async *listAtResourceLevelPagingPage(
resourceGroupName: string,
resourceProviderNamespace: string,
parentResourcePath: string,
resourceType: string,
resourceName: string,
options?: ManagementLocksListAtResourceLevelOptionalParams
): AsyncIterableIterator<ManagementLockObject[]> {
let result = await this._listAtResourceLevel(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listAtResourceLevelNext(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listAtResourceLevelPagingAll(
resourceGroupName: string,
resourceProviderNamespace: string,
parentResourcePath: string,
resourceType: string,
resourceName: string,
options?: ManagementLocksListAtResourceLevelOptionalParams
): AsyncIterableIterator<ManagementLockObject> {
for await (const page of this.listAtResourceLevelPagingPage(
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
options
)) {
yield* page;
}
}
/**
* Gets all the management locks for a subscription.
* @param options The options parameters.
*/
public listAtSubscriptionLevel(
options?: ManagementLocksListAtSubscriptionLevelOptionalParams
): PagedAsyncIterableIterator<ManagementLockObject> {
const iter = this.listAtSubscriptionLevelPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listAtSubscriptionLevelPagingPage(options);
}
};
}
private async *listAtSubscriptionLevelPagingPage(
options?: ManagementLocksListAtSubscriptionLevelOptionalParams
): AsyncIterableIterator<ManagementLockObject[]> {
let result = await this._listAtSubscriptionLevel(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listAtSubscriptionLevelNext(
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listAtSubscriptionLevelPagingAll(
options?: ManagementLocksListAtSubscriptionLevelOptionalParams
): AsyncIterableIterator<ManagementLockObject> {
for await (const page of this.listAtSubscriptionLevelPagingPage(options)) {
yield* page;
}
}
/**
* Gets all the management locks for a scope.
* @param scope The scope for the lock. When providing a scope for the assignment, use
* '/subscriptions/{subscriptionId}' for subscriptions,
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}'
* for resources.
* @param options The options parameters.
*/
public listByScope(
scope: string,
options?: ManagementLocksListByScopeOptionalParams
): PagedAsyncIterableIterator<ManagementLockObject> {
const iter = this.listByScopePagingAll(scope, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByScopePagingPage(scope, options);
}
};
}
private async *listByScopePagingPage(
scope: string,
options?: ManagementLocksListByScopeOptionalParams
): AsyncIterableIterator<ManagementLockObject[]> {
let result = await this._listByScope(scope, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByScopeNext(scope, continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByScopePagingAll(
scope: string,
options?: ManagementLocksListByScopeOptionalParams
): AsyncIterableIterator<ManagementLockObject> {
for await (const page of this.listByScopePagingPage(scope, options)) {
yield* page;
}
}
/**
* When you apply a lock at a parent scope, all child resources inherit the same lock. To create
* management locks, you must have access to Microsoft.Authorization/* or
* Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access
* Administrator are granted those actions.
* @param resourceGroupName The name of the resource group to lock.
* @param lockName The lock name. The lock name can be a maximum of 260 characters. It cannot contain
* <, > %, &, :, \, ?, /, or any control characters.
* @param parameters The management lock parameters.
* @param options The options parameters.
*/
createOrUpdateAtResourceGroupLevel(
resourceGroupName: string,
lockName: string,
parameters: ManagementLockObject,
options?: ManagementLocksCreateOrUpdateAtResourceGroupLevelOptionalParams
): Promise<ManagementLocksCreateOrUpdateAtResourceGroupLevelResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, lockName, parameters, options },
createOrUpdateAtResourceGroupLevelOperationSpec
);
}
/**
* To delete management locks, you must have access to Microsoft.Authorization/* or
* Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access
* Administrator are granted those actions.
* @param resourceGroupName The name of the resource group containing the lock.
* @param lockName The name of lock to delete.
* @param options The options parameters.
*/
deleteAtResourceGroupLevel(
resourceGroupName: string,
lockName: string,
options?: ManagementLocksDeleteAtResourceGroupLevelOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, lockName, options },
deleteAtResourceGroupLevelOperationSpec
);
}
/**
* Gets a management lock at the resource group level.
* @param resourceGroupName The name of the locked resource group.
* @param lockName The name of the lock to get.
* @param options The options parameters.
*/
getAtResourceGroupLevel(
resourceGroupName: string,
lockName: string,
options?: ManagementLocksGetAtResourceGroupLevelOptionalParams
): Promise<ManagementLocksGetAtResourceGroupLevelResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, lockName, options },
getAtResourceGroupLevelOperationSpec
);
}
/**
* Create or update a management lock by scope.
* @param scope The scope for the lock. When providing a scope for the assignment, use
* '/subscriptions/{subscriptionId}' for subscriptions,
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}'
* for resources.
* @param lockName The name of lock.
* @param parameters Create or update management lock parameters.
* @param options The options parameters.
*/
createOrUpdateByScope(
scope: string,
lockName: string,
parameters: ManagementLockObject,
options?: ManagementLocksCreateOrUpdateByScopeOptionalParams
): Promise<ManagementLocksCreateOrUpdateByScopeResponse> {
return this.client.sendOperationRequest(
{ scope, lockName, parameters, options },
createOrUpdateByScopeOperationSpec
);
}
/**
* Delete a management lock by scope.
* @param scope The scope for the lock.
* @param lockName The name of lock.
* @param options The options parameters.
*/
deleteByScope(
scope: string,
lockName: string,
options?: ManagementLocksDeleteByScopeOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scope, lockName, options },
deleteByScopeOperationSpec
);
}
/**
* Get a management lock by scope.
* @param scope The scope for the lock.
* @param lockName The name of lock.
* @param options The options parameters.
*/
getByScope(
scope: string,
lockName: string,
options?: ManagementLocksGetByScopeOptionalParams
): Promise<ManagementLocksGetByScopeResponse> {
return this.client.sendOperationRequest(
{ scope, lockName, options },
getByScopeOperationSpec
);
}
/**
* When you apply a lock at a parent scope, all child resources inherit the same lock. To create
* management locks, you must have access to Microsoft.Authorization/* or
* Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access
* Administrator are granted those actions.
* @param resourceGroupName The name of the resource group containing the resource to lock.
* @param resourceProviderNamespace The resource provider namespace of the resource to lock.
* @param parentResourcePath The parent resource identity.
* @param resourceType The resource type of the resource to lock.
* @param resourceName The name of the resource to lock.
* @param lockName The name of lock. The lock name can be a maximum of 260 characters. It cannot
* contain <, > %, &, :, \, ?, /, or any control characters.
* @param parameters Parameters for creating or updating a management lock.
* @param options The options parameters.
*/
createOrUpdateAtResourceLevel(
resourceGroupName: string,
resourceProviderNamespace: string,
parentResourcePath: string,
resourceType: string,
resourceName: string,
lockName: string,
parameters: ManagementLockObject,
options?: ManagementLocksCreateOrUpdateAtResourceLevelOptionalParams
): Promise<ManagementLocksCreateOrUpdateAtResourceLevelResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
lockName,
parameters,
options
},
createOrUpdateAtResourceLevelOperationSpec
);
}
/**
* To delete management locks, you must have access to Microsoft.Authorization/* or
* Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access
* Administrator are granted those actions.
* @param resourceGroupName The name of the resource group containing the resource with the lock to
* delete.
* @param resourceProviderNamespace The resource provider namespace of the resource with the lock to
* delete.
* @param parentResourcePath The parent resource identity.
* @param resourceType The resource type of the resource with the lock to delete.
* @param resourceName The name of the resource with the lock to delete.
* @param lockName The name of the lock to delete.
* @param options The options parameters.
*/
deleteAtResourceLevel(
resourceGroupName: string,
resourceProviderNamespace: string,
parentResourcePath: string,
resourceType: string,
resourceName: string,
lockName: string,
options?: ManagementLocksDeleteAtResourceLevelOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
lockName,
options
},
deleteAtResourceLevelOperationSpec
);
}
/**
* Get the management lock of a resource or any level below resource.
* @param resourceGroupName The name of the resource group.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param parentResourcePath An extra path parameter needed in some services, like SQL Databases.
* @param resourceType The type of the resource.
* @param resourceName The name of the resource.
* @param lockName The name of lock.
* @param options The options parameters.
*/
getAtResourceLevel(
resourceGroupName: string,
resourceProviderNamespace: string,
parentResourcePath: string,
resourceType: string,
resourceName: string,
lockName: string,
options?: ManagementLocksGetAtResourceLevelOptionalParams
): Promise<ManagementLocksGetAtResourceLevelResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
lockName,
options
},
getAtResourceLevelOperationSpec
);
}
/**
* When you apply a lock at a parent scope, all child resources inherit the same lock. To create
* management locks, you must have access to Microsoft.Authorization/* or
* Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access
* Administrator are granted those actions.
* @param lockName The name of lock. The lock name can be a maximum of 260 characters. It cannot
* contain <, > %, &, :, \, ?, /, or any control characters.
* @param parameters The management lock parameters.
* @param options The options parameters.
*/
createOrUpdateAtSubscriptionLevel(
lockName: string,
parameters: ManagementLockObject,
options?: ManagementLocksCreateOrUpdateAtSubscriptionLevelOptionalParams
): Promise<ManagementLocksCreateOrUpdateAtSubscriptionLevelResponse> {
return this.client.sendOperationRequest(
{ lockName, parameters, options },
createOrUpdateAtSubscriptionLevelOperationSpec
);
}
/**
* To delete management locks, you must have access to Microsoft.Authorization/* or
* Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access
* Administrator are granted those actions.
* @param lockName The name of lock to delete.
* @param options The options parameters.
*/
deleteAtSubscriptionLevel(
lockName: string,
options?: ManagementLocksDeleteAtSubscriptionLevelOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ lockName, options },
deleteAtSubscriptionLevelOperationSpec
);
}
/**
* Gets a management lock at the subscription level.
* @param lockName The name of the lock to get.
* @param options The options parameters.
*/
getAtSubscriptionLevel(
lockName: string,
options?: ManagementLocksGetAtSubscriptionLevelOptionalParams
): Promise<ManagementLocksGetAtSubscriptionLevelResponse> {
return this.client.sendOperationRequest(
{ lockName, options },
getAtSubscriptionLevelOperationSpec
);
}
/**
* Gets all the management locks for a resource group.
* @param resourceGroupName The name of the resource group containing the locks to get.
* @param options The options parameters.
*/
private _listAtResourceGroupLevel(
resourceGroupName: string,
options?: ManagementLocksListAtResourceGroupLevelOptionalParams
): Promise<ManagementLocksListAtResourceGroupLevelResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listAtResourceGroupLevelOperationSpec
);
}
/**
* Gets all the management locks for a resource or any level below resource.
* @param resourceGroupName The name of the resource group containing the locked resource. The name is
* case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param parentResourcePath The parent resource identity.
* @param resourceType The resource type of the locked resource.
* @param resourceName The name of the locked resource.
* @param options The options parameters.
*/
private _listAtResourceLevel(
resourceGroupName: string,
resourceProviderNamespace: string,
parentResourcePath: string,
resourceType: string,
resourceName: string,
options?: ManagementLocksListAtResourceLevelOptionalParams
): Promise<ManagementLocksListAtResourceLevelResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
options
},
listAtResourceLevelOperationSpec
);
}
/**
* Gets all the management locks for a subscription.
* @param options The options parameters.
*/
private _listAtSubscriptionLevel(
options?: ManagementLocksListAtSubscriptionLevelOptionalParams
): Promise<ManagementLocksListAtSubscriptionLevelResponse> {
return this.client.sendOperationRequest(
{ options },
listAtSubscriptionLevelOperationSpec
);
}
/**
* Gets all the management locks for a scope.
* @param scope The scope for the lock. When providing a scope for the assignment, use
* '/subscriptions/{subscriptionId}' for subscriptions,
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}'
* for resources.
* @param options The options parameters.
*/
private _listByScope(
scope: string,
options?: ManagementLocksListByScopeOptionalParams
): Promise<ManagementLocksListByScopeResponse> {
return this.client.sendOperationRequest(
{ scope, options },
listByScopeOperationSpec
);
}
/**
* ListAtResourceGroupLevelNext
* @param resourceGroupName The name of the resource group containing the locks to get.
* @param nextLink The nextLink from the previous successful call to the ListAtResourceGroupLevel
* method.
* @param options The options parameters.
*/
private _listAtResourceGroupLevelNext(
resourceGroupName: string,
nextLink: string,
options?: ManagementLocksListAtResourceGroupLevelNextOptionalParams
): Promise<ManagementLocksListAtResourceGroupLevelNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listAtResourceGroupLevelNextOperationSpec
);
}
/**
* ListAtResourceLevelNext
* @param resourceGroupName The name of the resource group containing the locked resource. The name is
* case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param parentResourcePath The parent resource identity.
* @param resourceType The resource type of the locked resource.
* @param resourceName The name of the locked resource.
* @param nextLink The nextLink from the previous successful call to the ListAtResourceLevel method.
* @param options The options parameters.
*/
private _listAtResourceLevelNext(
resourceGroupName: string,
resourceProviderNamespace: string,
parentResourcePath: string,
resourceType: string,
resourceName: string,
nextLink: string,
options?: ManagementLocksListAtResourceLevelNextOptionalParams
): Promise<ManagementLocksListAtResourceLevelNextResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
nextLink,
options
},
listAtResourceLevelNextOperationSpec
);
}
/**
* ListAtSubscriptionLevelNext
* @param nextLink The nextLink from the previous successful call to the ListAtSubscriptionLevel
* method.
* @param options The options parameters.
*/
private _listAtSubscriptionLevelNext(
nextLink: string,
options?: ManagementLocksListAtSubscriptionLevelNextOptionalParams
): Promise<ManagementLocksListAtSubscriptionLevelNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listAtSubscriptionLevelNextOperationSpec
);
}
/**
* ListByScopeNext
* @param scope The scope for the lock. When providing a scope for the assignment, use
* '/subscriptions/{subscriptionId}' for subscriptions,
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}'
* for resources.
* @param nextLink The nextLink from the previous successful call to the ListByScope method.
* @param options The options parameters.
*/
private _listByScopeNext(
scope: string,
nextLink: string,
options?: ManagementLocksListByScopeNextOptionalParams
): Promise<ManagementLocksListByScopeNextResponse> {
return this.client.sendOperationRequest(
{ scope, nextLink, options },
listByScopeNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createOrUpdateAtResourceGroupLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.ManagementLockObject
},
201: {
bodyMapper: Mappers.ManagementLockObject
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.lockName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteAtResourceGroupLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "DELETE",
responses: { 200: {}, 204: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.lockName,
Parameters.subscriptionId
],
serializer
};
const getAtResourceGroupLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockObject
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.lockName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateByScopeOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.ManagementLockObject
},
201: {
bodyMapper: Mappers.ManagementLockObject
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.lockName, Parameters.scope],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteByScopeOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "DELETE",
responses: { 200: {}, 204: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.lockName, Parameters.scope],
serializer
};
const getByScopeOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockObject
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.lockName, Parameters.scope],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateAtResourceLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.ManagementLockObject
},
201: {
bodyMapper: Mappers.ManagementLockObject
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.lockName,
Parameters.subscriptionId,
Parameters.resourceProviderNamespace,
Parameters.parentResourcePath,
Parameters.resourceType,
Parameters.resourceName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteAtResourceLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "DELETE",
responses: { 200: {}, 204: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.lockName,
Parameters.subscriptionId,
Parameters.resourceProviderNamespace,
Parameters.parentResourcePath,
Parameters.resourceType,
Parameters.resourceName
],
serializer
};
const getAtResourceLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockObject
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.lockName,
Parameters.subscriptionId,
Parameters.resourceProviderNamespace,
Parameters.parentResourcePath,
Parameters.resourceType,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateAtSubscriptionLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.ManagementLockObject
},
201: {
bodyMapper: Mappers.ManagementLockObject
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.lockName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteAtSubscriptionLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "DELETE",
responses: { 200: {}, 204: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.lockName,
Parameters.subscriptionId
],
serializer
};
const getAtSubscriptionLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockObject
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.lockName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listAtResourceGroupLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listAtResourceLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.resourceProviderNamespace,
Parameters.parentResourcePath,
Parameters.resourceType,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const listAtSubscriptionLevelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByScopeOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Authorization/locks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [Parameters.$host, Parameters.scope],
headerParameters: [Parameters.accept],
serializer
};
const listAtResourceGroupLevelNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listAtResourceLevelNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.resourceProviderNamespace,
Parameters.parentResourcePath,
Parameters.resourceType,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const listAtSubscriptionLevelNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByScopeNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ManagementLockListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [Parameters.$host, Parameters.nextLink, Parameters.scope],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { EventEmitter } from 'events';
import {
DeclarativePaymentDetector,
EscrowERC20InfoRetriever,
} from '@requestnetwork/payment-detection';
import { IdentityTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types';
import { ICurrencyManager } from '@requestnetwork/currency';
import Utils from '@requestnetwork/utils';
import * as Types from '../types';
import ContentDataExtension from './content-data-extension';
import localUtils from './utils';
import { erc20EscrowToPayArtifact } from '@requestnetwork/smart-contracts';
/**
* Class representing a request.
* Instances of this class can be accepted, paid, refunded, etc.
* Use the member function `getData` to access the properties of the Request.
*
* Requests should be created with `RequestNetwork.createRequest()`.
*/
export default class Request {
/**
* Unique ID of the request
*/
public readonly requestId: RequestLogicTypes.RequestId;
private requestLogic: RequestLogicTypes.IRequestLogic;
private paymentNetwork: PaymentTypes.IPaymentNetwork | null = null;
private contentDataExtension: ContentDataExtension | null;
private emitter: EventEmitter;
/**
* true if the creation emitted an event 'error'
*/
private confirmationErrorOccurredAtCreation = false;
/**
* Data of the request (see request-logic)
*/
private requestData: RequestLogicTypes.IRequest | null = null;
/**
* Pending data of the request (see request-logic)
*/
private pendingData: RequestLogicTypes.IPendingRequest | null = null;
/**
* Content data parsed from the extensions data
*/
private contentData: any | null = null;
/**
* Meta data of the request (e.g: where the data have been retrieved from)
*/
private requestMeta: RequestLogicTypes.IReturnMeta | null = null;
/**
* Balance and payments/refund events
*/
private balance: PaymentTypes.IBalanceWithEvents | null = null;
/**
* if true, skip the payment detection
*/
private skipPaymentDetection = false;
/**
* if true, do not send blockchain confirmation events (on creation, approval, etc.)
*/
private disableEvents = false;
/**
* A list of known tokens
*/
private currencyManager: ICurrencyManager;
/**
* Creates an instance of Request
*
* @param requestLogic Instance of the request-logic layer
* @param requestId ID of the Request
* @param paymentNetwork Instance of a payment network to manage the request
* @param contentDataManager Instance of content data manager
* @param requestLogicCreateResult return from the first request creation (optimization)
* @param options options
*/
constructor(
requestId: RequestLogicTypes.RequestId,
requestLogic: RequestLogicTypes.IRequestLogic,
currencyManager: ICurrencyManager,
options?: {
paymentNetwork?: PaymentTypes.IPaymentNetwork | null;
contentDataExtension?: ContentDataExtension | null;
requestLogicCreateResult?: RequestLogicTypes.IReturnCreateRequest;
skipPaymentDetection?: boolean;
disableEvents?: boolean;
},
) {
this.requestLogic = requestLogic;
this.requestId = requestId;
this.contentDataExtension = options?.contentDataExtension || null;
this.paymentNetwork = options?.paymentNetwork || null;
this.emitter = new EventEmitter();
this.skipPaymentDetection = options?.skipPaymentDetection || false;
this.disableEvents = options?.disableEvents || false;
this.currencyManager = currencyManager;
if (options && options.requestLogicCreateResult && !this.disableEvents) {
const originalEmitter = options.requestLogicCreateResult;
originalEmitter
.on('confirmed', async () => {
try {
this.emitter.emit('confirmed', await this.refresh());
} catch (error) {
originalEmitter.emit('error', error);
}
})
.on('error', (error) => {
this.confirmationErrorOccurredAtCreation = true;
this.emitter.emit('error', error);
});
}
}
/**
* Listen the confirmation of the creation
*
* @param type only "confirmed" event for now
* @param callback callback to call when confirmed event is risen
* @returns this
*/
public on<K extends keyof Types.IRequestEvents>(
event: K,
listener: Types.IRequestEvents[K],
): this {
this.emitter.on(event, listener);
return this;
}
/**
* Wait for the confirmation
*
* @returns the request data
*/
public waitForConfirmation(): Promise<Types.IRequestDataWithEvents> {
return new Promise((resolve, reject): any => {
this.on('confirmed', resolve);
this.on('error', reject);
});
}
/**
* Accepts a request
*
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @param refundInformation Refund information to add (any because it is specific to the payment network used by the request)
* @returns The updated request
*/
public async accept(
signerIdentity: IdentityTypes.IIdentity,
refundInformation?: any,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (refundInformation) {
if (!this.paymentNetwork) {
throw new Error('Cannot add refund information without payment network');
}
extensionsData.push(
this.paymentNetwork.createExtensionsDataForAddRefundInformation(refundInformation),
);
}
const parameters: RequestLogicTypes.IAcceptParameters = {
extensionsData,
requestId: this.requestId,
};
const acceptResult = await this.requestLogic.acceptRequest(parameters, signerIdentity, true);
return this.handleRequestDataEvents(acceptResult);
}
/**
* Cancels a request
*
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @param refundInformation refund information to add (any because it is specific to the payment network used by the request)
* @returns The updated request
*/
public async cancel(
signerIdentity: IdentityTypes.IIdentity,
refundInformation?: any,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (refundInformation) {
if (!this.paymentNetwork) {
throw new Error('Cannot add refund information without payment network');
}
extensionsData.push(
this.paymentNetwork.createExtensionsDataForAddRefundInformation(refundInformation),
);
}
const parameters: RequestLogicTypes.ICancelParameters = {
extensionsData,
requestId: this.requestId,
};
const cancelResult = await this.requestLogic.cancelRequest(parameters, signerIdentity, true);
return this.handleRequestDataEvents(cancelResult);
}
/**
* Increases the expected amount of the request.
*
* @param deltaAmount Amount by which to increase the expected amount
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @param refundInformation Refund information to add (any because it is specific to the payment network used by the request)
* @returns The updated request
*/
public async increaseExpectedAmountRequest(
deltaAmount: RequestLogicTypes.Amount,
signerIdentity: IdentityTypes.IIdentity,
refundInformation?: any,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (refundInformation) {
if (!this.paymentNetwork) {
throw new Error('Cannot add refund information without payment network');
}
extensionsData.push(
this.paymentNetwork.createExtensionsDataForAddRefundInformation(refundInformation),
);
}
const parameters: RequestLogicTypes.IIncreaseExpectedAmountParameters = {
deltaAmount,
extensionsData,
requestId: this.requestId,
};
const increaseExpectedResult = await this.requestLogic.increaseExpectedAmountRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(increaseExpectedResult);
}
/**
* Reduces the expected amount of the request. This can be called by the payee e.g. to apply discounts or special offers.
*
* @param deltaAmount Amount by which to reduce the expected amount
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @param paymentInformation Payment information to add (any because it is specific to the payment network used by the request)
* @returns The updated request
*/
public async reduceExpectedAmountRequest(
deltaAmount: RequestLogicTypes.Amount,
signerIdentity: IdentityTypes.IIdentity,
paymentInformation?: any,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (paymentInformation) {
if (!this.paymentNetwork) {
throw new Error('Cannot add payment information without payment network');
}
extensionsData.push(
this.paymentNetwork.createExtensionsDataForAddPaymentInformation(paymentInformation),
);
}
const parameters: RequestLogicTypes.IReduceExpectedAmountParameters = {
deltaAmount,
extensionsData,
requestId: this.requestId,
};
const reduceExpectedResult = await this.requestLogic.reduceExpectedAmountRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(reduceExpectedResult);
}
/**
* Adds payment information
*
* @param paymentInformation Payment information to add (any because it is specific to the payment network used by the request)
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @returns The updated request
*/
public async addPaymentInformation(
paymentInformation: any,
signerIdentity: IdentityTypes.IIdentity,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (!this.paymentNetwork) {
throw new Error('Cannot add payment information without payment network');
}
extensionsData.push(
this.paymentNetwork.createExtensionsDataForAddPaymentInformation(paymentInformation),
);
const parameters: RequestLogicTypes.IAddExtensionsDataParameters = {
extensionsData,
requestId: this.requestId,
};
const addExtensionResult = await this.requestLogic.addExtensionsDataRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(addExtensionResult);
}
/**
* Adds refund information
*
* @param refundInformation Refund information to add (any because it is specific to the payment network used by the request)
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @returns The updated request
*/
public async addRefundInformation(
refundInformation: any,
signerIdentity: IdentityTypes.IIdentity,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (!this.paymentNetwork) {
throw new Error('Cannot add refund information without payment network');
}
extensionsData.push(
this.paymentNetwork.createExtensionsDataForAddRefundInformation(refundInformation),
);
const parameters: RequestLogicTypes.IAddExtensionsDataParameters = {
extensionsData,
requestId: this.requestId,
};
const addExtensionResult = await this.requestLogic.addExtensionsDataRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(addExtensionResult);
}
/**
* Declare a payment is sent for the declarative payment network
*
* @param amount Amount sent
* @param note Note from payer about the sent payment
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @returns The updated request
*/
public async declareSentPayment(
amount: RequestLogicTypes.Amount,
note: string,
signerIdentity: IdentityTypes.IIdentity,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (!this.paymentNetwork) {
throw new Error('Cannot declare sent payment without payment network');
}
// We need to cast the object since IPaymentNetwork doesn't implement createExtensionsDataForDeclareSentPayment
const declarativePaymentNetwork = this.paymentNetwork as DeclarativePaymentDetector;
if (!declarativePaymentNetwork.createExtensionsDataForDeclareSentPayment) {
throw new Error('Cannot declare sent payment without declarative payment network');
}
extensionsData.push(
declarativePaymentNetwork.createExtensionsDataForDeclareSentPayment({ amount, note }),
);
const parameters: RequestLogicTypes.IAddExtensionsDataParameters = {
extensionsData,
requestId: this.requestId,
};
const addExtensionResult = await this.requestLogic.addExtensionsDataRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(addExtensionResult);
}
/**
* Declare a refund is sent for the declarative payment network
*
* @param amount Amount sent
* @param note Note from payee about the sent refund
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @returns The updated request
*/
public async declareSentRefund(
amount: RequestLogicTypes.Amount,
note: string,
signerIdentity: IdentityTypes.IIdentity,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (!this.paymentNetwork) {
throw new Error('Cannot declare sent refund without payment network');
}
// We need to cast the object since IPaymentNetwork doesn't implement createExtensionsDataForDeclareSentRefund
const declarativePaymentNetwork = this.paymentNetwork as DeclarativePaymentDetector;
if (!declarativePaymentNetwork.createExtensionsDataForDeclareSentRefund) {
throw new Error('Cannot declare sent refund without declarative payment network');
}
extensionsData.push(
declarativePaymentNetwork.createExtensionsDataForDeclareSentRefund({
amount,
note,
}),
);
const parameters: RequestLogicTypes.IAddExtensionsDataParameters = {
extensionsData,
requestId: this.requestId,
};
const addExtensionResult = await this.requestLogic.addExtensionsDataRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(addExtensionResult);
}
/**
* Declare a payment is received for the declarative payment network
*
* @param amount Amount received
* @param note Note from payee about the received payment
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @param txHash transaction hash
* @param network network of the transaction
* @returns The updated request
*/
public async declareReceivedPayment(
amount: RequestLogicTypes.Amount,
note: string,
signerIdentity: IdentityTypes.IIdentity,
txHash?: string,
network?: string,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (!this.paymentNetwork) {
throw new Error('Cannot declare received payment without payment network');
}
// We need to cast the object since IPaymentNetwork doesn't implement createExtensionsDataForDeclareReceivedPayment
const declarativePaymentNetwork = this.paymentNetwork as DeclarativePaymentDetector;
if (!declarativePaymentNetwork.createExtensionsDataForDeclareReceivedPayment) {
throw new Error('Cannot declare received payment without declarative payment network');
}
extensionsData.push(
declarativePaymentNetwork.createExtensionsDataForDeclareReceivedPayment({
amount,
note,
txHash,
network,
}),
);
const parameters: RequestLogicTypes.IAddExtensionsDataParameters = {
extensionsData,
requestId: this.requestId,
};
const addExtensionResult = await this.requestLogic.addExtensionsDataRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(addExtensionResult);
}
/**
* Declare a refund is received for the declarative payment network
*
* @param amount Amount received
* @param note Note from payer about the received refund
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @param txHash transaction hash
* @param network network of the transaction
* @returns The updated request
*/
public async declareReceivedRefund(
amount: RequestLogicTypes.Amount,
note: string,
signerIdentity: IdentityTypes.IIdentity,
txHash?: string,
network?: string,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: any[] = [];
if (!this.paymentNetwork) {
throw new Error('Cannot declare received refund without payment network');
}
// We need to cast the object since IPaymentNetwork doesn't implement createExtensionsDataForDeclareReceivedRefund
const declarativePaymentNetwork = this.paymentNetwork as DeclarativePaymentDetector;
if (!declarativePaymentNetwork.createExtensionsDataForDeclareReceivedRefund) {
throw new Error('Cannot declare received refund without declarative payment network');
}
extensionsData.push(
declarativePaymentNetwork.createExtensionsDataForDeclareReceivedRefund({
amount,
note,
txHash,
network,
}),
);
const parameters: RequestLogicTypes.IAddExtensionsDataParameters = {
extensionsData,
requestId: this.requestId,
};
const addExtensionResult = await this.requestLogic.addExtensionsDataRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(addExtensionResult);
}
/**
* Add a delegate for the declarative payment network
*
* @param delegate Identity of the delegate
* @param signerIdentity Identity of the signer. The identity type must be supported by the signature provider.
* @returns The updated request
*/
public async addDeclarativeDelegate(
delegate: IdentityTypes.IIdentity,
signerIdentity: IdentityTypes.IIdentity,
): Promise<Types.IRequestDataWithEvents> {
const extensionsData: Types.Extension.IAction[] = [];
if (!this.paymentNetwork) {
throw new Error('Cannot declare delegate without payment network');
}
// We need to cast the object since IPaymentNetwork doesn't implement createExtensionsDataForDeclareReceivedRefund
const declarativePaymentNetwork = this.paymentNetwork as DeclarativePaymentDetector;
if (!declarativePaymentNetwork.createExtensionsDataForAddDelegate) {
throw new Error('Cannot declare delegate without declarative payment network');
}
extensionsData.push(
declarativePaymentNetwork.createExtensionsDataForAddDelegate({
delegate,
}),
);
const parameters: RequestLogicTypes.IAddExtensionsDataParameters = {
extensionsData,
requestId: this.requestId,
};
const addExtensionResult = await this.requestLogic.addExtensionsDataRequest(
parameters,
signerIdentity,
true,
);
return this.handleRequestDataEvents(addExtensionResult);
}
protected handleRequestDataEvents(
eventEmitter: EventEmitter,
): Promise<Types.IRequestDataWithEvents> {
// refresh the local request data
const requestDataPromise = this.refresh();
if (!this.disableEvents) {
eventEmitter
.on('confirmed', async () => {
try {
const requestData = await requestDataPromise;
requestData.emit('confirmed', await this.refresh());
} catch (error) {
eventEmitter.emit('error', error);
}
})
.on('error', (error) => {
this.emitter.emit('error', error);
});
}
return requestDataPromise;
}
/**
* Gets the request data
*
* @returns The updated request data
*/
public getData(): Types.IRequestDataWithEvents {
if (this.confirmationErrorOccurredAtCreation) {
throw Error('request confirmation failed');
}
let requestData = Utils.deepCopy(this.requestData);
let pending = Utils.deepCopy(this.pendingData);
if (!requestData) {
requestData = pending as RequestLogicTypes.IRequest;
requestData.state = RequestLogicTypes.STATE.PENDING;
pending = { state: this.pendingData!.state };
}
const currency = this.currencyManager.fromStorageCurrency(requestData.currency);
return Object.assign(new EventEmitter(), {
...requestData,
balance: this.balance,
contentData: this.contentData,
currency: currency ? currency.id : 'unknown',
currencyInfo: requestData.currency,
meta: this.requestMeta,
pending,
});
}
public async getEscrowData(
paymentReference: string,
network: string,
): Promise<PaymentTypes.EscrowChainData> {
const escrowContractAddress = erc20EscrowToPayArtifact.getAddress(network);
const escrowInfoRetriever = new EscrowERC20InfoRetriever(
paymentReference,
escrowContractAddress,
0,
'',
'',
network,
);
return await escrowInfoRetriever.getEscrowRequestMapping();
}
/**
* Refresh the request data and balance from the network (check if new events happened - e.g: accept, payments etc..) and return these data
*
* @param requestAndMeta return from getRequestFromId to avoid asking twice
* @returns Refreshed request data
*/
public async refresh(
requestAndMeta?: RequestLogicTypes.IReturnGetRequestFromId,
): Promise<Types.IRequestDataWithEvents> {
if (this.confirmationErrorOccurredAtCreation) {
throw Error('request confirmation failed');
}
if (!requestAndMeta) {
requestAndMeta = await this.requestLogic.getRequestFromId(this.requestId);
}
if (!requestAndMeta.result.request && !requestAndMeta.result.pending) {
throw new Error(
`No request found for the id: ${this.requestId} - ${localUtils.formatGetRequestFromIdError(
requestAndMeta,
)}`,
);
}
if (this.contentDataExtension) {
// TODO: PROT-1131 - add a pending content
this.contentData = await this.contentDataExtension.getContent(
requestAndMeta.result.request || requestAndMeta.result.pending,
);
}
this.requestData = requestAndMeta.result.request;
this.pendingData = requestAndMeta.result.pending;
this.requestMeta = requestAndMeta.meta;
if (!this.skipPaymentDetection) {
// let's refresh the balance
await this.refreshBalance();
}
return this.getData();
}
/**
* Refresh only the balance of the request and return it
*
* @returns return the balance
*/
public async refreshBalance(): Promise<Types.Payment.IBalanceWithEvents<any> | null> {
// TODO: PROT-1131 - add a pending balance
if (this.paymentNetwork && this.requestData) {
this.balance = await this.paymentNetwork.getBalance(this.requestData);
}
return this.balance;
}
/**
* Enables the payment detection
*/
public enablePaymentDetection(): void {
this.skipPaymentDetection = false;
}
/**
* Disables the payment detection
*/
public disablePaymentDetection(): void {
this.skipPaymentDetection = true;
}
} | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import * as models from '../model/models';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable()
export class DefaultApi {
protected basePath = 'https://cpoxt4iiyh.execute-api.us-east-1.amazonaws.com/development';
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
}
}
/**
*
* @param userId
* @param booking
*/
public bookingsCreate(userId: string, booking: models.Booking, extraHttpRequestParams?: any): Observable<models.Booking> {
return this.bookingsCreateWithHttpInfo(userId, booking, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param userId
* @param bookingId
*/
public bookingsDelete(userId: string, bookingId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.bookingsDeleteWithHttpInfo(userId, bookingId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param userId
* @param bookingId
*/
public bookingsGet(userId: string, bookingId: string, extraHttpRequestParams?: any): Observable<models.Booking> {
return this.bookingsGetWithHttpInfo(userId, bookingId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
* @param resourceId
*/
public bookingsListByResourceId(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<models.BookingsListResponse> {
return this.bookingsListByResourceIdWithHttpInfo(locationId, resourceId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param userId
*/
public bookingsListByUserId(userId: string, extraHttpRequestParams?: any): Observable<models.BookingsListResponse> {
return this.bookingsListByUserIdWithHttpInfo(userId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param location
*/
public locationsCreate(location: models.Location, extraHttpRequestParams?: any): Observable<models.Location> {
return this.locationsCreateWithHttpInfo(location, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
*/
public locationsDelete(locationId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.locationsDeleteWithHttpInfo(locationId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
*/
public locationsGet(locationId: string, extraHttpRequestParams?: any): Observable<models.Location> {
return this.locationsGetWithHttpInfo(locationId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
*/
public locationsList(extraHttpRequestParams?: any): Observable<models.LocationsListResponse> {
return this.locationsListWithHttpInfo(extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
*/
public locationsLocationIdOptions(locationId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.locationsLocationIdOptionsWithHttpInfo(locationId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
*/
public locationsLocationIdResourcesOptions(locationId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.locationsLocationIdResourcesOptionsWithHttpInfo(locationId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
* @param resourceId
*/
public locationsLocationIdResourcesResourceIdBookingsOptions(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.locationsLocationIdResourcesResourceIdBookingsOptionsWithHttpInfo(locationId, resourceId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
* @param resourceId
*/
public locationsLocationIdResourcesResourceIdOptions(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.locationsLocationIdResourcesResourceIdOptionsWithHttpInfo(locationId, resourceId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
*/
public locationsOptions(extraHttpRequestParams?: any): Observable<{}> {
return this.locationsOptionsWithHttpInfo(extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
* @param resource
*/
public resourcesCreate(locationId: string, resource: models.Resource, extraHttpRequestParams?: any): Observable<models.Resource> {
return this.resourcesCreateWithHttpInfo(locationId, resource, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
* @param resourceId
*/
public resourcesDelete(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.resourcesDeleteWithHttpInfo(locationId, resourceId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
* @param resourceId
*/
public resourcesGet(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<models.Resource> {
return this.resourcesGetWithHttpInfo(locationId, resourceId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param locationId
*/
public resourcesList(locationId: string, extraHttpRequestParams?: any): Observable<models.ResourcesListResponse> {
return this.resourcesListWithHttpInfo(locationId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param userId
* @param bookingId
*/
public usersUserIdBookingsBookingIdOptions(userId: string, bookingId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.usersUserIdBookingsBookingIdOptionsWithHttpInfo(userId, bookingId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param userId
*/
public usersUserIdBookingsOptions(userId: string, extraHttpRequestParams?: any): Observable<{}> {
return this.usersUserIdBookingsOptionsWithHttpInfo(userId, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
*
* @param userId
* @param booking
*/
public bookingsCreateWithHttpInfo(userId: string, booking: models.Booking, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/users/${userId}/bookings'
.replace('${' + 'userId' + '}', String(userId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'userId' is not null or undefined
if (userId === null || userId === undefined) {
throw new Error('Required parameter userId was null or undefined when calling bookingsCreate.');
}
// verify required parameter 'booking' is not null or undefined
if (booking === null || booking === undefined) {
throw new Error('Required parameter booking was null or undefined when calling bookingsCreate.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: booking == null ? '' : JSON.stringify(booking), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param userId
* @param bookingId
*/
public bookingsDeleteWithHttpInfo(userId: string, bookingId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/users/${userId}/bookings/${bookingId}'
.replace('${' + 'userId' + '}', String(userId))
.replace('${' + 'bookingId' + '}', String(bookingId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'userId' is not null or undefined
if (userId === null || userId === undefined) {
throw new Error('Required parameter userId was null or undefined when calling bookingsDelete.');
}
// verify required parameter 'bookingId' is not null or undefined
if (bookingId === null || bookingId === undefined) {
throw new Error('Required parameter bookingId was null or undefined when calling bookingsDelete.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param userId
* @param bookingId
*/
public bookingsGetWithHttpInfo(userId: string, bookingId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/users/${userId}/bookings/${bookingId}'
.replace('${' + 'userId' + '}', String(userId))
.replace('${' + 'bookingId' + '}', String(bookingId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'userId' is not null or undefined
if (userId === null || userId === undefined) {
throw new Error('Required parameter userId was null or undefined when calling bookingsGet.');
}
// verify required parameter 'bookingId' is not null or undefined
if (bookingId === null || bookingId === undefined) {
throw new Error('Required parameter bookingId was null or undefined when calling bookingsGet.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
* @param resourceId
*/
public bookingsListByResourceIdWithHttpInfo(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}/resources/${resourceId}/bookings'
.replace('${' + 'locationId' + '}', String(locationId))
.replace('${' + 'resourceId' + '}', String(resourceId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling bookingsListByResourceId.');
}
// verify required parameter 'resourceId' is not null or undefined
if (resourceId === null || resourceId === undefined) {
throw new Error('Required parameter resourceId was null or undefined when calling bookingsListByResourceId.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param userId
*/
public bookingsListByUserIdWithHttpInfo(userId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/users/${userId}/bookings'
.replace('${' + 'userId' + '}', String(userId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'userId' is not null or undefined
if (userId === null || userId === undefined) {
throw new Error('Required parameter userId was null or undefined when calling bookingsListByUserId.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param location
*/
public locationsCreateWithHttpInfo(location: models.Location, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'location' is not null or undefined
if (location === null || location === undefined) {
throw new Error('Required parameter location was null or undefined when calling locationsCreate.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: location == null ? '' : JSON.stringify(location), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
*/
public locationsDeleteWithHttpInfo(locationId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}'
.replace('${' + 'locationId' + '}', String(locationId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling locationsDelete.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
// authentication (spacefinder-custom-authorizer) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
*/
public locationsGetWithHttpInfo(locationId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}'
.replace('${' + 'locationId' + '}', String(locationId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling locationsGet.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
*/
public locationsListWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (spacefinder-userPool-authorizer) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
*/
public locationsLocationIdOptionsWithHttpInfo(locationId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}'
.replace('${' + 'locationId' + '}', String(locationId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling locationsLocationIdOptions.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Options,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
*/
public locationsLocationIdResourcesOptionsWithHttpInfo(locationId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}/resources'
.replace('${' + 'locationId' + '}', String(locationId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling locationsLocationIdResourcesOptions.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Options,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
* @param resourceId
*/
public locationsLocationIdResourcesResourceIdBookingsOptionsWithHttpInfo(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}/resources/${resourceId}/bookings'
.replace('${' + 'locationId' + '}', String(locationId))
.replace('${' + 'resourceId' + '}', String(resourceId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling locationsLocationIdResourcesResourceIdBookingsOptions.');
}
// verify required parameter 'resourceId' is not null or undefined
if (resourceId === null || resourceId === undefined) {
throw new Error('Required parameter resourceId was null or undefined when calling locationsLocationIdResourcesResourceIdBookingsOptions.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Options,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
* @param resourceId
*/
public locationsLocationIdResourcesResourceIdOptionsWithHttpInfo(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}/resources/${resourceId}'
.replace('${' + 'locationId' + '}', String(locationId))
.replace('${' + 'resourceId' + '}', String(resourceId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling locationsLocationIdResourcesResourceIdOptions.');
}
// verify required parameter 'resourceId' is not null or undefined
if (resourceId === null || resourceId === undefined) {
throw new Error('Required parameter resourceId was null or undefined when calling locationsLocationIdResourcesResourceIdOptions.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Options,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
*/
public locationsOptionsWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Options,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
* @param resource
*/
public resourcesCreateWithHttpInfo(locationId: string, resource: models.Resource, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}/resources'
.replace('${' + 'locationId' + '}', String(locationId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling resourcesCreate.');
}
// verify required parameter 'resource' is not null or undefined
if (resource === null || resource === undefined) {
throw new Error('Required parameter resource was null or undefined when calling resourcesCreate.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (spacefinder-custom-authorizer) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: resource == null ? '' : JSON.stringify(resource), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
* @param resourceId
*/
public resourcesDeleteWithHttpInfo(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}/resources/${resourceId}'
.replace('${' + 'locationId' + '}', String(locationId))
.replace('${' + 'resourceId' + '}', String(resourceId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling resourcesDelete.');
}
// verify required parameter 'resourceId' is not null or undefined
if (resourceId === null || resourceId === undefined) {
throw new Error('Required parameter resourceId was null or undefined when calling resourcesDelete.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
];
// authentication (spacefinder-custom-authorizer) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
* @param resourceId
*/
public resourcesGetWithHttpInfo(locationId: string, resourceId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}/resources/${resourceId}'
.replace('${' + 'locationId' + '}', String(locationId))
.replace('${' + 'resourceId' + '}', String(resourceId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling resourcesGet.');
}
// verify required parameter 'resourceId' is not null or undefined
if (resourceId === null || resourceId === undefined) {
throw new Error('Required parameter resourceId was null or undefined when calling resourcesGet.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param locationId
*/
public resourcesListWithHttpInfo(locationId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/locations/${locationId}/resources'
.replace('${' + 'locationId' + '}', String(locationId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'locationId' is not null or undefined
if (locationId === null || locationId === undefined) {
throw new Error('Required parameter locationId was null or undefined when calling resourcesList.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
// authentication (sigv4) required
if (this.configuration.apiKey) {
headers.set('Authorization', this.configuration.apiKey);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param userId
* @param bookingId
*/
public usersUserIdBookingsBookingIdOptionsWithHttpInfo(userId: string, bookingId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/users/${userId}/bookings/${bookingId}'
.replace('${' + 'userId' + '}', String(userId))
.replace('${' + 'bookingId' + '}', String(bookingId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'userId' is not null or undefined
if (userId === null || userId === undefined) {
throw new Error('Required parameter userId was null or undefined when calling usersUserIdBookingsBookingIdOptions.');
}
// verify required parameter 'bookingId' is not null or undefined
if (bookingId === null || bookingId === undefined) {
throw new Error('Required parameter bookingId was null or undefined when calling usersUserIdBookingsBookingIdOptions.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Options,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param userId
*/
public usersUserIdBookingsOptionsWithHttpInfo(userId: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/users/${userId}/bookings'
.replace('${' + 'userId' + '}', String(userId));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'userId' is not null or undefined
if (userId === null || userId === undefined) {
throw new Error('Required parameter userId was null or undefined when calling usersUserIdBookingsOptions.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Options,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
} | the_stack |
import * as React from "react";
import * as ReactDOM from "react-dom";
import { observer } from "mobx-react";
import * as accounting from "accounting";
import SelectCustomer from "../Shared/Components/SelectCustomer";
import SelectPaymentTerm from "../Shared/Components/SelectPaymentTerm";
import SelectLineItem from "../Shared/Components/SelectLineItem";
import SelectLineMeasurement from "../Shared/Components/SelectLineMeasurement";
import SalesOrderStore from "../Shared/Stores/Sales/SalesOrderStore";
let quotationId = window.location.search.split("?quotationId=")[1];
let orderId = window.location.search.split("?orderId=")[1];
let store = new SalesOrderStore(quotationId, orderId);
let baseUrl = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
@observer
class ValidationErrors extends React.Component<any, {}> {
render() {
if (store.validationErrors !== undefined && store.validationErrors.length > 0) {
var errors = [];
store.validationErrors.map(function(item, index) {
errors.push(<li key={index}>{item}</li>);
});
return (
<div>
<ul>{errors}</ul>
</div>
);
}
return null;
}
}
class SaveOrderButton extends React.Component<any, {}> {
saveNewSalesOrder(e) {
store.saveNewSalesOrder();
}
render() {
return (
<input
type="button"
className="btn btn-sm btn-primary btn-flat pull-left"
value="Save"
onClick={this.saveNewSalesOrder.bind(this)}
/>
);
}
}
class CancelOrderButton extends React.Component<any, {}> {
cancelOnClick() {
let baseUrl = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
window.location.href = baseUrl + "sales/salesorders";
}
render() {
return (
<button
type="button"
color="danger"
className="btn btn-sm btn-default btn-flat pull-left"
onClick={this.cancelOnClick.bind(this)}
>
Close
</button>
);
}
}
@observer
class SalesOrderHeader extends React.Component<any, {}> {
onChangeOrderDate(e) {
store.changedOrderDate(e.target.value);
}
onChangeReferenceNo(e) {
store.changedReferenceNo(e.target.value);
}
render() {
return (
<div class="card">
<div class="card-header">
<a data-toggle="collapse" href="#customer-info" aria-expanded="true" aria-controls="customer-info"><i class="fa fa-align-justify"></i></a> Customer Information
</div>
<div class="card-body collapse show row" id="customer-info">
<div className="col-md-6">
<div className="row">
<div className="col-sm-2">Customer</div>
<div className="col-sm-10"><SelectCustomer store={store} selected={store.salesOrder.customerId} /></div>
</div>
<div className="row">
<div className="col-sm-2">Payment Term</div>
<div className="col-sm-10"><SelectPaymentTerm store={store} selected={store.salesOrder.paymentTermId} /></div>
</div>
</div>
<div className="col-md-6">
<div className="row">
<div className="col-sm-2">Date</div>
<div className="col-sm-10"><input type="date" className="form-control pull-right" onChange={this.onChangeOrderDate.bind(this)}
value={store.salesOrder.orderDate !== undefined ? store.salesOrder.orderDate.substring(0, 10) : new Date(Date.now()).toISOString().substring(0, 10)} /></div>
</div>
<div className="row">
<div className="col-sm-2">Reference no.</div>
<div className="col-sm-10"><input type="text" className="form-control" value={store.salesOrder.referenceNo || ''} onChange={this.onChangeReferenceNo.bind(this)} /></div>
</div>
<div className="row">
<div className="col-sm-2">Status</div>
<div className="col-sm-10"><label>{store.salesOrderStatus}</label></div>
</div>
</div>
</div>
</div>
);
}
}
@observer
class SalesOrderLines extends React.Component<any, {}> {
addLineItem() {
if (store.validationLine()) {
var itemId, measurementId, quantity, amount, discount, code;
itemId = (document.getElementById("optNewItemId") as HTMLInputElement).value;
measurementId = (document.getElementById("optNewMeasurementId") as HTMLInputElement).value;
quantity = (document.getElementById("txtNewQuantity") as HTMLInputElement).value;
amount = (document.getElementById("txtNewAmount") as HTMLInputElement).value;
discount = (document.getElementById("txtNewDiscount") as HTMLInputElement).value;
code = (document.getElementById("txtNewCode") as HTMLInputElement).value;
//console.log(`itemId: ${itemId} | measurementId: ${measurementId} | quantity: ${quantity} | amount: ${amount} | discount: ${discount}`);
store.addLineItem(0, itemId, measurementId, quantity, amount, discount, code);
(document.getElementById("optNewItemId") as HTMLInputElement).value = "";
(document.getElementById("txtNewCode") as HTMLInputElement).value = "";
(document.getElementById("optNewMeasurementId") as HTMLInputElement).value = "";
(document.getElementById("txtNewQuantity") as HTMLInputElement).value = "1";
(document.getElementById("txtNewAmount") as HTMLInputElement).value = "";
(document.getElementById("txtNewDiscount") as HTMLInputElement).value = "";
}
}
onClickRemoveLineItem(i, e) {
store.removeLineItem(i);
}
onChangeQuantity(e) {
store.updateLineItem(e.target.name, "quantity", e.target.value);
}
onChangeAmount(e) {
store.updateLineItem(e.target.name, "amount", e.target.value);
}
onChangeDiscount(e) {
store.updateLineItem(e.target.name, "discount", e.target.value);
}
onChangeCode(e) {
store.updateLineItem(e.target.name, "code", e.target.value);
}
onFocusOutItem(e, isNew, i) {
var isExisting = false;
for (var x = 0; x < store.commonStore.items.length; x++) {
if (store.commonStore.items[x].code == i.target.value) {
isExisting = true;
if (isNew) {
(document.getElementById("optNewItemId") as HTMLInputElement).value = store.commonStore.items[x].id;
(document.getElementById("optNewMeasurementId") as HTMLInputElement).value =
store.commonStore.items[x].sellMeasurementId;
(document.getElementById("txtNewAmount") as HTMLInputElement).value = store.commonStore.items[x].price;
(document.getElementById("txtNewQuantity") as HTMLInputElement).value = "1";
document.getElementById("txtNewCode").style.borderColor = "";
} else {
store.updateLineItem(e, "itemId", store.commonStore.items[x].id);
store.updateLineItem(e, "measurementId", store.commonStore.items[x].sellMeasurementId);
store.updateLineItem(e, "amount", store.commonStore.items[x].price);
store.updateLineItem(e, "quantity", 1);
i.target.style.borderColor = "";
}
}
}
if (!isExisting)
if (isNew) {
(document.getElementById("optNewItemId") as HTMLInputElement).value = "";
(document.getElementById("optNewMeasurementId") as HTMLInputElement).value = "";
(document.getElementById("txtNewAmount") as HTMLInputElement).value = "";
(document.getElementById("txtNewQuantity") as HTMLInputElement).value = "";
document.getElementById("txtNewCode").style.borderColor = "#FF0000";
//document.getElementById("txtNewCode").appendChild(span);
// document.getElementById("txtNewCode").style.border = 'solid';
} else {
//store.updateLineItem(e, "itemId", "");
//store.updateLineItem(e, "measurementId", "");
//store.updateLineItem(e, "amount", "");
//store.updateLineItem(e, "quantity", "");
i.target.style.borderColor = "red";
//i.target.appendChild(span);
// i.target.style.border = "solid";
}
}
//<td>{store.salesOrder.salesOrderLines[i].itemId}</td>
render() {
var newLine = 0;
var lineItems = [];
for (var i = 0; i < store.salesOrder.salesOrderLines.length; i++) {
newLine = newLine + 10;
lineItems.push(
<tr key={i}>
<td>
<label>{newLine}</label>
</td>
<td>
<SelectLineItem store={store} row={i} selected={store.salesOrder.salesOrderLines[i].itemId} />
</td>
<td>
<input
className="form-control"
type="text"
name={i.toString()}
value={store.salesOrder.salesOrderLines[i].code}
onBlur={this.onFocusOutItem.bind(this, i, false)}
onChange={this.onChangeCode.bind(this)}
/>
</td>
<td>
<SelectLineMeasurement row={i} store={store} selected={store.salesOrder.salesOrderLines[i].measurementId} />
</td>
<td>
<input
type="text"
className="form-control"
name={i.toString()}
value={store.salesOrder.salesOrderLines[i].quantity}
onChange={this.onChangeQuantity.bind(this)}
/>
</td>
<td>
<input
type="text"
className="form-control"
name={i.toString()}
value={store.salesOrder.salesOrderLines[i].amount}
onChange={this.onChangeAmount.bind(this)}
/>
</td>
<td>
<input
type="text"
className="form-control"
name={i.toString()}
value={store.salesOrder.salesOrderLines[i].discount}
onChange={this.onChangeDiscount.bind(this)}
/>
</td>
<td>{store.getLineTotal(i)}</td>
<td>
<button type="button" className="btn btn-box-tool" onClick={this.onClickRemoveLineItem.bind(this, i)}>
<i className="fa fa-fw fa-times" />
</button>
</td>
</tr>
);
}
return (
<div className="card">
<div className="card-header">
<a data-toggle="collapse" href="#line-items" aria-expanded="true" aria-controls="line-items"><i className="fa fa-align-justify"></i></a> Line Items
</div>
<div className="card-body collapse show table-responsive" id="line-items">
<table className="table table-hover">
<thead>
<tr>
<td>No</td>
<td>Item Id</td>
<td>Item Name</td>
<td>Measurement</td>
<td>Quantity</td>
<td>Amount</td>
<td>Discount</td>
<td>Line Total</td>
<td />
</tr>
</thead>
<tbody>
{lineItems}
<tr>
<td />
<td>
<SelectLineItem store={store} controlId="optNewItemId" />
</td>
<td>
<input
className="form-control"
type="text"
id="txtNewCode"
onBlur={this.onFocusOutItem.bind(this, i, true)}
/>
</td>
<td>
<SelectLineMeasurement store={store} controlId="optNewMeasurementId" />
</td>
<td>
<input className="form-control" type="text" id="txtNewQuantity" />
</td>
<td>
<input className="form-control" type="text" id="txtNewAmount" />
</td>
<td>
<input className="form-control" type="text" id="txtNewDiscount" />
</td>
<td />
<td>
<button type="button" className="btn btn-box-tool" onClick={this.addLineItem}>
<i className="fa fa-fw fa-check" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
}
@observer
class SalesOrderTotals extends React.Component<any, {}> {
render() {
return (
<div className="card">
<div className="card-body">
<div className="row">
<div className="col-md-2">
<label>SubTotal: </label>
</div>
<div className="col-md-2">{accounting.formatMoney(store.RTotal, { symbol: "", format: "%s%v" })}</div>
<div className="col-md-2">
<label>Tax: </label>
</div>
<div className="col-md-2">{accounting.formatMoney(store.TTotal, { symbol: "", format: "%s%v" })}</div>
<div className="col-md-2">
<label>Total: </label>
</div>
<div className="col-md-2">{accounting.formatMoney(store.GTotal, { symbol: "", format: "%s%v" })}</div>
</div>
</div>
</div>
);
}
}
@observer
class EditButton extends React.Component<any, {}> {
onClickEditButton() {
// Remove " disabledControl" from current className
var nodes = document.getElementById("divSalesOrderForm").getElementsByTagName("*");
for (var i = 0; i < nodes.length; i++) {
var subStringLength = nodes[i].className.length - " disabledControl".length;
nodes[i].className = nodes[i].className.substring(0, subStringLength);
}
store.changedEditMode(true);
}
render() {
return (
<a
href="#"
id="linkEdit"
onClick={this.onClickEditButton}
className={
!store.editMode && !store.hasQuotation
? //className={store.salesOrder.statusId == 0 && !store.editMode
"btn"
: "btn inactiveLink"
}
>
<i className="fa fa-edit" />
Edit
</a>
);
}
}
export default class SalesOrder extends React.Component<any, {}> {
render() {
return (
<div>
<div id="divActionsTop">
<EditButton />
</div>
<div id="divSalesOrderForm">
<ValidationErrors />
<SalesOrderHeader />
<SalesOrderLines />
<SalesOrderTotals />
</div>
<div>
<SaveOrderButton />
<CancelOrderButton />
</div>
</div>
);
}
}
ReactDOM.render(<SalesOrder />, document.getElementById("divSalesOrder")); | the_stack |
import { AppRecord, BackendContext, DevtoolsApi } from '@vue-devtools/app-backend-api'
import { classify } from '@vue-devtools/shared-utils'
import { ComponentTreeNode, ComponentInstance } from '@vue/devtools-api'
import { getRootElementsFromComponentInstance } from './el'
import { getInstanceName, getRenderKey, getUniqueId, isBeingDestroyed } from './util'
export let instanceMap: Map<any, any>
export let functionalVnodeMap: Map<any, any>
let appRecord: AppRecord
let api: DevtoolsApi
const consoleBoundInstances = Array(5)
let filter = ''
const functionalIds = new Map()
// Dedupe instances
// Some instances may be both on a component and on a child abstract/functional component
const captureIds = new Map()
export async function walkTree (instance, pFilter: string, api: DevtoolsApi, ctx: BackendContext): Promise<ComponentTreeNode[]> {
initCtx(api, ctx)
filter = pFilter
functionalIds.clear()
captureIds.clear()
const result: ComponentTreeNode[] = flatten(await findQualifiedChildren(instance))
return result
}
export function getComponentParents (instance, api: DevtoolsApi, ctx: BackendContext) {
initCtx(api, ctx)
const captureIds = new Map()
const captureId = vm => {
const id = getUniqueId(vm)
if (captureIds.has(id)) return
captureIds.set(id, undefined)
mark(vm)
}
const parents = []
captureId(instance)
let parent = instance
while ((parent = parent.$parent)) {
captureId(parent)
parents.push(parent)
}
return parents
}
function initCtx (_api: DevtoolsApi, ctx: BackendContext) {
appRecord = ctx.currentAppRecord
api = _api
if (!appRecord.meta.instanceMap) {
appRecord.meta.instanceMap = new Map()
}
instanceMap = appRecord.meta.instanceMap
if (!appRecord.meta.functionalVnodeMap) {
appRecord.meta.functionalVnodeMap = new Map()
}
functionalVnodeMap = appRecord.meta.functionalVnodeMap
}
/**
* Iterate through an array of instances and flatten it into
* an array of qualified instances. This is a depth-first
* traversal - e.g. if an instance is not matched, we will
* recursively go deeper until a qualified child is found.
*/
function findQualifiedChildrenFromList (instances: any[]): Promise<ComponentTreeNode[]> {
instances = instances
.filter(child => !isBeingDestroyed(child))
return Promise.all(!filter
? instances.map(capture)
: Array.prototype.concat.apply([], instances.map(findQualifiedChildren)))
}
/**
* Find qualified children from a single instance.
* If the instance itself is qualified, just return itself.
* This is ok because [].concat works in both cases.
*/
async function findQualifiedChildren (instance): Promise<ComponentTreeNode[]> {
if (isQualified(instance)) {
return [await capture(instance)]
} else {
let children = await findQualifiedChildrenFromList(instance.$children)
// Find functional components in recursively in non-functional vnodes.
if (instance._vnode && instance._vnode.children) {
const list = await Promise.all(flatten<Promise<ComponentTreeNode>>((instance._vnode.children as any[]).filter(child => !child.componentInstance).map(captureChild)))
// Filter qualified children.
const additionalChildren = list.filter(instance => isQualified(instance))
children = children.concat(additionalChildren)
}
return children
}
}
/**
* Get children from a component instance.
*/
function getInternalInstanceChildren (instance): any[] {
if (instance.$children) {
return instance.$children
}
return []
}
/**
* Check if an instance is qualified.
*/
function isQualified (instance): boolean {
const name = classify(getInstanceName(instance)).toLowerCase()
return name.indexOf(filter) > -1
}
function flatten<T> (items: any[]): T[] {
const r = items.reduce((acc, item) => {
if (Array.isArray(item)) {
let children = []
for (const i of item) {
if (Array.isArray(i)) {
children = children.concat(flatten(i))
} else {
children.push(i)
}
}
acc.push(...children)
} else if (item) {
acc.push(item)
}
return acc
}, [] as T[])
return r
}
function captureChild (child): Promise<ComponentTreeNode[] | ComponentTreeNode> {
if (child.fnContext && !child.componentInstance) {
return capture(child)
} else if (child.componentInstance) {
if (!isBeingDestroyed(child.componentInstance)) return capture(child.componentInstance)
} else if (child.children) {
return Promise.all(flatten<Promise<ComponentTreeNode>>(child.children.map(captureChild)))
}
}
/**
* Capture the meta information of an instance. (recursive)
*/
async function capture (instance, index?: number, list?: any[]): Promise<ComponentTreeNode> {
if (instance.__VUE_DEVTOOLS_FUNCTIONAL_LEGACY__) {
instance = instance.vnode
}
if (instance.$options && instance.$options.abstract && instance._vnode && instance._vnode.componentInstance) {
instance = instance._vnode.componentInstance
}
if (instance.$options?.devtools?.hide) return
// Functional component.
if (instance.fnContext && !instance.componentInstance) {
const contextUid = instance.fnContext.__VUE_DEVTOOLS_UID__
let id = functionalIds.get(contextUid)
if (id == null) {
id = 0
} else {
id++
}
functionalIds.set(contextUid, id)
const functionalId = contextUid + ':functional:' + id
markFunctional(functionalId, instance)
const childrenPromise = (instance.children
? instance.children.map(
child => child.fnContext
? captureChild(child)
: child.componentInstance
? capture(child.componentInstance)
: undefined,
)
// router-view has both fnContext and componentInstance on vnode.
: instance.componentInstance ? [capture(instance.componentInstance)] : [])
// await all childrenCapture to-be resolved
const children = (await Promise.all(childrenPromise)).filter(Boolean) as ComponentTreeNode[]
const treeNode = {
uid: functionalId,
id: functionalId,
tags: [
{
label: 'functional',
textColor: 0x555555,
backgroundColor: 0xeeeeee,
},
],
name: getInstanceName(instance),
renderKey: getRenderKey(instance.key),
children,
hasChildren: !!children.length,
inactive: false,
isFragment: false, // TODO: Check what is it for.
}
return api.visitComponentTree(
instance,
treeNode,
filter,
appRecord?.options?.app,
)
}
// instance._uid is not reliable in devtools as there
// may be 2 roots with same _uid which causes unexpected
// behaviour
instance.__VUE_DEVTOOLS_UID__ = getUniqueId(instance)
// Dedupe
if (captureIds.has(instance.__VUE_DEVTOOLS_UID__)) {
return
} else {
captureIds.set(instance.__VUE_DEVTOOLS_UID__, undefined)
}
mark(instance)
const name = getInstanceName(instance)
const children = (await Promise.all((await getInternalInstanceChildren(instance))
.filter(child => !isBeingDestroyed(child))
.map(capture))).filter(Boolean)
const ret: ComponentTreeNode = {
uid: instance._uid,
id: instance.__VUE_DEVTOOLS_UID__,
name,
renderKey: getRenderKey(instance.$vnode ? instance.$vnode.key : null),
inactive: !!instance._inactive,
isFragment: !!instance._isFragment,
children,
hasChildren: !!children.length,
tags: [],
meta: {},
}
if (instance._vnode && instance._vnode.children) {
const vnodeChildren = await Promise.all(flatten(instance._vnode.children.map(captureChild)))
ret.children = ret.children.concat(
flatten<any>(vnodeChildren).filter(Boolean),
)
ret.hasChildren = !!ret.children.length
}
// ensure correct ordering
const rootElements = getRootElementsFromComponentInstance(instance)
const firstElement = rootElements[0]
if (firstElement?.parentElement) {
const parentInstance = instance.$parent
const parentRootElements = parentInstance ? getRootElementsFromComponentInstance(parentInstance) : []
let el = firstElement
const indexList = []
do {
indexList.push(Array.from(el.parentElement.childNodes).indexOf(el))
el = el.parentElement
} while (el.parentElement && parentRootElements.length && !parentRootElements.includes(el))
ret.domOrder = indexList.reverse()
} else {
ret.domOrder = [-1]
}
// check if instance is available in console
const consoleId = consoleBoundInstances.indexOf(instance.__VUE_DEVTOOLS_UID__)
ret.consoleId = consoleId > -1 ? '$vm' + consoleId : null
// check router view
const isRouterView2 = instance.$vnode?.data?.routerView
if (instance._routerView || isRouterView2) {
ret.isRouterView = true
if (!instance._inactive && instance.$route) {
const matched = instance.$route.matched
const depth = isRouterView2
? instance.$vnode.data.routerViewDepth
: instance._routerView.depth
ret.meta.matchedRouteSegment =
matched &&
matched[depth] &&
(isRouterView2 ? matched[depth].path : matched[depth].handler.path)
}
ret.tags.push({
label: `router-view${ret.meta.matchedRouteSegment ? `: ${ret.meta.matchedRouteSegment}` : ''}`,
textColor: 0x000000,
backgroundColor: 0xff8344,
})
}
return api.visitComponentTree(
instance,
ret,
filter,
appRecord?.options?.app,
)
}
/**
* Mark an instance as captured and store it in the instance map.
*
* @param {Vue} instance
*/
function mark (instance) {
const refId = instance.__VUE_DEVTOOLS_UID__
if (!instanceMap.has(refId)) {
instanceMap.set(refId, instance)
appRecord.instanceMap.set(refId, instance)
instance.$on('hook:beforeDestroy', function () {
instanceMap.delete(refId)
})
}
}
function markFunctional (id, vnode) {
const refId = vnode.fnContext.__VUE_DEVTOOLS_UID__
if (!functionalVnodeMap.has(refId)) {
functionalVnodeMap.set(refId, {})
vnode.fnContext.$on('hook:beforeDestroy', function () {
functionalVnodeMap.delete(refId)
})
}
functionalVnodeMap.get(refId)[id] = vnode
appRecord.instanceMap.set(id, {
__VUE_DEVTOOLS_UID__: id,
__VUE_DEVTOOLS_FUNCTIONAL_LEGACY__: true,
vnode,
} as unknown as ComponentInstance)
} | the_stack |
import { P2P, events } from '../../src/index';
import { wait } from '../utils/helpers';
import { createNetwork, destroyNetwork, NETWORK_START_PORT } from '../utils/network_setup';
import { REMOTE_EVENT_RPC_GET_PEERS_LIST, REMOTE_EVENT_RPC_GET_NODE_INFO } from '../../src/events';
const { EVENT_MESSAGE_RECEIVED, EVENT_REMOVE_PEER } = events;
describe('Message rate limit', () => {
let p2pNodeList: ReadonlyArray<P2P> = [];
let collectedMessages: Array<any> = [];
let messageRates: Map<number, Array<number>> = new Map();
const removedPeers = new Map();
beforeEach(async () => {
const customConfig = (index: number) => ({
// For the third node, make the message rate limit higher.
wsMaxMessageRate: index === 2 ? 100000 : 110,
rateCalculationInterval: 100,
fallbackSeedPeerDiscoveryInterval: 10000,
});
p2pNodeList = await createNetwork({ customConfig });
for (const p2p of p2pNodeList) {
// eslint-disable-next-line no-loop-func
p2p.on(EVENT_MESSAGE_RECEIVED, message => {
collectedMessages.push({
nodePort: p2p.config.port,
message,
});
const peerRates = messageRates.get(p2p.config.port) ?? [];
peerRates.push(message.rate);
messageRates.set(p2p.config.port, peerRates);
});
}
const secondP2PNode = p2pNodeList[1];
secondP2PNode.on(EVENT_REMOVE_PEER, peerId => {
const peerport = peerId.split(':')[1];
const localRemovedNodes = [];
if (removedPeers.get(secondP2PNode.config.port)) {
localRemovedNodes.push(...removedPeers.get(secondP2PNode.config.port));
}
localRemovedNodes.push(peerport);
removedPeers.set(secondP2PNode.config.port, localRemovedNodes);
});
const thirdP2PNode = p2pNodeList[2];
thirdP2PNode.on(EVENT_REMOVE_PEER, peerId => {
const peerport = peerId.split(':')[1];
const localRemovedNodes = [];
if (removedPeers.get(thirdP2PNode.config.port)) {
localRemovedNodes.push(...removedPeers.get(thirdP2PNode.config.port));
}
localRemovedNodes.push(peerport);
removedPeers.set(thirdP2PNode.config.port, localRemovedNodes);
});
});
afterEach(async () => {
await destroyNetwork(p2pNodeList);
});
describe('P2P.sendToPeer', () => {
beforeEach(() => {
collectedMessages = [];
messageRates = new Map();
});
it('should track the message rate correctly when receiving messages', async () => {
const TOTAL_SENDS = 100;
const firstP2PNode = p2pNodeList[0];
const ratePerSecondLowerBound = 60;
const ratePerSecondUpperBound = 130;
const targetPeerPort = NETWORK_START_PORT + 3;
const targetPeerId = `127.0.0.1:${targetPeerPort}`;
for (let i = 0; i < TOTAL_SENDS; i += 1) {
await wait(10);
try {
firstP2PNode.sendToPeer(
{
event: 'foo',
data: i,
},
targetPeerId,
);
// eslint-disable-next-line no-empty
} catch (error) {}
}
await wait(50);
const secondPeerRates = messageRates.get(targetPeerPort) ?? [];
const lastRate = secondPeerRates[secondPeerRates.length - 1];
expect(lastRate).toBeGreaterThan(ratePerSecondLowerBound);
expect(lastRate).toBeLessThan(ratePerSecondUpperBound);
});
it('should disconnect the peer if it tries to send messages at a rate above wsMaxMessageRate', async () => {
const TOTAL_SENDS = 300;
const firstP2PNode = p2pNodeList[0];
const secondP2PNode = p2pNodeList[1];
const targetPeerId = `127.0.0.1:${secondP2PNode.config.port}`;
for (let i = 0; i < TOTAL_SENDS; i += 1) {
await wait(1);
try {
firstP2PNode.sendToPeer(
{
event: 'foo',
data: i,
},
targetPeerId,
);
// eslint-disable-next-line no-empty
} catch (error) {}
}
await wait(10);
expect(removedPeers.get(secondP2PNode.config.port)).toEqual(
expect.arrayContaining([firstP2PNode.config.port.toString()]),
);
});
});
describe('P2P.requestFromPeer', () => {
let requestRates: Map<number, Array<number>> = new Map();
beforeEach(() => {
collectedMessages = [];
requestRates = new Map();
for (const p2p of p2pNodeList) {
// eslint-disable-next-line no-loop-func
p2p.on('EVENT_REQUEST_RECEIVED', request => {
collectedMessages.push({
nodePort: p2p.config.port,
request,
});
if (request.procedure === 'getGreeting') {
request.end(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Hello ${request.data} from peer ${p2p.config.port}`,
);
} else if (!request.wasResponseSent) {
request.end(456);
}
const peerRates = requestRates.get(p2p.config.port) ?? [];
peerRates.push(request.rate);
requestRates.set(p2p.config.port, peerRates);
});
}
});
it('should track the request rate correctly when receiving requests', async () => {
const TOTAL_SENDS = 100;
const requesterP2PNode = p2pNodeList[1];
const ratePerSecondLowerBound = 60;
const ratePerSecondUpperBound = 130;
const targetPeerPort = NETWORK_START_PORT;
const targetPeerId = `127.0.0.1:${targetPeerPort}`;
for (let i = 0; i < TOTAL_SENDS; i += 1) {
await wait(10);
await requesterP2PNode.requestFromPeer(
{
procedure: 'proc',
data: 123456,
},
targetPeerId,
);
}
await wait(50);
const secondPeerRates = requestRates.get(targetPeerPort) ?? [];
const lastRate = secondPeerRates[secondPeerRates.length - 1];
expect(lastRate).toBeGreaterThan(ratePerSecondLowerBound);
expect(lastRate).toBeLessThan(ratePerSecondUpperBound);
});
it('should disconnect the peer if it tries to send responses at a rate above wsMaxMessageRate', async () => {
const TOTAL_SENDS = 300;
const requesterP2PNode = p2pNodeList[0];
const targetP2PNode = p2pNodeList[1];
const targetPeerId = `127.0.0.1:${targetP2PNode.config.port}`;
for (let i = 0; i < TOTAL_SENDS; i += 1) {
await wait(1);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
try {
await requesterP2PNode.requestFromPeer(
{
procedure: 'proc',
data: 123456,
},
targetPeerId,
);
// eslint-disable-next-line no-empty
} catch (error) {}
})();
}
await wait(10);
expect(removedPeers.get(targetP2PNode.config.port)).toEqual(
expect.arrayContaining([requesterP2PNode.config.port.toString()]),
);
});
});
describe('Post node info message rate limit', () => {
it('should not ban the attacker node if it sends only 4 nodeInfo messages in 10 seconds', async () => {
// Arrange
const attackerNode = p2pNodeList[0];
const targetNode = p2pNodeList[1];
// Act
// Send nodeInfo message 3 times, so total of 4 messages of max allowed and not get ban score
for (let i = 0; i < 3; i += 1) {
attackerNode.applyNodeInfo(attackerNode.nodeInfo);
}
await wait(10);
// Assert
expect(targetNode['_peerBook'].triedPeers[0].internalState?.reputation).toEqual(100);
});
it('should add a ban score of peer when it sends postNodeInfo messages more than 4 within 10 seconds', async () => {
// Arrange
const attackerNode = p2pNodeList[0];
const targetNode = p2pNodeList[1];
// Act
// Send nodeInfo message 4 times and once its send on connection to get a ban score
for (let i = 0; i < 4; i += 1) {
attackerNode.applyNodeInfo(attackerNode.nodeInfo);
}
await wait(10);
// Assert
expect(targetNode['_peerBook'].triedPeers[0].internalState?.reputation).toEqual(90);
});
it('should ban a peer when it sends postNodeInfo messages more than 4 + 10 times within 10 seconds', async () => {
// Arrange
const attackerNode = p2pNodeList[0];
const targetNode = p2pNodeList[1];
// Act
// Send nodeInfo message 14 times and once its send on connection (total of 15 messages to get banned)
for (let i = 0; i < 14; i += 1) {
attackerNode.applyNodeInfo(attackerNode.nodeInfo);
}
await wait(10);
// Assert
expect(removedPeers.get(targetNode.config.port)).toEqual(
expect.arrayContaining([attackerNode.config.port.toString()]),
);
});
});
describe('Request peerList or nodeInfo more than once', () => {
it('should ban a peer when it requests getPeers RPC explicitly for more than 10 times', async () => {
// Arrange
const attackerNode = p2pNodeList[0];
const targetNode = p2pNodeList[1];
const targetPeerId = `127.0.0.1:${targetNode.config.port}`;
// Act
// With every getPeers RPC request apply penalty of 10, 10 * 10 times will result in banning
for (let i = 0; i < 10; i += 1) {
await wait(1);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
try {
await attackerNode.requestFromPeer(
{
procedure: REMOTE_EVENT_RPC_GET_PEERS_LIST,
},
targetPeerId,
);
// eslint-disable-next-line no-empty
} catch (error) {}
})();
}
await wait(10);
// Assert
expect(removedPeers.get(targetNode.config.port)).toEqual(
expect.arrayContaining([attackerNode.config.port.toString()]),
);
});
it('should ban a peer when it requests RPC getNodeInfo explicitly for more than 10 times', async () => {
// Arrange
const attackerNode = p2pNodeList[0];
const targetNode = p2pNodeList[1];
const targetPeerId = `127.0.0.1:${targetNode.config.port}`;
// Act
// With every getNodeInfo RPC request apply penalty of 10, 10 * 10 times will result in banning
for (let i = 0; i < 10; i += 1) {
await wait(1);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
try {
await attackerNode.requestFromPeer(
{
procedure: REMOTE_EVENT_RPC_GET_NODE_INFO,
},
targetPeerId,
);
// eslint-disable-next-line no-empty
} catch (error) {}
})();
}
await wait(10);
// Assert
expect(removedPeers.get(targetNode.config.port)).toEqual(
expect.arrayContaining([attackerNode.config.port.toString()]),
);
});
});
}); | the_stack |
import './ToolbarButton.scss'
import React, { useRef, useEffect } from 'react'
import { useActions, useValues } from 'kea'
import { HogLogo } from '~/toolbar/assets/HogLogo'
import { Circle } from '~/toolbar/button/Circle'
import { toolbarButtonLogic } from '~/toolbar/button/toolbarButtonLogic'
import { heatmapLogic } from '~/toolbar/elements/heatmapLogic'
import { toolbarLogic } from '~/toolbar/toolbarLogic'
import { getShadowRoot, getShadowRootPopupContainer } from '~/toolbar/utils'
import { elementsLogic } from '~/toolbar/elements/elementsLogic'
import { useLongPress } from 'lib/hooks/useLongPress'
import { Flag } from '~/toolbar/button/icons/Flag'
import { Fire } from '~/toolbar/button/icons/Fire'
import { Magnifier } from '~/toolbar/button/icons/Magnifier'
import { actionsTabLogic } from '~/toolbar/actions/actionsTabLogic'
import { actionsLogic } from '~/toolbar/actions/actionsLogic'
import { Close } from '~/toolbar/button/icons/Close'
import { AimOutlined, QuestionOutlined } from '@ant-design/icons'
import { Tooltip } from 'lib/components/Tooltip'
import { FEATURE_FLAGS } from 'lib/constants'
const HELP_URL =
'https://posthog.com/docs/tutorials/toolbar?utm_medium=in-product&utm_source=in-product&utm_campaign=toolbar-help-button'
export function ToolbarButton(): JSX.Element {
const {
extensionPercentage,
heatmapInfoVisible,
toolbarListVerticalPadding,
helpButtonOnTop,
side,
closeDistance,
closeRotation,
inspectExtensionPercentage,
heatmapExtensionPercentage,
actionsExtensionPercentage,
actionsInfoVisible,
featureFlagsExtensionPercentage,
flagsVisible,
} = useValues(toolbarButtonLogic)
const {
setExtensionPercentage,
showHeatmapInfo,
hideHeatmapInfo,
showActionsInfo,
hideActionsInfo,
showFlags,
hideFlags,
} = useActions(toolbarButtonLogic)
const { buttonActionsVisible, showActionsTooltip } = useValues(actionsTabLogic)
const { hideButtonActions, showButtonActions } = useActions(actionsTabLogic)
const { actionCount, allActionsLoading } = useValues(actionsLogic)
const { enableInspect, disableInspect } = useActions(elementsLogic)
const { inspectEnabled, selectedElement } = useValues(elementsLogic)
const { enableHeatmap, disableHeatmap } = useActions(heatmapLogic)
const { heatmapEnabled, heatmapLoading, elementCount, showHeatmapTooltip } = useValues(heatmapLogic)
const { isAuthenticated, featureFlags } = useValues(toolbarLogic)
const { authenticate, logout } = useActions(toolbarLogic)
const globalMouseMove = useRef((e: MouseEvent) => {
e
})
// Tricky: the feature flag's used here are not PostHog's normal feature flags, rather they're
// the feature flags of the user. The toolbar does not have access to posthog's feature flags because
// it uses Posthog-js-lite. As a result, this feature flag can only be turned on for posthog internal
// (or any other posthog customer that has a flag with the name `posthog-toolbar-feature-flags` set).
// (Should be removed when we want to roll this out broadly)
const showFeatureFlags = featureFlags[FEATURE_FLAGS.TOOLBAR_FEATURE_FLAGS]
useEffect(
() => {
globalMouseMove.current = function (e: MouseEvent): void {
const buttonDiv = getShadowRoot()?.getElementById('button-toolbar')
if (buttonDiv) {
const rect = buttonDiv.getBoundingClientRect()
const x = rect.left + rect.width / 2
const y = rect.top + rect.height / 2
const distance = Math.sqrt((e.clientX - x) * (e.clientX - x) + (e.clientY - y) * (e.clientY - y))
const maxDistance = isAuthenticated ? 300 : 100
if (distance >= maxDistance && toolbarButtonLogic.values.extensionPercentage !== 0) {
setExtensionPercentage(0)
}
}
}
window.addEventListener('mousemove', globalMouseMove.current)
return () => window.removeEventListener('mousemove', globalMouseMove.current)
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isAuthenticated]
)
// using useLongPress for short presses (clicks) since it detects if the element was dragged (no click) or not (click)
const clickEvents = useLongPress(
(clicked) => {
if (clicked) {
if (isAuthenticated) {
setExtensionPercentage(extensionPercentage === 1 ? 0 : 1)
} else {
authenticate()
}
}
},
{
ms: undefined,
clickMs: 1,
touch: true,
click: true,
}
)
const borderRadius = 14
const buttonWidth = 42
let n = 0
return (
<Circle
rootNode
width={62}
className="floating-toolbar-button"
content={<HogLogo style={{ width: 45, cursor: 'pointer' }} />}
{...clickEvents}
onMouseOver={isAuthenticated ? undefined : () => setExtensionPercentage(1)}
style={{ borderRadius: 10, height: 46, marginTop: -23 }}
zIndex={3}
>
<Circle
width={26}
extensionPercentage={extensionPercentage}
distance={closeDistance}
rotation={closeRotation}
content={<Close style={{ width: 14, height: 14 }} />}
zIndex={extensionPercentage > 0.95 ? 5 : 2}
onClick={logout}
style={{
cursor: 'pointer',
background: '#393939',
borderRadius: 6,
color: 'white',
transform: `scale(${0.2 + 0.8 * extensionPercentage})`,
}}
/>
{isAuthenticated ? (
<>
<Circle
width={32}
extensionPercentage={extensionPercentage}
distance={helpButtonOnTop ? 75 : 55}
rotation={helpButtonOnTop ? (side === 'left' ? -95 + 360 : -95) : 90}
content={<QuestionOutlined style={{ fontSize: 22 }} />}
label="Help"
zIndex={2}
onClick={() => window.open(HELP_URL, '_blank')?.focus()}
labelStyle={{ opacity: extensionPercentage > 0.8 ? (extensionPercentage - 0.8) / 0.2 : 0 }}
style={{
cursor: 'pointer',
background: '#777',
color: 'white',
borderRadius: 10,
transform: `scale(${0.2 + 0.8 * extensionPercentage})`,
}}
/>
<Circle
width={buttonWidth}
x={side === 'left' ? 80 : -80}
y={toolbarListVerticalPadding + n++ * 60}
extensionPercentage={inspectExtensionPercentage}
rotationFixer={(r) => (side === 'right' && r < 0 ? 360 : 0)}
label="Inspect"
labelPosition={side === 'left' ? 'right' : 'left'}
labelStyle={{
opacity: inspectExtensionPercentage > 0.8 ? (inspectExtensionPercentage - 0.8) / 0.2 : 0,
}}
content={
<div style={{ position: 'relative' }}>
<Magnifier style={{ height: 34, paddingTop: 2 }} engaged={inspectEnabled} />
{inspectEnabled && selectedElement ? (
<div
style={{
position: 'absolute',
top: 8,
left: 9,
fontSize: 13,
color: 'white',
}}
>
<Close style={{ width: 10, height: 10 }} />
</div>
) : null}
</div>
}
zIndex={1}
onClick={inspectEnabled ? disableInspect : enableInspect}
style={{
cursor: 'pointer',
background: inspectEnabled ? '#8F98FF' : '#E7EAFD',
transition: 'transform 0.2s, color 0.2s, background: 0.2s',
transform: `scale(${0.2 + 0.8 * inspectExtensionPercentage})`,
borderRadius,
}}
/>
<Circle
width={buttonWidth}
x={side === 'left' ? 80 : -80}
y={toolbarListVerticalPadding + n++ * 60}
extensionPercentage={heatmapExtensionPercentage}
rotationFixer={(r) => (side === 'right' && r < 0 ? 360 : 0)}
label={heatmapEnabled && !heatmapLoading ? null : 'Heatmap'}
labelPosition={side === 'left' ? 'right' : 'left'}
labelStyle={{
opacity:
heatmapEnabled && !heatmapLoading
? 0
: heatmapExtensionPercentage > 0.8
? (heatmapExtensionPercentage - 0.8) / 0.2
: 0,
}}
content={<Fire style={{ height: 26 }} engaged={heatmapEnabled} animated={heatmapLoading} />}
zIndex={2}
onClick={heatmapEnabled ? disableHeatmap : enableHeatmap}
style={{
cursor: 'pointer',
background: heatmapEnabled ? '#FF9870' : '#FEE3DA',
transform: `scale(${0.2 + 0.8 * heatmapExtensionPercentage})`,
borderRadius,
}}
>
{heatmapEnabled && !heatmapLoading ? (
<Circle
width={26}
x={
(side === 'left' ? 50 : -50) *
heatmapExtensionPercentage *
heatmapExtensionPercentage
}
y={0}
content={
<Tooltip
visible={showHeatmapTooltip}
title="Click for details"
placement={side === 'left' ? 'right' : 'left'}
getPopupContainer={getShadowRootPopupContainer}
>
<div style={{ whiteSpace: 'nowrap', textAlign: 'center' }}>{elementCount}</div>
</Tooltip>
}
zIndex={4}
onClick={heatmapInfoVisible ? hideHeatmapInfo : showHeatmapInfo}
style={{
cursor: 'pointer',
background: heatmapInfoVisible ? 'hsla(17, 100%, 47%, 1)' : 'hsla(17, 84%, 95%, 1)',
color: heatmapInfoVisible ? '#FFEB3B' : 'hsl(17, 64%, 32%)',
width: 'auto',
minWidth: 26,
fontSize: '20px',
lineHeight: '26px',
padding: '0 4px',
transform: `scale(${0.2 + 0.8 * heatmapExtensionPercentage})`,
borderRadius: 7,
}}
/>
) : null}
</Circle>
<Circle
width={buttonWidth}
x={side === 'left' ? 80 : -80}
y={toolbarListVerticalPadding + n++ * 60}
extensionPercentage={actionsExtensionPercentage}
rotationFixer={(r) => (side === 'right' && r < 0 ? 360 : 0)}
label={buttonActionsVisible && (!allActionsLoading || actionCount > 0) ? null : 'Actions'}
labelPosition={side === 'left' ? 'right' : 'left'}
labelStyle={{
opacity: actionsExtensionPercentage > 0.8 ? (actionsExtensionPercentage - 0.8) / 0.2 : 0,
}}
content={
<AimOutlined
style={{ fontSize: '28px', color: buttonActionsVisible ? '#fef5e2' : '#f1aa04' }}
/>
}
zIndex={1}
onClick={buttonActionsVisible ? hideButtonActions : showButtonActions}
style={{
cursor: 'pointer',
transform: `scale(${0.2 + 0.8 * actionsExtensionPercentage})`,
background: buttonActionsVisible ? '#f1aa04' : '#fef5e2',
borderRadius,
}}
>
{buttonActionsVisible && (!allActionsLoading || actionCount > 0) ? (
<Circle
width={26}
x={
(side === 'left' ? 50 : -50) *
actionsExtensionPercentage *
actionsExtensionPercentage
}
y={0}
content={
<Tooltip
visible={showActionsTooltip}
title="Click for details"
placement={side === 'left' ? 'right' : 'left'}
getPopupContainer={getShadowRootPopupContainer}
>
<div style={{ whiteSpace: 'nowrap', textAlign: 'center' }}>{actionCount}</div>
</Tooltip>
}
zIndex={4}
onClick={actionsInfoVisible ? hideActionsInfo : showActionsInfo}
style={{
cursor: 'pointer',
background: actionsInfoVisible ? '#f1aa04' : '#fef5e2',
color: actionsInfoVisible ? '#fef5e2' : '#f1aa04',
width: 'auto',
minWidth: 26,
fontSize: '20px',
lineHeight: '26px',
padding: '0 4px',
transform: `scale(${0.2 + 0.8 * actionsExtensionPercentage})`,
borderRadius: 7,
}}
/>
) : null}
</Circle>
{showFeatureFlags ? (
<Circle
width={buttonWidth}
x={side === 'left' ? 80 : -80}
y={toolbarListVerticalPadding + n++ * 60}
extensionPercentage={featureFlagsExtensionPercentage}
rotationFixer={(r) => (side === 'right' && r < 0 ? 360 : 0)}
label="Feature Flags"
labelPosition={side === 'left' ? 'right' : 'left'}
labelStyle={{
opacity:
featureFlagsExtensionPercentage > 0.8
? (featureFlagsExtensionPercentage - 0.8) / 0.2
: 0,
}}
content={<Flag style={{ height: 29 }} engaged={flagsVisible} />}
zIndex={1}
onClick={flagsVisible ? hideFlags : showFlags}
style={{
cursor: 'pointer',
transform: `scale(${0.2 + 0.8 * featureFlagsExtensionPercentage})`,
background: flagsVisible ? '#94D674' : '#D6EBCC',
borderRadius,
}}
/>
) : null}
</>
) : null}
</Circle>
)
} | the_stack |
import G = require('./ggraph');
import M = require('./messages');
importScripts("sharpkit_pre.js");
importScripts("jsclr.js");
importScripts("Microsoft.Msagl.js");
importScripts("sharpkit_post.js");
/** Namespace for SharpKit-generated code. */
declare var Microsoft: any;
/** Name of the SharpKit type test function that exists in jsclr.js. */
declare var Is: any;
/** Variable that exists in web workers as a reference to the worker. */
declare var self: any;
type SetPolylineResult = { curve: G.GCurve, sourceArrowHeadStart: G.GPoint, sourceArrowHeadEnd: G.GPoint, targetArrowHeadStart: G.GPoint, targetArrowHeadEnd: G.GPoint };
type NodeMap = { [id: string]: { mnode: any, gnode: G.GNode } };
type EdgeMap = { [id: string]: { medge: any, gedge: G.GEdge } };
/** This class includes code to convert a GGraph to and from MSAGL shape - or, more accurately, the shape that SharpKit outputs on converting the
MSAGL data structures. It can use this to run a layout operation (synchronously). */
class LayoutWorker {
private getMsaglPoint(ipoint: G.IPoint): any {
return new Microsoft.Msagl.Core.Geometry.Point.ctor$$Double$$Double(ipoint.x, ipoint.y);
}
private getMsaglRect(grect: G.GRect): any {
return new Microsoft.Msagl.Core.Geometry.Rectangle.ctor$$Double$$Double$$Point(grect.x, grect.y, this.getMsaglPoint({ x: grect.width, y: grect.height }));
}
/** Converts a GCurve to a MSAGL curve (depending on the type of curve). */
private getMsaglCurve(gcurve: G.GCurve): any {
if (gcurve == null)
return null;
else if (gcurve.curvetype == "Ellipse") {
var gellipse = <G.GEllipse>gcurve;
return new Microsoft.Msagl.Core.Geometry.Curves.Ellipse.ctor$$Double$$Double$$Point$$Point$$Point(
gellipse.parStart,
gellipse.parEnd,
this.getMsaglPoint(gellipse.axisA),
this.getMsaglPoint(gellipse.axisB),
this.getMsaglPoint(gellipse.center));
}
else if (gcurve.curvetype == "Line") {
var gline = <G.GLine>gcurve;
return new Microsoft.Msagl.Core.Geometry.Curves.LineSegment.ctor$$Point$$Point(
this.getMsaglPoint(gline.start),
this.getMsaglPoint(gline.end));
}
else if (gcurve.curvetype == "Bezier") {
var gbezier = <G.GBezier>gcurve;
return new Microsoft.Msagl.Core.Geometry.Curves.CubicBezierSegment.ctor(
this.getMsaglPoint(gbezier.start),
this.getMsaglPoint(gbezier.p1),
this.getMsaglPoint(gbezier.p2),
this.getMsaglPoint(gbezier.p3));
}
else if (gcurve.curvetype == "Polyline") {
var gpolyline = <G.GPolyline>gcurve;
var points: any[] = [];
for (var i = 0; i < gpolyline.points.length; i++)
points.push(this.getMsaglPoint(gpolyline.points[i]));
return new Microsoft.Msagl.Core.Geometry.Curves.Polyline.ctor$$IEnumerable$1$Point(points);
}
else if (gcurve.curvetype == "RoundedRect") {
var groundedrect = <G.GRoundedRect>gcurve;
return new Microsoft.Msagl.Core.Geometry.Curves.RoundedRect.ctor$$Rectangle$$Double$$Double(
this.getMsaglRect(groundedrect.bounds),
groundedrect.radiusX,
groundedrect.radiusY);
}
else if (gcurve.curvetype == "SegmentedCurve") {
// In the case of a SegmentedCurve, I actually need to convert each of the sub-curves, and then build a MSAGL
// object out of them.
var gsegcurve = <G.GSegmentedCurve>gcurve;
var curves: any[] = [];
for (var i = 0; i < gsegcurve.segments.length; i++)
curves.push(this.getMsaglCurve(gsegcurve.segments[i]));
return new Microsoft.Msagl.Core.Geometry.Curves.Curve.ctor$$List$1$ICurve(curves);
}
return null;
}
private addNodeToMsagl(graph: any, rootCluster: any, nodeMap: NodeMap, gnode: G.GNode): any {
var children = (<G.GCluster>gnode).children;
var node: any = null;
if (children != null) {
var gcluster = <G.GCluster>gnode;
node = new Microsoft.Msagl.Core.Layout.Cluster.ctor();
for (let child of children) {
let childNode = this.addNodeToMsagl(graph, node, nodeMap, child);
if ((<G.GCluster>child).children == null)
node.AddNode(childNode);
}
node.set_GeometryParent(rootCluster);
var rectangularBoundary = new Microsoft.Msagl.Core.Geometry.RectangularClusterBoundary.ctor();
rectangularBoundary.set_BottomMargin(gcluster.margin.bottom);
rectangularBoundary.set_TopMargin(gcluster.margin.top);
rectangularBoundary.set_RightMargin(gcluster.margin.right);
rectangularBoundary.set_LeftMargin(gcluster.margin.left);
rectangularBoundary.set_MinWidth(gcluster.margin.minWidth);
rectangularBoundary.set_MinHeight(gcluster.margin.minHeight);
node.set_RectangularBoundary(rectangularBoundary);
rootCluster.AddCluster(node);
}
else {
node = new Microsoft.Msagl.Core.Layout.Node.ctor();
graph.get_Nodes().Add(node);
var curve = this.getMsaglCurve(gnode.boundaryCurve);
if (curve == null)
curve = this.getMsaglCurve(new G.GRoundedRect({
bounds: { x: 0, y: 0, width: 0, height: 0 }, radiusX: 0, radiusY: 0
}));
node.set_BoundaryCurve(curve);
}
node.set_UserData(gnode.id);
nodeMap[gnode.id] = { mnode: node, gnode: gnode };
return node;
}
private addEdgeToMsagl(graph: any, nodeMap: NodeMap, edgeMap: { [idx: string]: any }, gedge: G.GEdge) {
var source = nodeMap[gedge.source].mnode;
var target = nodeMap[gedge.target].mnode;
var edge = new Microsoft.Msagl.Core.Layout.Edge.ctor$$Node$$Node(source, target);
var curve = this.getMsaglCurve(gedge.curve);
if (curve != null)
edge.set_Curve(curve);
if (gedge.label != null) {
var label = new Microsoft.Msagl.Core.Layout.Label.ctor$$Double$$Double$$GeometryObject(gedge.label.bounds.width, gedge.label.bounds.height, edge);
label.set_GeometryParent(edge);
edge.set_Label(label);
}
if (gedge.arrowHeadAtSource != null)
edge.get_EdgeGeometry().set_SourceArrowhead(new Microsoft.Msagl.Core.Layout.Arrowhead.ctor());
if (gedge.arrowHeadAtTarget != null)
edge.get_EdgeGeometry().set_TargetArrowhead(new Microsoft.Msagl.Core.Layout.Arrowhead.ctor());
graph.get_Edges().Add(edge);
edgeMap[gedge.id] = { medge: edge, gedge: gedge };
}
/** Converts a GGraph to a MSAGL geometry graph. The GGraph is stored inside the MSAGL graph, so that it can be retrieved later. */
private getMsagl(ggraph: G.GGraph): { graph: any, settings: any, nodeMap: NodeMap, edgeMap: EdgeMap, source: G.GGraph } {
var nodeMap: { [id: string]: { mnode: any, gnode: G.GNode } } = {};
var edgeMap: { [id: string]: { medge: any, gedge: G.GEdge } } = {};
var graph = new Microsoft.Msagl.Core.Layout.GeometryGraph.ctor();
// Add nodes (and clusters)
var rootCluster = graph.get_RootCluster();
rootCluster.set_GeometryParent(graph);
for (var i = 0; i < ggraph.nodes.length; i++)
this.addNodeToMsagl(graph, rootCluster, nodeMap, ggraph.nodes[i]);
// Add edges
for (var i = 0; i < ggraph.edges.length; i++)
this.addEdgeToMsagl(graph, nodeMap, edgeMap, ggraph.edges[i]);
// Set the settings. Different layout algorithm support different settings.
var settings: any;
if (ggraph.settings.layout == G.GSettings.mdsLayout) {
settings = new Microsoft.Msagl.Layout.MDS.MdsLayoutSettings.ctor();
settings.set_IterationsWithMajorization(settings.iterationsWithMajorization);
}
else {
settings = new Microsoft.Msagl.Layout.Layered.SugiyamaLayoutSettings.ctor();
// Set the plane transformation used for the Sugiyama layout.
var transformation = new Microsoft.Msagl.Core.Geometry.Curves.PlaneTransformation.ctor$$Double$$Double$$Double$$Double$$Double$$Double(
ggraph.settings.transformation.m00, ggraph.settings.transformation.m01, ggraph.settings.transformation.m02,
ggraph.settings.transformation.m10, ggraph.settings.transformation.m11, ggraph.settings.transformation.m12);
settings.set_Transformation(transformation);
// Set the enforced aspect ratio for the Sugiyama layout.
settings.set_AspectRatio(ggraph.settings.aspectRatio);
// Set the up/down constraints for the Sugiyama layout.
for (var i = 0; i < ggraph.settings.upDownConstraints.length; i++) {
var upNode = nodeMap[ggraph.settings.upDownConstraints[i].upNode].mnode;
var downNode = nodeMap[ggraph.settings.upDownConstraints[i].downNode].mnode;
settings.AddUpDownConstraint(upNode, downNode);
}
}
// All layout algorithms support certain edge routing algorithms (they are called after laying out the nodes).
var edgeRoutingSettings = settings.get_EdgeRoutingSettings();
if (ggraph.settings.routing == G.GSettings.splinesRouting)
edgeRoutingSettings.set_EdgeRoutingMode(Microsoft.Msagl.Core.Routing.EdgeRoutingMode.Spline);
else if (ggraph.settings.routing == G.GSettings.splinesBundlingRouting)
edgeRoutingSettings.set_EdgeRoutingMode(Microsoft.Msagl.Core.Routing.EdgeRoutingMode.SplineBundling);
else if (ggraph.settings.routing == G.GSettings.straightLineRouting)
edgeRoutingSettings.set_EdgeRoutingMode(Microsoft.Msagl.Core.Routing.EdgeRoutingMode.StraightLine);
else if (ggraph.settings.routing == G.GSettings.rectilinearRouting)
edgeRoutingSettings.set_EdgeRoutingMode(Microsoft.Msagl.Core.Routing.EdgeRoutingMode.Rectilinear);
else if (ggraph.settings.routing == G.GSettings.rectilinearToCenterRouting)
edgeRoutingSettings.set_EdgeRoutingMode(Microsoft.Msagl.Core.Routing.EdgeRoutingMode.RectilinearToCenter);
return { graph: graph, settings: settings, nodeMap: nodeMap, edgeMap: edgeMap, source: ggraph };
}
private getGPoint(point: any): G.GPoint {
return new G.GPoint({ x: point.get_X(), y: point.get_Y() });
}
private getGRect(rect: any): G.GRect {
return new G.GRect({ x: rect.get_Left(), y: rect.get_Bottom(), width: rect.get_Width(), height: rect.get_Height() });
}
/** Converts a MSAGL curve to a TS curve object. */
private getGCurve(curve: any): G.GCurve {
var ret: G.GCurve;
if (Is(curve, Microsoft.Msagl.Core.Geometry.Curves.Curve.ctor)) {
// The segmented curve is a special case; each of its components need to get converted separately.
var segments: G.GCurve[] = [];
var sEn = curve.get_Segments().GetEnumerator();
while (sEn.MoveNext())
segments.push(this.getGCurve(sEn.get_Current()));
ret = new G.GSegmentedCurve({
type: "SegmentedCurve",
segments: segments
});
}
else if (Is(curve, Microsoft.Msagl.Core.Geometry.Curves.Polyline.ctor)) {
var points: G.GPoint[] = [];
var pEn = curve.get_PolylinePoints().GetEnumerator();
while (pEn.MoveNext())
points.push(this.getGPoint(pEn.get_Current()));
ret = new G.GPolyline({
type: "Polyline",
start: this.getGPoint(curve.get_Start()),
points: points,
closed: curve.get_Closed()
});
}
else if (Is(curve, Microsoft.Msagl.Core.Geometry.Curves.CubicBezierSegment.ctor)) {
ret = new G.GBezier({
type: "Bezier",
start: this.getGPoint(curve.get_Start()),
p1: this.getGPoint(curve.B(1)),
p2: this.getGPoint(curve.B(2)),
p3: this.getGPoint(curve.B(3)),
});
}
else if (Is(curve, Microsoft.Msagl.Core.Geometry.Curves.LineSegment.ctor)) {
ret = new G.GLine({
type: "Line",
start: this.getGPoint(curve.get_Start()),
end: this.getGPoint(curve.get_End())
});
}
else if (Is(curve, Microsoft.Msagl.Core.Geometry.Curves.Ellipse.ctor)) {
ret = new G.GEllipse({
type: "Ellipse",
axisA: this.getGPoint(curve.get_AxisA()),
axisB: this.getGPoint(curve.get_AxisB()),
center: this.getGPoint(curve.get_Center()),
parEnd: curve.get_ParEnd(),
parStart: curve.get_ParStart()
});
}
else if (Is(curve, Microsoft.Msagl.Core.Geometry.Curves.RoundedRect.ctor)) {
ret = new G.GRoundedRect({
type: "RoundedRect",
bounds: this.getGRect(curve.get_BoundingBox()),
radiusX: curve.get_RadiusX(),
radiusY: curve.get_RadiusY()
});
}
return ret;
}
/** Converts a MSAGL graph into a GGraph. More accurately, it gets back the GGraph that was originally used to make the MSAGL
graph, and sets all of its geometrical elements to the ones that were calculated by MSAGL. */
private getGGraph(msagl: any): G.GGraph {
msagl.source.boundingBox = this.getGRect(msagl.graph.get_BoundingBox());
// Get the node boundary curves and labels.
for (var id in msagl.nodeMap) {
var node = msagl.nodeMap[id].mnode;
var gnode: G.GNode = msagl.nodeMap[id].gnode;
var curve = node.get_BoundaryCurve();
gnode.boundaryCurve = this.getGCurve(curve);
if (gnode.label != null) {
if ((<G.GCluster>gnode).children != null) {
// It's a cluster. Position the label at the top.
gnode.label.bounds.x = node.get_Center().get_X() - gnode.label.bounds.width / 2;
gnode.label.bounds.y = node.get_BoundingBox().get_Bottom() + gnode.label.bounds.height / 2;
}
else {
// It's not a cluster. Position the label in the middle.
gnode.label.bounds.x = node.get_Center().get_X() - gnode.label.bounds.width / 2;
gnode.label.bounds.y = node.get_Center().get_Y() - gnode.label.bounds.height / 2;
}
}
}
// Get the edge curves, labels and arrowheads.
for (var id in msagl.edgeMap) {
var edge = msagl.edgeMap[id].medge;
var gedge: G.GEdge = msagl.edgeMap[id].gedge;
var curve = edge.get_Curve();
if (curve == null)
console.log("MSAGL warning: layout engine did not create a curve for the edge " + id);
else {
if (gedge.label != null) {
var labelbbox = this.getGRect(edge.get_Label().get_BoundingBox());
gedge.label.bounds.x = labelbbox.x;
gedge.label.bounds.y = labelbbox.y;
}
if (gedge.arrowHeadAtSource != null) {
gedge.arrowHeadAtSource.start = this.getGPoint(curve.get_Start());
gedge.arrowHeadAtSource.end = this.getGPoint(edge.get_EdgeGeometry().get_SourceArrowhead().get_TipPosition());
}
if (gedge.arrowHeadAtTarget != null) {
gedge.arrowHeadAtTarget.start = this.getGPoint(curve.get_End());
gedge.arrowHeadAtTarget.end = this.getGPoint(edge.get_EdgeGeometry().get_TargetArrowhead().get_TipPosition());
}
gedge.curve = this.getGCurve(curve);
if (gedge.curve == null)
console.log("MSAGL warning: failed to translate curve for the edge " + id);
}
}
return msagl.source;
}
/** The GGraph that this instance of MsaglWorker is working on. */
originalGraph: G.GGraph;
/** The result of the layout operation. */
finalGraph: G.GGraph;
/** Construct this with the graph you intend to run layout on. */
constructor(graph: G.GGraph) {
this.originalGraph = graph;
}
/** Performs a layout operation on the graph, and stores the result in finalGraph. */
runLayout(): void {
// Get the MSAGL shape of the GGraph.
var msagl = this.getMsagl(this.originalGraph);
// Create a cancel token and set it to false; this is not really relevant, as the cancel token can never be set anyway.
var cancelToken = new Microsoft.Msagl.Core.CancelToken.ctor();
cancelToken.set_Canceled(false);
// Run the layout operation. This can take some time.
Microsoft.Msagl.Miscellaneous.LayoutHelpers.CalculateLayout(msagl.graph, msagl.settings, cancelToken);
// Convert the MSAGL-shaped graph to a GGraph.
this.finalGraph = this.getGGraph(msagl);
}
runEdgeRouting(edgeIDs?: string[]): void {
// Reset the settings to spline if they are Sugiyama splines. Sugiyama splines cannot be used separately from layout.
if (this.originalGraph.settings.routing == G.GSettings.sugiyamaSplinesRouting)
this.originalGraph.settings.routing = G.GSettings.splinesRouting;
// Get the MSAGL shape of the GGraph.
var msagl = this.getMsagl(this.originalGraph);
// Create an edge set.
var edges: any[] = [];
if (edgeIDs == null || edgeIDs.length == 0)
for (var id in msagl.edgeMap)
edges.push(msagl.edgeMap[id].medge);
else
for (var i = 0; i < edgeIDs.length; i++) {
var msaglEdge = msagl.edgeMap[edgeIDs[i]].medge;
edges.push(msaglEdge);
}
// Run the layout operation. This can take some time.
//Microsoft.Msagl.Miscellaneous.LayoutHelpers.RouteAndLabelEdges(msagl.graph, msagl.settings, edges);
var router = new Microsoft.Msagl.Routing.SplineRouter.ctor$$GeometryGraph$$Double$$Double$$Double$$BundlingSettings(msagl.graph, msagl.settings.get_EdgeRoutingSettings().get_Padding(),
msagl.settings.get_EdgeRoutingSettings().get_PolylinePadding(),
msagl.settings.get_EdgeRoutingSettings().get_ConeAngle(),
msagl.settings.get_EdgeRoutingSettings().get_BundlingSettings());
router.Run();
var elp = new Microsoft.Msagl.Core.Layout.EdgeLabelPlacement.ctor$$GeometryGraph(msagl.graph);
elp.Run();
// Convert the MSAGL-shaped graph to a GGraph.
this.finalGraph = this.getGGraph(msagl);
}
setPolyline(edge: string, points: G.GPoint[]): SetPolylineResult {
var msagl = this.getMsagl(this.originalGraph);
var medge = msagl.edgeMap[edge].medge;
var mpoints = points.map(this.getMsaglPoint);
var mpolyline = Microsoft.Msagl.Core.Geometry.SmoothedPolyline.FromPoints(mpoints);
var mcurve = mpolyline.CreateCurve();
if (!Microsoft.Msagl.Core.Layout.Arrowheads.TrimSplineAndCalculateArrowheads$$Edge$$ICurve$$Boolean$$Boolean(medge, mcurve, true, false))
Microsoft.Msagl.Core.Layout.Arrowheads.CreateBigEnoughSpline(medge);
mcurve = medge.get_Curve();
var curve = this.getGCurve(mcurve);
var hasSourceArrowhead = medge.get_EdgeGeometry().get_SourceArrowhead() != null;
var hasTargetArrowhead = medge.get_EdgeGeometry().get_TargetArrowhead() != null;
var sourceArrowHeadStart = hasSourceArrowhead ? this.getGPoint(mcurve.get_Start()) : null;
var sourceArrowHeadEnd = hasSourceArrowhead ? this.getGPoint(medge.get_EdgeGeometry().get_SourceArrowhead().get_TipPosition()) : null;
var targetArrowHeadStart = hasTargetArrowhead ? this.getGPoint(mcurve.get_End()) : null;
var targetArrowHeadEnd = hasTargetArrowhead ? this.getGPoint(medge.get_EdgeGeometry().get_TargetArrowhead().get_TipPosition()) : null;
return { curve: curve, sourceArrowHeadStart: sourceArrowHeadStart, sourceArrowHeadEnd: sourceArrowHeadEnd, targetArrowHeadStart: targetArrowHeadStart, targetArrowHeadEnd: targetArrowHeadEnd };
}
}
/** Handles a web worker message (which is always a JSON string representing a GGraph, for which a layout operation should be performed). */
export function handleMessage(e: any): void {
var message: M.Request = e.data;
var ggraph = G.GGraph.ofJSON(message.graph);
var worker = new LayoutWorker(ggraph);
var answer: M.Response = null;
switch (message.msgtype) {
case "RunLayout":
{
try {
worker.runLayout();
answer = { msgtype: "RunLayout", graph: worker.finalGraph.getJSON() };
}
catch (e) {
if (e.message != null)
e = e.message;
console.log("error in MSAGL.RunLayout: " + JSON.stringify(e));
answer = { msgtype: "Error", error: e };
}
break;
}
case "RouteEdges":
{
var edges: string[] = (<M.Req_RouteEdges>message).edges;
try {
worker.runEdgeRouting(edges);
answer = { msgtype: "RouteEdges", graph: worker.finalGraph.getJSON(), edges: edges };
}
catch (e) {
if (e.message != null)
e = e.message;
console.log("error in MSAGL.RouteEdges: " + JSON.stringify(e));
answer = { msgtype: "Error", error: e };
}
break;
}
case "SetPolyline":
{
var edge: string = (<M.Req_SetPolyline>message).edge;
var points: G.GPoint[] = JSON.parse((<M.Req_SetPolyline>message).polyline);
var result: SetPolylineResult = null;
try {
result = worker.setPolyline(edge, points);
answer = {
msgtype: "SetPolyline", edge: edge, curve: JSON.stringify(result.curve),
sourceArrowHeadStart: result.sourceArrowHeadStart == null ? null : JSON.stringify(result.sourceArrowHeadStart),
sourceArrowHeadEnd: result.sourceArrowHeadEnd == null ? null : JSON.stringify(result.sourceArrowHeadEnd),
targetArrowHeadStart: result.targetArrowHeadStart == null ? null : JSON.stringify(result.targetArrowHeadStart),
targetArrowHeadEnd: result.targetArrowHeadEnd == null ? null : JSON.stringify(result.targetArrowHeadEnd)
};
}
catch (e) {
if (e.message != null)
e = e.message;
console.log("error in MSAGL.SetPolyline: " + JSON.stringify(e));
answer = { msgtype: "Error", error: e };
}
break;
}
}
self.postMessage(answer);
}
self.addEventListener('message', handleMessage); | the_stack |
import { DocumentEditor } from '../../src/document-editor/document-editor';
import { createElement } from '@syncfusion/ej2-base';
import { Editor, DocumentHelper } from '../../src/index';
import { TestHelper } from '../test-helper.spec';
import { LayoutViewer, PageLayoutViewer } from '../../src/index';
import { Selection } from '../../src/index';
import { EditorHistory } from '../../src/document-editor/implementation/editor-history/editor-history';
/**
* Auto Convert List Test script
*/
describe('Auto convert list using space key possible cases and level pattern arabic validation', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('Starting numerical text 1 and followed by .', () => {
console.log('Starting numerical text 1 and followed by .');
editor.openBlank();
editor.editorModule.insertText('1');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
expect(editor.selection.paragraphFormat.leftIndent).toBe(36);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
expect(editor.selection.paragraphFormat.leftIndent).toBe(36);
});
it('Starting numerical text 1 and followed by -', () => {
console.log('Starting numerical text 1 and followed by -');
editor.openBlank();
editor.editorModule.insertText('1');
editor.editorModule.insertText('-');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
expect(editor.selection.paragraphFormat.leftIndent).toBe(36);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
expect(editor.selection.paragraphFormat.leftIndent).toBe(36);
});
it('Starting numerical text 1 and followed by >', () => {
console.log('Starting numerical text 1 and followed by >');
editor.openBlank();
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText('1');
editor.editorModule.insertText('>');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text 1 and followed by )', () => {
console.log('Starting numerical text 1 and followed by )');
editor.openBlank();
editor.editorModule.insertText('1');
editor.editorModule.insertText(')');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text 1 and followed by &', () => {
console.log('Starting numerical text 1 and followed by &');
editor.openBlank();
editor.editorModule.insertText('1');
editor.editorModule.insertText('&');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('Starting numerical text 1 and followed by . and also paragraph is not empty', () => {
console.log('Starting numerical text 1 and followed by . and also paragraph is not empty');
editor.openBlank();
editor.editorModule.insertText('Adventure');
documentHelper.selection.handleHomeKey();
editor.editorModule.insertText('1');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
});
describe('Auto convert list using tab key possible cases with level pattern low letter and up letter validation', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('Starting numerical text a and followed by .', () => {
console.log('Starting numerical text a and followed by .');
editor.openBlank();
editor.editorModule.insertText('a');
editor.editorModule.insertText('.');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
expect(editor.selection.paragraphFormat.leftIndent).toBe(36);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
expect(editor.selection.paragraphFormat.leftIndent).toBe(36);
});
it('Starting numerical text a and followed by -', () => {
console.log('Starting numerical text a and followed by -');
editor.openBlank();
editor.editorModule.insertText('a');
editor.editorModule.insertText('-');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text a and followed by )', () => {
console.log('Starting numerical text a and followed by )');
editor.openBlank();
editor.editorModule.insertText('a');
editor.editorModule.insertText(')');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text a and followed by & with not possible cases', () => {
console.log('Starting numerical text a and followed by & with not possible cases');
editor.openBlank();
editor.editorModule.insertText('1');
editor.editorModule.insertText('&');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('Starting numerical text 1 and followed by . and also paragraph is not empty', () => {
console.log('Starting numerical text 1 and followed by . and also paragraph is not empty');
editor.openBlank();
editor.editorModule.insertText('Adventure');
documentHelper.selection.handleHomeKey();
editor.editorModule.insertText('1');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
});
describe('Auto convert list using space and tab key possible cases with level pattern low Roman and Up Roman validation', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('Starting numerical text i and followed by .', () => {
console.log('Starting numerical text i and followed by .');
editor.openBlank();
editor.editorModule.insertText('i');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text I and followed by -', () => {
console.log('Starting numerical text I and followed by -');
editor.openBlank();
editor.editorModule.insertText('I');
editor.editorModule.insertText('-');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text i and followed by >', () => {
console.log('Starting numerical text i and followed by >');
editor.openBlank();
editor.editorModule.insertText('i');
editor.editorModule.insertText('>');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text I and followed by )', () => {
console.log('Starting numerical text I and followed by )');
editor.openBlank();
editor.editorModule.insertText('I');
editor.editorModule.insertText(')');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text I and followed by &', () => {
console.log('Starting numerical text I and followed by &');
editor.openBlank();
editor.editorModule.insertText('I');
editor.editorModule.insertText('&');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('Starting numerical text i and followed by . and also paragraph is not empty', () => {
console.log('Starting numerical text i and followed by . and also paragraph is not empty');
editor.openBlank();
editor.editorModule.insertText('Adventure');
documentHelper.selection.handleHomeKey();
editor.editorModule.insertText('i');
editor.editorModule.insertText('.');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
});
describe('Auto convert list using space and tab key with not possible cases and also text ', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('Starting numerical text 2 and followed by .', () => {
console.log('Starting numerical text 2 and followed by .');
editor.openBlank();
editor.editorModule.insertText('2');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('Starting numerical text I and followed by ,', () => {
console.log('Starting numerical text I and followed by ,');
editor.openBlank();
editor.editorModule.insertText('I');
editor.editorModule.insertText(',');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
documentHelper.selection.handleTabKey(false, false);
documentHelper.selection.handleTabKey(false, false);
documentHelper.selection.handleTabKey(false, false);
});
it('Starting numerical text z and followed by >', () => {
console.log('Starting numerical text z and followed by >');
editor.openBlank();
editor.editorModule.insertText('z');
editor.editorModule.insertText('>');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('Starting numerical text 0 and followed by )', () => {
console.log('Starting numerical text 0 and followed by )');
editor.openBlank();
editor.editorModule.insertText('0');
editor.editorModule.insertText(')');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text i and followed by . and also paragraph is not empty', () => {
console.log('Starting numerical text i and followed by . and also paragraph is not empty');
editor.openBlank();
editor.editorModule.insertText('Adventure');
editor.editorModule.insertText('i');
editor.editorModule.insertText('.');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('Apply list to already list contain paragraph', () => {
console.log('Apply list to already list contain paragraph');
editor.openBlank();
editor.editorModule.insertText('Adventure');
editor.editorModule.applyBulletOrNumbering('%1.', 'Arabic', 'Verdana');
documentHelper.selection.handleHomeKey();
editor.editorModule.insertText('i');
editor.editorModule.insertText('.');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Apply list to already list contain paragraph', () => {
console.log('Apply list to already list contain paragraph');
editor.openBlank();
editor.editorModule.insertText('Adventure');
editor.editorModule.applyBulletOrNumbering('%1.', 'Arabic', 'Verdana');
documentHelper.selection.handleEndKey();
editor.editorModule.onEnter();
editor.editorModule.onEnter();
editor.editorModule.insertText('I');
editor.editorModule.insertText('.');
documentHelper.selection.handleTabKey(false, false);
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Previous span is field', () => {
console.log('Previous span is field');
editor.openBlank();
editor.editorModule.insertText('www.google.com');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText('I');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
});
describe('Auto convert list using space key possible cases with level pattern as Leading zero', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('Starting numerical text 01 and followed by .', () => {
console.log('Starting numerical text 01 and followed by .');
editor.openBlank();
editor.editorModule.insertText('01');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
});
it('Starting numerical text 01 and followed by -', () => {
console.log('Starting numerical text 01 and followed by -');
editor.openBlank();
editor.editorModule.insertText('01');
editor.editorModule.insertText('-');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text 01 and followed by >', () => {
console.log('Starting numerical text 01 and followed by >');
editor.openBlank();
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText('01');
editor.editorModule.insertText('>');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text 00 and followed by )', () => {
console.log('Starting numerical text 00 and followed by )');
editor.openBlank();
editor.editorModule.insertText('00');
editor.editorModule.insertText(')');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('Starting numerical text 01 and followed by &', () => {
console.log('Starting numerical text 01 and followed by &');
editor.openBlank();
editor.editorModule.insertText('01');
editor.editorModule.insertText('&');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('Starting numerical text 01 and followed by . and also paragraph is not empty', () => {
console.log('Starting numerical text 01 and followed by . and also paragraph is not empty');
editor.openBlank();
editor.editorModule.insertText('Adventure');
documentHelper.selection.handleHomeKey();
editor.editorModule.insertText('01');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
});
let imageString: string = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAIAAAADnC86AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADQSURBVFhH7ZbRDYQgDIYZ5UZhFEdxlBuFUUhY4N7vwWtTURJz5tem8GAbTYS0/eGjWsN7hJVSAuku3c2FuyF31BvqBNu90/mLmnSRjKDbMZULt2csz/kV8hRbVjSkSZkxRC0yKcbl+6FLhttSDIV5W6vYnKeZVWkR1WyFGbhIHrAbCzPhEcL1XCvqptYMd7xXExUXM4+pT3ENe53OP5yGqJ8kDDZGpIld6E730uFR/uuDs1J6OmolQDzcUeOslJ6OWgkQD3fUOCulJ6Ome4j9AGEu0k90WN54AAAAAElFTkSuQmCC';
describe('Different left indent with paragraph contains only space , tab and combination of both validation - 1', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('Multiple tab followed by text 1 and followed by )', () => {
console.log('Multiple tab followed by text 1 and followed by )');
editor.openBlank();
editor.documentHelper.owner.editorModule.handleTextInput('\t');
editor.documentHelper.owner.editorModule.handleTextInput('\t');
editor.documentHelper.owner.editorModule.handleTextInput('\t');
editor.editorModule.insertText('1');
editor.editorModule.insertText(')');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('combination of space and tab followed by text A and followed by >', () => {
console.log('combination of space and tab followed by text A and followed by >');
editor.openBlank();
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.documentHelper.owner.editorModule.handleTextInput('\t');
editor.editorModule.insertText('A');
editor.editorModule.insertText('>');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('get List Level Pattern branch validation', () => {
console.log('get List Level Pattern branch validation');
editor.openBlank();
let value = (editor.editorModule as any).getListLevelPattern('2.');
expect(value).toBe('None');
});
});
describe('Different left indent with paragraph contains only space , tab and combination of both validation - 1', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('combination of tab and space followed by text I and followed by >', () => {
console.log('combination of tab and space followed by text I and followed by >');
editor.openBlank();
editor.documentHelper.owner.editorModule.handleTextInput('\t');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText('I');
editor.editorModule.insertText('>');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).not.toBe(-1);
});
it('combination of text, tab and space followed by text I and followed by >', () => {
console.log('combination of text, tab and space followed by text I and followed by >');
editor.openBlank();
editor.editorModule.insertText('sample');
editor.documentHelper.owner.editorModule.handleTextInput('\t');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText(' ');
editor.editorModule.insertText('I');
editor.editorModule.insertText('>');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.undo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
editor.editorHistory.redo();
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('span is image validation', () => {
console.log('span is image validation');
editor.openBlank();
editor.editor.insertImage(imageString, 100, 100);
documentHelper.selection.handleRightKey();
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
it('span is image validation and previous span is image', () => {
console.log('span is image validation and previous span is image');
editor.openBlank();
editor.editor.insertImage(imageString, 100, 100);
documentHelper.selection.handleRightKey();
editor.editorModule.insertText('1');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(-1);
});
});
// describe('Numbering apply validation in different scenario', () => {
// let editor: DocumentEditor;
// let documentHelper: DocumentHelper;
// beforeAll((): void => {
// let ele: HTMLElement = createElement('div', { id: 'container' });
// document.body.appendChild(ele);
// DocumentEditor.Inject(Editor, Selection, EditorHistory);
// editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
// editor.acceptTab = true;
// (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
// (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
// (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
// (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
// editor.appendTo('#container');
// documentHelper = editor.documentHelper;
// });
// afterAll((done): void => {
// documentHelper.destroy();
// documentHelper = undefined;
// editor.destroy();
// document.body.removeChild(document.getElementById('container'));
// editor = undefined;
// setTimeout(function () {
// document.body.innerHTML = '';
// done();
// }, 1000);
// });
// it('Numbering list with previous Paragrph contains list and next paragraph is table and next paragraph is empty', () => {
// console.log('Numbering list with previous Paragrph contains list and next paragraph is table and next paragraph is empty');
// editor.openBlank();
// editor.editorModule.insertText('1');
// editor.editorModule.insertText('.');
// editor.editorModule.insertText(' ');
// editor.editorModule.insertText('Adventure');
// let listId = editor.selection.paragraphFormat.listId;
// editor.editorModule.onEnter();
// editor.editorModule.onEnter();
// editor.editor.insertTable(2, 2);
// editor.selection.moveDown();
// editor.selection.moveDown();
// editor.editor.applyNumbering('%1.', 'Arabic');
// expect(editor.selection.paragraphFormat.listId).not.toBe(listId);
// });
// it('Numbering list with previous Paragrph contains list and next paragraph is table and next paragraph is not empty', () => {
// console.log('Numbering list with previous Paragrph contains list and next paragraph is table and next paragraph is not empty');
// editor.openBlank();
// editor.editorModule.insertText('1');
// editor.editorModule.insertText('.');
// editor.editorModule.insertText(' ');
// editor.editorModule.insertText('Adventure');
// let listId = editor.selection.paragraphFormat.listId;
// editor.editorModule.onEnter();
// editor.editorModule.onEnter();
// editor.editorModule.insertText('Adventure');
// editor.editorModule.onEnter();
// editor.editor.applyNumbering('%1.', 'Arabic');
// expect(editor.selection.paragraphFormat.listId).not.toBe(listId);
// });
// it('Numbering list with previous Paragrph contains list and next paragraph is table and next paragraph is not empty', () => {
// console.log('Numbering list with previous Paragrph contains list and next paragraph is table and next paragraph is not empty');
// editor.openBlank();
// editor.editorModule.insertText('1');
// editor.editorModule.insertText('.');
// editor.editorModule.insertText(' ');
// editor.editorModule.insertText('Adventure');
// let listId = editor.selection.paragraphFormat.listId;
// editor.editorModule.onEnter();
// editor.editorModule.onEnter();
// editor.editor.applyNumbering('%1.', 'UpLetter');
// expect(editor.selection.paragraphFormat.listId).not.toBe(listId);
// });
// it('Numbering list with previous Paragrph contains list and next paragraph is table and next paragraph is not empty', () => {
// console.log('Numbering list with previous Paragrph contains list and next paragraph is table and next paragraph is not empty');
// editor.openBlank();
// editor.editorModule.insertText('1');
// editor.editorModule.insertText('.');
// editor.editorModule.insertText(' ');
// editor.editorModule.insertText('Adventure');
// let listId = editor.selection.paragraphFormat.listId;
// editor.editorModule.onEnter();
// editor.editorModule.onEnter();
// editor.editorModule.onEnter();
// editor.editorModule.onEnter();
// editor.editorModule.onEnter();
// editor.editor.applyNumbering('%1.', 'UpLetter');
// expect(editor.selection.paragraphFormat.listId).not.toBe(listId);
// });
// });
describe('Bullet list Apply validation', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
// it('Bullet List validation', () => {
// console.log('Bullet List validation');
// editor.openBlank();
// editor.editorModule.insertText('1');
// editor.editorModule.insertText('.');
// editor.editorModule.insertText(' ');
// editor.editorModule.insertText('Adventure');
// let listId = editor.selection.paragraphFormat.listId;
// editor.editorModule.onEnter();
// editor.editorModule.onEnter();
// editor.editor.applyBullet('\uf0b7', 'Symbol');
// expect(editor.selection.paragraphFormat.listId).not.toBe(listId);
// editor.editor.applyBullet('\uf0b7', 'Windings');
// });
it('Bullet List validation with back ward selection', () => {
console.log('Bullet List validation with back ward selection');
editor.openBlank();
editor.editorModule.insertText('1');
editor.editorModule.insertText('.');
editor.editorModule.insertText(' ');
editor.editorModule.insertText('Adventure');
let listId = editor.selection.paragraphFormat.listId;
editor.selection.extendToLineStart();
editor.editor.applyBullet('\uf0b7', 'Symbol');
expect(editor.selection.paragraphFormat.listId).not.toBe(listId);
});
// it('Applying same list validation', () => {
// console.log('Applying same list validation');
// editor.openBlank();
// editor.editor.applyNumbering('%1.', 'Arabic');
// expect(editor.selection.paragraphFormat.listLevelNumber).toBe(0);
// editor.editor.applyNumbering('%1.', 'Arabic');
// });
describe('Asterisk and hyphen Apply validation', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('Asterisk List validation', () => {
console.log('Asterisk List validation');
editor.openBlank();
editor.editorModule.insertText('*');
editor.editorModule.insertText(' ');
expect(editor.selection.paragraphFormat.listId).toBe(0);
});
// it('Hyphen list validation', () => {
// console.log('Hyphen list validation');
// editor.openBlank();
// editor.editorModule.insertText('-');
// editor.editorModule.insertText(' ');
// expect(editor.selection.paragraphFormat.listId).toBe(1);
// });
});
});
describe('Table relayouting validation', () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 1000);
});
it('Table with 30 column editing', () => {
console.log('Table with 30 column editing');
editor.editorModule.insertTable(2, 30);
for (let i: number = 0; i < 20; i++) {
editor.editorModule.insertText('efefefefef');
}
expect(editor.documentHelper.pages.length).toBeGreaterThan(1);
});
it('undo changes', () => {
console.log('undo changes');
for (let i: number = 0; i < 20; i++) {
editor.editorHistory.undo();
}
expect(editor.documentHelper.pages.length).toBe(1);
});
it('redo changes', () => {
console.log('redo changes');
for (let i: number = 0; i < 20; i++) {
editor.editorHistory.redo();
}
expect(editor.documentHelper.pages.length).toBeGreaterThan(1);
});
});
describe("Press enter key", () => {
let editor: DocumentEditor;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, isReadOnly: false, enableSelection: true, enableEditorHistory: true });
editor.acceptTab = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterAll((done): void => {
documentHelper.destroy();
documentHelper = undefined;
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
setTimeout(function () {
document.body.innerHTML = '';
done();
}, 500);
});
it("Inside nested table", () => {
editor.editor.insertTable(2, 2);
editor.editor.onEnter();
editor.editor.insertTable(2, 2);
editor.selection.moveUp();
editor.selection.characterFormat.fontSize = 96;
for (let i = 0; i < 7; i++) {
editor.editor.onEnter();
}
editor.selection.moveDown();
expect(function () { editor.editor.onEnter() }).not.toThrowError();
});
}); | the_stack |
import { Checkpoint, CheckpointStore, PartitionOwnership } from "@azure/event-hubs";
import { TableClient, TableInsertEntityHeaders, odata } from "@azure/data-tables";
import { logErrorStackTrace, logger } from "./log";
/**
*
* Checks if the value contains a `Timestamp` field of type `string`.
*/
function _hasTimestamp<T extends TableInsertEntityHeaders>(
value: T
): value is T & { Timestamp: string } {
return typeof (value as any).Timestamp === "string";
}
/**
* A checkpoint entity of type CheckpointEntity to be stored in the table
* @internal
*
*/
export interface CheckpointEntity {
/**
* The partitionKey is a composite key assembled in the following format:
* `${fullyQualifiedNamespace} ${eventHubName} ${consumerGroup} Checkpoint`
*/
partitionKey: string;
/**
* The rowKey is the partitionId
*
*/
rowKey: string;
sequencenumber: string;
offset: string;
}
/**
* An ownership entity of type PartitionOwnership to be stored in the table
* @internal
*/
export interface PartitionOwnershipEntity {
/**
* The partitionKey is a composite key assembled in the following format:
* `${fullyQualifiedNamespace} ${eventHubName} ${consumerGroup} Ownership`
*/
partitionKey: string;
/**
* The rowKey is the partitionId
*
*/
rowKey: string;
ownerid: string;
}
/**
* An implementation of CheckpointStore that uses Azure Table Storage to persist checkpoint data.
*/
export class TableCheckpointStore implements CheckpointStore {
private _tableClient: TableClient;
constructor(tableClient: TableClient) {
this._tableClient = tableClient;
}
/**
* Get the list of all existing partition ownership from the underlying data store. May return empty
* results if there are is no existing ownership information.
* Partition Ownership contains the information on which `EventHubConsumerClient` subscribe call is currently processing the partition.
*
* @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to
* <yournamespace>.servicebus.windows.net.
* @param eventHubName - The event hub name.
* @param consumerGroup - The consumer group name.
* @param options - A set of options that can be specified to influence the behavior of this method.
* - `abortSignal`: A signal used to request operation cancellation.
* - `tracingOptions`: Options for configuring tracing.
* @returns Partition ownership details of all the partitions that have had an owner.
*/
async listOwnership(
fullyQualifiedNamespace: string,
eventHubName: string,
consumerGroup: string
): Promise<PartitionOwnership[]> {
const partitionKey = `${fullyQualifiedNamespace} ${eventHubName} ${consumerGroup} Ownership`;
const partitionOwnershipArray: PartitionOwnership[] = [];
const entitiesIter = this._tableClient.listEntities<PartitionOwnershipEntity>({
queryOptions: { filter: odata`PartitionKey eq ${partitionKey}` }
});
try {
for await (const entity of entitiesIter) {
if (!entity.timestamp) {
throw new Error(
`Unable to retrieve timestamp from partitionKey "${partitionKey}", rowKey "${entity.rowKey}"`
);
}
const partitionOwnership: PartitionOwnership = {
fullyQualifiedNamespace,
eventHubName,
consumerGroup,
ownerId: entity.ownerid,
partitionId: entity.rowKey,
lastModifiedTimeInMs: new Date(entity.timestamp).getTime(),
etag: entity.etag
};
partitionOwnershipArray.push(partitionOwnership);
}
return partitionOwnershipArray;
} catch (err) {
logger.warning(`Error occurred while fetching the list of entities`, err.message);
logErrorStackTrace(err);
if (err?.name === "AbortError") throw err;
throw new Error(`Error occurred while fetching the list of entities. \n${err}`);
}
}
/**
* Claim ownership of a list of partitions. This will return the list of partitions that were
* successfully claimed.
*
* @param partitionOwnership - The list of partition ownership this instance is claiming to own.
* @param options - A set of options that can be specified to influence the behavior of this method.
* - `abortSignal`: A signal used to request operation cancellation.
* - `tracingOptions`: Options for configuring tracing.
* @returns A list partitions this instance successfully claimed ownership.
*/
async claimOwnership(partitionOwnership: PartitionOwnership[]): Promise<PartitionOwnership[]> {
const partitionOwnershipArray: PartitionOwnership[] = [];
for (const ownership of partitionOwnership) {
const updatedOwnership = { ...ownership };
const partitionKey = `${ownership.fullyQualifiedNamespace} ${ownership.eventHubName} ${ownership.consumerGroup} Ownership`;
const ownershipEntity: PartitionOwnershipEntity = {
partitionKey: partitionKey,
rowKey: ownership.partitionId,
ownerid: ownership.ownerId
};
// When we have an etag, we know the entity existed.
// If we encounter an error we should fail.
try {
if (ownership.etag) {
const updatedMetadata = await this._tableClient.updateEntity(ownershipEntity, "Replace", {
etag: ownership.etag
});
const entityRetrieved = await this._tableClient.getEntity(
ownershipEntity.partitionKey,
ownershipEntity.rowKey
);
if (!entityRetrieved.timestamp) {
throw new Error(
`Unable to retrieve timestamp from partitionKey "${partitionKey}", rowKey "${entityRetrieved.rowKey}"`
);
}
updatedOwnership.lastModifiedTimeInMs = new Date(entityRetrieved.timestamp).getTime();
updatedOwnership.etag = updatedMetadata.etag;
partitionOwnershipArray.push(updatedOwnership);
logger.info(
`[${ownership.ownerId}] Claimed ownership successfully for partition: ${ownership.partitionId}`,
`LastModifiedTime: ${ownership.lastModifiedTimeInMs}, ETag: ${ownership.etag}`
);
} else {
const newOwnershipMetadata = await this._tableClient.createEntity(ownershipEntity, {
requestOptions: {
customHeaders: {
Prefer: "return-content"
}
}
});
if (!_hasTimestamp(newOwnershipMetadata)) {
throw new Error(
`Unable to retrieve timestamp from partitionKey "${partitionKey}", rowKey "${ownershipEntity.rowKey}"`
);
}
updatedOwnership.lastModifiedTimeInMs = new Date(
newOwnershipMetadata.Timestamp
).getTime();
updatedOwnership.etag = newOwnershipMetadata.etag;
partitionOwnershipArray.push(updatedOwnership);
}
} catch (err) {
if (err.statusCode === 412) {
// etag failures (precondition not met) aren't fatal errors. They happen
// as multiple consumers attempt to claim the same partition (first one wins)
// and losers get this error.
logger.verbose(
`[${ownership.ownerId}] Did not claim partition ${ownership.partitionId}. Another processor has already claimed it.`
);
continue;
}
logger.warning(
`Error occurred while claiming ownership for partition: ${ownership.partitionId}`,
err.message
);
logErrorStackTrace(err);
}
}
return partitionOwnershipArray;
}
/**
* Lists all the checkpoints in a data store for a given namespace, eventhub and consumer group.
*
* @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to
* <yournamespace>.servicebus.windows.net.
* @param eventHubName - The event hub name.
* @param consumerGroup - The consumer group name.
* @param options - A set of options that can be specified to influence the behavior of this method.
* - `abortSignal`: A signal used to request operation cancellation.
* - `tracingOptions`: Options for configuring tracing.
*/
async listCheckpoints(
fullyQualifiedNamespace: string,
eventHubName: string,
consumerGroup: string
): Promise<Checkpoint[]> {
const partitionKey = `${fullyQualifiedNamespace} ${eventHubName} ${consumerGroup} Checkpoint`;
const checkpoints: Checkpoint[] = [];
const entitiesIter = this._tableClient.listEntities<CheckpointEntity>({
queryOptions: { filter: odata`PartitionKey eq ${partitionKey}` }
});
for await (const entity of entitiesIter) {
checkpoints.push({
consumerGroup,
eventHubName,
fullyQualifiedNamespace,
partitionId: entity.rowKey,
offset: parseInt(entity.offset, 10),
sequenceNumber: parseInt(entity.sequencenumber, 10)
});
}
return checkpoints;
}
/**
* Updates the checkpoint in the data store for a partition.
*
* @param checkpoint - The checkpoint.
* @param options - A set of options that can be specified to influence the behavior of this method.
* - `abortSignal`: A signal used to request operation cancellation.
* - `tracingOptions`: Options for configuring tracing.
* @returns A promise that resolves when the checkpoint has been updated.
*/
async updateCheckpoint(checkpoint: Checkpoint): Promise<void> {
const partitionKey = `${checkpoint.fullyQualifiedNamespace} ${checkpoint.eventHubName} ${checkpoint.consumerGroup} Checkpoint`;
const checkpointEntity: CheckpointEntity = {
partitionKey: partitionKey,
rowKey: checkpoint.partitionId,
sequencenumber: checkpoint.sequenceNumber.toString(),
offset: checkpoint.offset.toString()
};
try {
await this._tableClient.upsertEntity(checkpointEntity);
logger.verbose(`Updated checkpoint successfully for partition: ${checkpoint.partitionId}`);
return;
} catch (err) {
logger.verbose(
`Error occurred while upating the checkpoint for partition: ${checkpoint.partitionId}.`,
err.message
);
throw err;
}
}
} | the_stack |
import assert from 'assert';
import retry from 'async-retry';
import { Logger, PlatformAccessory, Service } from 'homebridge';
import { isNull, isUndefined } from 'lodash';
import { Device } from 'zigbee-herdsman/dist/controller/model';
import { HAP } from '../index';
import { ZigbeeNTHomebridgePlatform } from '../platform';
import {
DEFAULT_POLL_INTERVAL,
isDeviceRouter,
MAX_POLL_INTERVAL,
MIN_POLL_INTERVAL,
} from '../utils/device';
import { HSBType } from '../utils/hsb-type';
import { ButtonAction, DeviceState, ZigBeeDefinition, ZigBeeEntity } from '../zigbee/types';
import { ZigBeeClient } from '../zigbee/zig-bee-client';
import { ConfigurableAccessory } from './configurable-accessory';
import { doWithButtonAction } from './utils';
export interface ZigBeeAccessoryCtor {
new (
platform: ZigbeeNTHomebridgePlatform,
accessory: PlatformAccessory,
client: ZigBeeClient,
device: Device
): ZigBeeAccessory;
}
export type ZigBeeAccessoryFactory = (
platform: ZigbeeNTHomebridgePlatform,
accessory: PlatformAccessory,
client: ZigBeeClient,
device: Device
) => ConfigurableAccessory;
const MAX_PING_ATTEMPTS = 1;
const MAX_NAME_LENGTH = 64;
function isValidValue(v: any) {
return !isNull(v) && !isUndefined(v);
}
export abstract class ZigBeeAccessory {
public readonly ieeeAddr: string;
protected platform: ZigbeeNTHomebridgePlatform;
protected log: Logger;
protected accessory: PlatformAccessory;
protected readonly client: ZigBeeClient;
protected state: DeviceState;
protected readonly entity: ZigBeeEntity;
private missedPing = 0;
private isConfiguring = false;
private interval: number;
private mappedServices: Service[];
public isOnline: boolean;
constructor(
platform: ZigbeeNTHomebridgePlatform,
accessory: PlatformAccessory,
client: ZigBeeClient,
device: Device
) {
this.client = client;
this.ieeeAddr = device.ieeeAddr;
this.platform = platform;
this.log = this.platform.log;
this.state = {};
this.accessory = accessory;
this.accessory.context = device;
this.entity = this.client.resolveEntity(device);
this.isOnline = true;
assert(this.entity !== null, 'ZigBee Entity resolution failed');
const Characteristic = platform.Characteristic;
this.accessory
.getService(this.platform.Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, device.manufacturerName)
.setCharacteristic(Characteristic.Model, device.modelID)
.setCharacteristic(Characteristic.SerialNumber, device.ieeeAddr)
.setCharacteristic(Characteristic.SoftwareRevision, `${device.softwareBuildID}`)
.setCharacteristic(Characteristic.HardwareRevision, `${device.hardwareVersion}`)
.setCharacteristic(Characteristic.Name, this.friendlyName);
this.accessory.on('identify', () => this.handleAccessoryIdentify());
}
/**
* Perform initialization of the accessory. By default is creates services exposed by the
* accessory by invoking {@link ZigBeeAccessory.getAvailableServices}
*/
public async initialize(): Promise<void> {
this.mappedServices = this.getAvailableServices();
try {
this.onDeviceMount();
} catch (e) {
this.log.error(`Error mounting device ${this.friendlyName}: ${e.message}`);
}
}
handleAccessoryIdentify(): void {}
public get zigBeeDeviceDescriptor(): Device {
return this.accessory.context as Device;
}
public get zigBeeDefinition(): ZigBeeDefinition {
return this.entity.definition;
}
public get friendlyName(): string {
const ieeeAddr = this.zigBeeDeviceDescriptor.ieeeAddr;
return (
this.entity?.settings?.friendlyName ||
`${this.zigBeeDefinition.description.substr(
0,
MAX_NAME_LENGTH - 1 - ieeeAddr.length
)}-${ieeeAddr}`
);
}
public abstract getAvailableServices(): Service[];
public onDeviceMount(): void {
this.log.info(`Mounting device ${this.friendlyName}...`);
if (
isDeviceRouter(this.zigBeeDeviceDescriptor) &&
this.platform.config.disableRoutingPolling !== true
) {
this.isOnline = false; // wait until we can ping the device
this.log.info(`Device ${this.friendlyName} is a router, install ping`);
this.interval = this.getPollingInterval();
this.ping().then(() => this.log.debug(`Ping received from ${this.friendlyName}`));
} else {
this.configureDevice()
.then(() => this.log.debug(`${this.friendlyName} successfully configured`))
.catch((e) => this.log.error(e.message));
}
}
private getPollingInterval(): number {
let interval = this.platform.config.routerPollingInterval * 1000 || DEFAULT_POLL_INTERVAL;
if (this.interval < MIN_POLL_INTERVAL || this.interval > MAX_POLL_INTERVAL) {
interval = DEFAULT_POLL_INTERVAL;
}
return interval;
}
public async ping(): Promise<void> {
try {
await this.zigBeeDeviceDescriptor.ping();
await this.configureDevice();
this.zigBeeDeviceDescriptor.save();
this.missedPing = 0;
this.isOnline = true;
setTimeout(() => this.ping(), this.interval);
} catch (e) {
this.log.warn(`No response from ${this.entity.settings.friendlyName}. Is it online?`);
this.missedPing++;
if (this.missedPing > MAX_PING_ATTEMPTS) {
this.log.error(
`Device is not responding after ${MAX_PING_ATTEMPTS} ping, sending it offline...`
);
this.isOnline = false;
this.zigBeeDeviceDescriptor.save();
} else {
setTimeout(() => this.ping(), this.interval);
}
}
}
public async configureDevice(): Promise<boolean> {
if (this.shouldConfigure()) {
this.isConfiguring = true;
const coordinatorEndpoint = this.client.getCoordinator().getEndpoint(1);
return await retry<boolean>(
async (bail: (e: Error) => void, attempt: number) => {
await this.zigBeeDefinition.configure(this.zigBeeDeviceDescriptor, coordinatorEndpoint);
this.isConfigured = true;
this.zigBeeDeviceDescriptor.save();
this.log.info(
`Device ${this.friendlyName} successfully configured on attempt ${attempt}!`
);
return true;
},
{
retries: MAX_PING_ATTEMPTS,
onRetry: (e: Error, attempt: number) => {
if (attempt === MAX_PING_ATTEMPTS) {
this.isConfiguring = false;
this.isConfigured = false;
this.zigBeeDeviceDescriptor.save();
}
},
}
);
}
return false;
}
private get isConfigured() {
return !!this.zigBeeDefinition.meta?.configured;
}
private set isConfigured(val: boolean) {
if (val === true) {
if (!this.zigBeeDefinition.meta) {
this.zigBeeDefinition.meta = {};
}
if (this.zigBeeDefinition.meta.configureKey) {
this.zigBeeDefinition.meta.configured = this.zigBeeDefinition.meta.configureKey;
} else {
this.zigBeeDefinition.meta.configured = 1;
}
} else {
delete this.zigBeeDefinition.meta?.configured;
}
}
private shouldConfigure() {
return (
!!this.zigBeeDefinition.configure && // it must have the configure function defined
!this.isConfigured &&
!this.zigBeeDefinition.interviewing &&
!this.isConfiguring
);
}
public internalUpdate(state: DeviceState): void {
try {
this.log.debug(`Updating state of device ${this.friendlyName} with `, state);
this.state = Object.assign(this.state, { ...state });
this.log.debug(`Updated state for device ${this.friendlyName} is now `, this.state);
this.configureDevice().then((configured) =>
configured ? this.log.debug(`${this.friendlyName} configured after state update`) : null
);
this.update({ ...this.state });
delete this.state.action;
} catch (e) {
this.log.error(e.message, e);
}
}
/**
* This function handles most of the characteristics update you need.
* Override this function only if you need some specific update feature for your accessory
* @param state DeviceState Current device state
*/
public update(state: DeviceState): void {
const Service = this.platform.Service;
const Characteristic = this.platform.Characteristic;
const serviceMap = this.mappedServices.reduce((map, service) => {
map.set(service.UUID, service);
return map;
}, new Map());
[...serviceMap.values()].forEach((service) => {
this.log.debug(
`Updating service ${service.UUID} for device ${this.friendlyName} with state`,
state
);
if (this.supports('battery_low')) {
service.updateCharacteristic(
Characteristic.StatusLowBattery,
state.battery_low
? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW
: Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL
);
}
if (this.supports('tamper')) {
service.updateCharacteristic(
Characteristic.StatusTampered,
state.tamper
? Characteristic.StatusTampered.TAMPERED
: Characteristic.StatusTampered.NOT_TAMPERED
);
}
switch (service.UUID) {
case Service.Battery.UUID:
case Service.BatteryService.UUID:
if (isValidValue(state.battery)) {
service.updateCharacteristic(Characteristic.BatteryLevel, state.battery || 0);
service.updateCharacteristic(
Characteristic.StatusLowBattery,
state.battery && state.battery < 10
);
}
break;
case Service.ContactSensor.UUID:
service.updateCharacteristic(
Characteristic.ContactSensorState,
state.contact
? Characteristic.ContactSensorState.CONTACT_DETECTED
: Characteristic.ContactSensorState.CONTACT_NOT_DETECTED
);
break;
case Service.LeakSensor.UUID:
if (this.supports('water_leak')) {
service
.getCharacteristic(Characteristic.ContactSensorState)
.setValue(
state.water_leak === true
? Characteristic.LeakDetected.LEAK_DETECTED
: Characteristic.LeakDetected.LEAK_NOT_DETECTED
);
}
if (this.supports('gas')) {
service
.getCharacteristic(Characteristic.ContactSensorState)
.setValue(
state.gas === true
? Characteristic.LeakDetected.LEAK_DETECTED
: Characteristic.LeakDetected.LEAK_NOT_DETECTED
);
}
break;
case Service.Switch.UUID:
if (isValidValue(state.state)) {
service.updateCharacteristic(this.platform.Characteristic.On, state.state === 'ON');
}
break;
case Service.Lightbulb.UUID:
if (isValidValue(state.state)) {
service.updateCharacteristic(this.platform.Characteristic.On, state.state === 'ON');
}
if (this.supports('brightness')) {
if (isValidValue(state.brightness_percent)) {
service.updateCharacteristic(
this.platform.Characteristic.Brightness,
state.brightness_percent
);
} else if (isValidValue(state.brightness)) {
service.updateCharacteristic(
this.platform.Characteristic.Brightness,
Math.round(Number(state.brightness) / 2.55)
);
}
}
if (this.supports('color_temp') && isValidValue(state.color_temp)) {
service.updateCharacteristic(
this.platform.Characteristic.ColorTemperature,
state.color_temp
);
}
if (this.supports('color_hs') && isValidValue(state.color?.s)) {
if (isValidValue(state.color?.s)) {
service.updateCharacteristic(this.platform.Characteristic.Saturation, state.color.s);
}
if (isValidValue(state.color?.hue)) {
service.updateCharacteristic(this.platform.Characteristic.Hue, state.color.hue);
}
} else if (this.supports('color_xy') && isValidValue(state.color?.x)) {
const hsbType = HSBType.fromXY(state.color.x, state.color.y);
state.color.hue = hsbType.hue;
state.color.s = hsbType.saturation;
service.updateCharacteristic(Characteristic.Hue, state.color.hue);
service.updateCharacteristic(Characteristic.Saturation, state.color.s);
}
break;
case Service.LightSensor.UUID:
if (this.supports('illuminance_lux') && isValidValue(state.illuminance_lux)) {
service.updateCharacteristic(
Characteristic.CurrentAmbientLightLevel,
state.illuminance_lux
);
}
if (this.supports('illuminance') && isValidValue(state.illuminance)) {
service.updateCharacteristic(
Characteristic.CurrentAmbientLightLevel,
state.illuminance
);
}
break;
case Service.MotionSensor.UUID:
service.updateCharacteristic(
this.platform.Characteristic.MotionDetected,
state.occupancy === true
);
break;
case Service.Outlet.UUID:
if (isValidValue(state.state)) {
service.updateCharacteristic(this.platform.Characteristic.On, state.state === 'ON');
}
if (this.supports('power') || this.supports('voltage') || this.supports('energy')) {
service.updateCharacteristic(
this.platform.Characteristic.InUse,
state.power > 0 || state.voltage > 0 || state.current > 0
);
if (this.supports('power') && typeof state.power === 'number') {
service.updateCharacteristic(HAP.CurrentPowerConsumption, state.power);
}
if (this.supports('voltage') && typeof state.voltage === 'number') {
service.updateCharacteristic(HAP.CurrentVoltage, state.voltage);
}
if (this.supports('energy') && typeof state.current === 'number') {
service.updateCharacteristic(HAP.CurrentConsumption, state.current);
}
}
break;
case Service.TemperatureSensor.UUID:
if (isValidValue(state.temperature)) {
service.updateCharacteristic(
this.platform.Characteristic.CurrentTemperature,
state.temperature
);
}
break;
case Service.HumiditySensor.UUID:
if (isValidValue(state.humidity)) {
service.updateCharacteristic(
this.platform.Characteristic.CurrentRelativeHumidity,
state.humidity
);
}
break;
case Service.StatelessProgrammableSwitch.UUID:
this.handleButtonAction(state.action, service);
break;
}
});
}
private handleButtonAction(action: ButtonAction, service: Service) {
const ProgrammableSwitchEvent = this.platform.Characteristic.ProgrammableSwitchEvent;
doWithButtonAction(action, (event: number) => {
service.getCharacteristic(ProgrammableSwitchEvent).setValue(event);
});
}
public supports(property: string): boolean {
return (
this.entity.definition.exposes?.find((capability) => capability.name === property) !== null
);
}
} | the_stack |
import { defaultMemoize } from "reselect";
import {
BoundingBox,
Entity,
isSentence,
isSymbol,
isTerm,
Relationship,
Sentence,
Symbol,
Term,
} from "../api/types";
import { Entities } from "../state";
import { Rectangle } from "../types/ui";
export function selectedEntityType(
selectedEntityId: string | null,
entities: Entities | null
): string | null {
if (
selectedEntityId === null ||
entities === null ||
entities.byId[selectedEntityId] === undefined
) {
return null;
}
return entities.byId[selectedEntityId].type;
}
/**
* Return all sentences containing a list of entities.
*/
export function sentences(entityIds: string[], entities: Entities): Sentence[] {
return entityIds
.map((id) => entities.byId[id])
.filter((e) => e !== undefined)
.filter((e) => isSymbol(e) || isTerm(e))
.map((e) => e as Term | Symbol)
.map((s) => s.relationships.sentence.id)
.filter((sentId) => sentId !== null)
.map((sentId) => entities.byId[sentId as string])
.filter((sent) => sent !== undefined)
.filter(isSentence);
}
/*
* Highlight sentences that contain definition information.
*/
export function definingSentences(
entityIds: string[],
entities: Entities
): Sentence[] {
const sentenceIds = [];
/*
* Accumulate defining sentences for symbols.
*/
sentenceIds.push(
...entityIds
.map((id) => entities.byId[id])
.filter((e) => e !== undefined)
.filter(isSymbol)
.map((e) => [
...e.relationships.definition_sentences.map((r) => r.id),
...e.relationships.nickname_sentences.map((r) => r.id),
...e.relationships.defining_formula_equations.map((r) => r.id),
])
.flat()
.filter((id) => id !== null)
);
/*
* Accumulate defining sentences for terms.
*/
sentenceIds.push(
...entityIds
.map((id) => entities.byId[id])
.filter((e) => e !== undefined)
.filter(isTerm)
.map((e) => [...e.relationships.definition_sentences.map((r) => r.id)])
.flat()
.filter((id) => id !== null)
);
return sentenceIds
.map((id) => entities.byId[id as string])
.filter((e) => e !== undefined)
.filter(isSentence);
}
/**
* If page is not specified, an outer bounding boxes is returned for the all bounding boxes
* for the symbol on the same page as the first bounding box.
*/
export function outerBoundingBox(
entity: Entity,
page?: number
): Rectangle | null {
if (entity.attributes.bounding_boxes.length === 0) {
return null;
}
page = entity.attributes.bounding_boxes[0].page;
const boxes = entity.attributes.bounding_boxes.filter((b) => b.page === page);
if (boxes.length === 0) {
return null;
}
const left = Math.min(...boxes.map((b) => b.left));
const top = Math.min(...boxes.map((b) => b.top));
const right = Math.max(...boxes.map((b) => b.left + b.width));
const bottom = Math.max(...boxes.map((b) => b.top + b.height));
return {
left,
top,
width: right - left,
height: bottom - top,
};
}
/**
* Filter a list of entity IDs to just those in a specified page.
*/
export function entityIdsInPage(
entityIds: string[],
entities: Entities | null,
page: number
) {
if (entities === null) {
return [];
}
return entityIds
.map((e) => entities.byId[e])
.filter((e) => e !== undefined)
.filter((e) => e.attributes.bounding_boxes.some((b) => b.page === page))
.map((e) => e.id);
}
function areBoxesVerticallyAligned(box1: BoundingBox, box2: BoundingBox) {
const box1Bottom = box1.top + box1.height;
const box2Bottom = box2.top + box2.height;
return (
(box1.top >= box2.top && box1.top <= box2Bottom) ||
(box2.top >= box1.top && box2.top <= box1Bottom)
);
}
/**
* Comparator for sorting boxes from highest position in the paper to lowest.
* See https://github.com/allenai/scholar-reader/issues/115 for a discussion for how we might
* be able to sort symbols by their order in the prose instead of their position.
*/
export function compareBoxes(box1: BoundingBox, box2: BoundingBox) {
if (box1.page !== box2.page) {
return box1.page - box2.page;
}
if (areBoxesVerticallyAligned(box1, box2)) {
return box1.left - box2.left;
} else {
return box1.top - box2.top;
}
}
/**
* Compare the position of two entities. Use as a comparator when ordering entities
* from top-to-bottom in the document.
*/
export function comparePosition(e1: Entity, e2: Entity) {
if (e1.id === e2.id) {
return 0;
}
if (
e1.attributes.bounding_boxes.length === 0 ||
e2.attributes.bounding_boxes.length === 0
) {
return 0;
}
return compareBoxes(
e1.attributes.bounding_boxes[0],
e2.attributes.bounding_boxes[0]
);
}
/**
* Get the page number for the first page the entity appears on.
*/
export function firstPage(entity: Entity) {
const boxes = entity.attributes.bounding_boxes;
if (boxes.length === 0) {
return null;
}
return Math.min(...boxes.map((b) => b.page));
}
export function readableFirstPageNumber(entity: Entity) {
const pageNumber = firstPage(entity);
return pageNumber !== null ? `${pageNumber + 1}` : "?";
}
/**
* Order a list of entity IDs by which ones appear first in the paper, using the position of
* the symbol bounding boxes. Does not take columns into account. This method is memoized
* because it's assumed that it will frequently be called with the list of all entities in
* the paper, and that this sort will be costly.
*/
export const orderByPosition = defaultMemoize(
(entityIds: string[], entities: Entities) => {
const sorted = [...entityIds];
sorted.sort((sId1, sId2) => {
const symbol1Boxes = entities.byId[sId1].attributes.bounding_boxes;
const symbol1TopBox = symbol1Boxes.sort(compareBoxes)[0];
const symbol2Boxes = entities.byId[sId2].attributes.bounding_boxes;
const symbol2TopBox = symbol2Boxes.sort(compareBoxes)[0];
if (symbol1Boxes.length === 0) {
return -1;
}
if (symbol2Boxes.length === 0) {
return 1;
}
return compareBoxes(symbol1TopBox, symbol2TopBox);
});
return sorted;
}
);
/**
* Order a list of definitions based on their accompanying contexts. 'definitions' and
* 'contexts' should have the same dimensions, where each definition is associated with one context.
* 'contexts' are used to sort the order of the definitions.
*/
export function orderExcerpts(
excerpts: string[],
contexts: Relationship[],
entities: Entities
) {
const contextualized = [];
for (let i = 0; i < excerpts.length; i++) {
const excerpt = excerpts[i];
const context = contexts[i];
if (context === undefined || context.id === null) {
continue;
}
const contextEntity = entities.byId[context.id];
if (contextEntity === undefined) {
continue;
}
const contextPage = firstPage(contextEntity);
if (contextPage === null) {
continue;
}
contextualized.push({ excerpt, contextEntity });
}
return contextualized.sort((c1, c2) =>
comparePosition(c1.contextEntity, c2.contextEntity)
);
}
/**
* Get definition that appears right before or after an entity. Don't include
* a definition where the entity appears.
*/
export function adjacentDefinition(
entityId: string,
entities: Entities,
where: "before" | "after"
) {
const entity = entities.byId[entityId];
const contexts = definitions([entityId], entities);
if (
entity === undefined ||
!(isTerm(entity) || isSymbol(entity)) ||
contexts.length === 0
) {
return null;
}
const sentenceId = entity.relationships.sentence.id;
return adjacentContext(sentenceId, entities, contexts, where);
}
/**
* Get a list of definitions for a set of entities, ordered by their position in the paper.
*/
export function definitions(
entityIds: string[],
entities: Entities,
includeNicknames?: boolean
) {
const entitiesWithDefinitions = entityIds
.map((id) => entities.byId[id])
.filter((e) => e !== undefined)
.filter((e) => isTerm(e) || isSymbol(e))
.map((e) => e as Term | Symbol);
const definitions = entitiesWithDefinitions
.map((e) => {
if (isTerm(e)) {
return e.attributes.definition_texs;
} else {
return e.attributes.definitions;
}
})
.flat();
const contexts = entitiesWithDefinitions
.map((s) => s.relationships.definition_sentences)
.flat();
return orderExcerpts(definitions, contexts, entities);
}
export function inDefinition(entityId: string, entities: Entities) {
const entity = entities.byId[entityId];
if (entity === undefined || (!isSymbol(entity) && !isTerm(entity))) {
return false;
}
if (isTerm(entity)) {
return entity.relationships.definition_sentences.some(
(r) => r.id !== null && r.id === entity.relationships.sentence.id
);
}
if (isSymbol(entity)) {
return (
entity.relationships.definition_sentences.some(
(r) => r.id !== null && r.id === entity.relationships.sentence.id
) ||
entity.relationships.nickname_sentences.some(
(r) => r.id !== null && r.id === entity.relationships.sentence.id
)
);
}
return false;
}
export function hasDefinition(entityId: string, entities: Entities) {
const entity = entities.byId[entityId];
if (entity === undefined || !(isSymbol(entity) || isTerm(entity))) {
return false;
}
if (isTerm(entity)) {
return entity.attributes.definition_texs.length > 0;
}
if (isSymbol(entity)) {
return (
entity.attributes.definitions.length > 0 ||
entity.attributes.nicknames.length > 0
);
}
}
/**
* Get the last context that appears right before an entity. Assumes that 'orderedContexts'
* has already been ordered by document position.
*/
export function adjacentContext(
entityId: string | null | undefined,
entities: Entities,
orderedContexts: { excerpt: string; contextEntity: Entity }[],
where: "before" | "after"
) {
if (orderedContexts.length === 0) {
return null;
}
/*
* If the requested entity doesn't exist, return the first context.
*/
if (entityId === undefined || entityId === null) {
return orderedContexts[0];
}
const entity = entities.byId[entityId];
if (entity === undefined || entity === null) {
return orderedContexts[0];
}
/*
* Return the first context that appears before the entity.
*/
if (where === "before") {
const reversed = [...orderedContexts].reverse();
for (const context of reversed) {
if (comparePosition(context.contextEntity, entity) < 0) {
return context;
}
}
} else {
for (const context of orderedContexts) {
if (comparePosition(entity, context.contextEntity) < 0) {
return context;
}
}
}
return null;
}
/**
* Get a list of usages for a set of entities, ordered by their position in the paper.
*/
export function usages(entityIds: string[], entities: Entities) {
const entitiesWithUsages = entityIds
.map((id) => entities.byId[id])
.filter((e) => e !== undefined)
.filter((e) => isTerm(e) || isSymbol(e))
.map((e) => e as Term | Symbol);
const snippets = entitiesWithUsages.map((e) => e.attributes.snippets).flat();
const contexts = entitiesWithUsages
.map((s) => s.relationships.snippet_sentences)
.flat();
return orderExcerpts(snippets, contexts, entities);
}
/**
* Rendering of equation TeX takes place using KaTeX. This leaves the rest of the text formatting
* for the prose, like citations, references, citations, italics, bolds, and more as it appeared
* in the raw TeX. This function performs some simple (brittle) replacements to attempt to turn the
* raw TeX into plaintext.
*/
export function cleanTex(tex: string) {
const noArgMacro = (name: string) => new RegExp(`\\\\${name}(?:{})?`, "g");
const oneArgMacro = (name: string) =>
new RegExp(`\\\\${name}\\{([^}]*)\\}`, "g");
return tex
.replace(/%.*?$/gm, "")
.replace(/\\&/gm, "&")
.replace(/\{\s*\\bf\s*([^}]*)\}/g, "$1")
.replace(oneArgMacro("label"), "")
.replace(oneArgMacro("texttt"), "$1")
.replace(oneArgMacro("textbf"), "$1")
.replace(oneArgMacro("textit|emph"), "$1")
.replace(oneArgMacro("footnote"), "")
.replace(oneArgMacro("\\w*cite\\w*\\*?"), "[Citation]")
.replace(oneArgMacro("(?:eq|c|)ref"), "[Reference]")
.replace(oneArgMacro("gls(?:pl)?\\*"), (_, arg) => arg.toUpperCase())
.replace(noArgMacro("bfseries"), "");
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/softwareUpdateConfigurationsMappers";
import * as Parameters from "../models/parameters";
import { AutomationClientContext } from "../automationClientContext";
/** Class representing a SoftwareUpdateConfigurations. */
export class SoftwareUpdateConfigurations {
private readonly client: AutomationClientContext;
/**
* Create a SoftwareUpdateConfigurations.
* @param {AutomationClientContext} client Reference to the service client.
*/
constructor(client: AutomationClientContext) {
this.client = client;
}
/**
* Create a new software update configuration with the name given in the URI.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param parameters Request body.
* @param [options] The optional parameters
* @returns Promise<Models.SoftwareUpdateConfigurationsCreateResponse>
*/
create(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, parameters: Models.SoftwareUpdateConfiguration, options?: Models.SoftwareUpdateConfigurationsCreateOptionalParams): Promise<Models.SoftwareUpdateConfigurationsCreateResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param parameters Request body.
* @param callback The callback
*/
create(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, parameters: Models.SoftwareUpdateConfiguration, callback: msRest.ServiceCallback<Models.SoftwareUpdateConfiguration>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param parameters Request body.
* @param options The optional parameters
* @param callback The callback
*/
create(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, parameters: Models.SoftwareUpdateConfiguration, options: Models.SoftwareUpdateConfigurationsCreateOptionalParams, callback: msRest.ServiceCallback<Models.SoftwareUpdateConfiguration>): void;
create(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, parameters: Models.SoftwareUpdateConfiguration, options?: Models.SoftwareUpdateConfigurationsCreateOptionalParams | msRest.ServiceCallback<Models.SoftwareUpdateConfiguration>, callback?: msRest.ServiceCallback<Models.SoftwareUpdateConfiguration>): Promise<Models.SoftwareUpdateConfigurationsCreateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
softwareUpdateConfigurationName,
parameters,
options
},
createOperationSpec,
callback) as Promise<Models.SoftwareUpdateConfigurationsCreateResponse>;
}
/**
* Get a single software update configuration by name.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param [options] The optional parameters
* @returns Promise<Models.SoftwareUpdateConfigurationsGetByNameResponse>
*/
getByName(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, options?: Models.SoftwareUpdateConfigurationsGetByNameOptionalParams): Promise<Models.SoftwareUpdateConfigurationsGetByNameResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param callback The callback
*/
getByName(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, callback: msRest.ServiceCallback<Models.SoftwareUpdateConfiguration>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param options The optional parameters
* @param callback The callback
*/
getByName(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, options: Models.SoftwareUpdateConfigurationsGetByNameOptionalParams, callback: msRest.ServiceCallback<Models.SoftwareUpdateConfiguration>): void;
getByName(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, options?: Models.SoftwareUpdateConfigurationsGetByNameOptionalParams | msRest.ServiceCallback<Models.SoftwareUpdateConfiguration>, callback?: msRest.ServiceCallback<Models.SoftwareUpdateConfiguration>): Promise<Models.SoftwareUpdateConfigurationsGetByNameResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
softwareUpdateConfigurationName,
options
},
getByNameOperationSpec,
callback) as Promise<Models.SoftwareUpdateConfigurationsGetByNameResponse>;
}
/**
* delete a specific software update configuration.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, options?: Models.SoftwareUpdateConfigurationsDeleteMethodOptionalParams): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param softwareUpdateConfigurationName The name of the software update configuration to be
* created.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, options: Models.SoftwareUpdateConfigurationsDeleteMethodOptionalParams, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, automationAccountName: string, softwareUpdateConfigurationName: string, options?: Models.SoftwareUpdateConfigurationsDeleteMethodOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
softwareUpdateConfigurationName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Get all software update configurations for the account.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param [options] The optional parameters
* @returns Promise<Models.SoftwareUpdateConfigurationsListResponse>
*/
list(resourceGroupName: string, automationAccountName: string, options?: Models.SoftwareUpdateConfigurationsListOptionalParams): Promise<Models.SoftwareUpdateConfigurationsListResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param callback The callback
*/
list(resourceGroupName: string, automationAccountName: string, callback: msRest.ServiceCallback<Models.SoftwareUpdateConfigurationListResult>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param options The optional parameters
* @param callback The callback
*/
list(resourceGroupName: string, automationAccountName: string, options: Models.SoftwareUpdateConfigurationsListOptionalParams, callback: msRest.ServiceCallback<Models.SoftwareUpdateConfigurationListResult>): void;
list(resourceGroupName: string, automationAccountName: string, options?: Models.SoftwareUpdateConfigurationsListOptionalParams | msRest.ServiceCallback<Models.SoftwareUpdateConfigurationListResult>, callback?: msRest.ServiceCallback<Models.SoftwareUpdateConfigurationListResult>): Promise<Models.SoftwareUpdateConfigurationsListResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
options
},
listOperationSpec,
callback) as Promise<Models.SoftwareUpdateConfigurationsListResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/softwareUpdateConfigurations/{softwareUpdateConfigurationName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.softwareUpdateConfigurationName
],
queryParameters: [
Parameters.apiVersion1
],
headerParameters: [
Parameters.clientRequestId,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.SoftwareUpdateConfiguration,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.SoftwareUpdateConfiguration
},
201: {
bodyMapper: Mappers.SoftwareUpdateConfiguration
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getByNameOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/softwareUpdateConfigurations/{softwareUpdateConfigurationName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.softwareUpdateConfigurationName
],
queryParameters: [
Parameters.apiVersion1
],
headerParameters: [
Parameters.clientRequestId,
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SoftwareUpdateConfiguration
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/softwareUpdateConfigurations/{softwareUpdateConfigurationName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.softwareUpdateConfigurationName
],
queryParameters: [
Parameters.apiVersion1
],
headerParameters: [
Parameters.clientRequestId,
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/softwareUpdateConfigurations",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.automationAccountName
],
queryParameters: [
Parameters.apiVersion1,
Parameters.filter
],
headerParameters: [
Parameters.clientRequestId,
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SoftwareUpdateConfigurationListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http';
import { MSGraphClient } from '@microsoft/sp-http';
import "@pnp/graph/users";
import "@pnp/graph/photos";
import "@pnp/graph/groups";
import { sp } from '@pnp/sp';
import "@pnp/sp/profiles";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/fields/list";
import "@pnp/sp/views/list";
import "@pnp/sp/site-users";
import "@pnp/sp/files";
import "@pnp/sp/folders";
import { Web, IWeb } from "@pnp/sp/webs";
import { ISiteUserInfo, ISiteUser } from "@pnp/sp/site-users/types";
import { PnPClientStorage, dateAdd } from '@pnp/common';
import { IUserInfo, IUserPickerInfo, SyncType, JobStatus, IAzFuncValues } from './IModel';
import * as moment from 'moment';
import ImageResize from 'image-resize';
import "@pnp/sp/search";
import { SearchQueryBuilder, SearchResults, ISearchQuery } from "@pnp/sp/search";
import { ChoiceFieldFormatType } from '@pnp/sp/fields/types';
const storage = new PnPClientStorage();
const imgResize_48 = new ImageResize({ format: 'png', width: 48, height: 48, output: 'base64' });
const imgResize_96 = new ImageResize({ format: 'png', width: 96, height: 96, output: 'base64' });
const imgResize_240 = new ImageResize({ format: 'png', width: 240, height: 240, output: 'base64' });
const map: any = require('lodash/map');
const intersection: any = require('lodash/intersection');
const orderBy: any = require('lodash/orderBy');
const chunk: any = require('lodash/chunk');
const flattenDeep: any = require('lodash/flattenDeep');
const batchItemLimit: number = 18;
const userBatchLimit: number = 6;
const userDefStorageKey: string = 'userDefaultInfo';
const userCusStorageKey: string = 'userCustomInfo';
export interface IHelper {
getLibraryDetails: (listid: string) => Promise<any>;
dataURItoBlob: (dataURI: any) => Blob;
getCurrentUserDefaultInfo: () => Promise<ISiteUserInfo>;
getCurrentUserCustomInfo: () => Promise<IUserInfo>;
checkCurrentUserGroup: (allowedGroups: string[], userGroups: string[]) => boolean;
getUsersInfo: (UserIds: string[]) => Promise<any[]>;
getUserPhotoFromAADForDisplay: (users: IUserPickerInfo[]) => Promise<any[]>;
getAndStoreUserThumbnailPhotos: (users: IUserPickerInfo[], tempLibId: string) => Promise<IAzFuncValues[]>;
generateAndStorePhotoThumbnails: (fileInfo: any[], tempLibId: string) => Promise<IAzFuncValues[]>;
createSyncItem: (syncType: SyncType) => Promise<number>;
updateSyncItem: (itemid: number, inputJson: string) => void;
getAllJobs: () => Promise<any[]>;
runAzFunction: (httpClient: HttpClient, inputData: any, azFuncUrl: string, itemid: number) => void;
checkAndCreateLists: () => Promise<boolean>;
}
export default class Helper implements IHelper {
private _web: IWeb = null;
private _graphClient: MSGraphClient = null;
private _graphUrl: string = "https://graph.microsoft.com/v1.0";
private web_ServerRelativeURL: string = '';
private TPhotoFolderName: string = 'UserPhotos';
private Lst_SyncJobs = 'UPS Photo Sync Jobs';
constructor(webRelativeUrl: string, weburl?: string, graphClient?: MSGraphClient) {
this._graphClient = graphClient ? graphClient : null;
this._web = weburl ? Web(weburl) : sp.web;
this.web_ServerRelativeURL = webRelativeUrl;
}
/**
* Get temp library details
* @param listid Temporary library
*/
public getLibraryDetails = async (listid: string): Promise<string> => {
let retFolderPath: string = '';
let listDetails = await this._web.lists.getById(listid).get();
retFolderPath = listDetails.DocumentTemplateUrl.replace('/Forms/template.dotx', '') + '/' + this.TPhotoFolderName;
return retFolderPath;
}
/**
* Check for the template folder, if not creates.
*/
public checkAndCreateFolder = async (folderPath: string) => {
try {
await this._web.getFolderByServerRelativeUrl(folderPath).get();
} catch (err) {
await this._web.folders.add(folderPath);
}
}
/**
* Convert base64 image to blob.
*/
public dataURItoBlob = (dataURI): Blob => {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: mimeString });
}
/**
* Get current logged in user default info.
*/
public getCurrentUserDefaultInfo = async (): Promise<ISiteUserInfo> => {
//return await this._web.currentUser.get();
let currentUserInfo: ISiteUserInfo = storage.local.get(userDefStorageKey);
if (!currentUserInfo) {
currentUserInfo = await this._web.currentUser.get();
storage.local.put(userDefStorageKey, currentUserInfo, dateAdd(new Date(), 'hour', 1));
}
return currentUserInfo;
}
/**
* Get current logged in user custom information.
*/
public getCurrentUserCustomInfo = async (): Promise<IUserInfo> => {
let currentUserInfo = await this._web.currentUser.get();
let currentUserGroups = await this._web.currentUser.groups.get();
return ({
ID: currentUserInfo.Id,
Email: currentUserInfo.Email,
LoginName: currentUserInfo.LoginName,
DisplayName: currentUserInfo.Title,
IsSiteAdmin: currentUserInfo.IsSiteAdmin,
Groups: map(currentUserGroups, 'LoginName'),
Picture: '/_layouts/15/userphoto.aspx?size=S&username=' + currentUserInfo.UserPrincipalName,
});
}
/**
* Check current user is a member of groups or not.
*/
public checkCurrentUserGroup = (allowedGroups: string[], userGroups: string[]): boolean => {
if (userGroups.length > 0) {
let diff: string[] = intersection(allowedGroups, userGroups);
if (diff && diff.length > 0) return true;
}
return false;
}
/**
* Get user profile photos from Azure AD
*/
public getUserPhotoFromAADForDisplay = async (users: IUserPickerInfo[]): Promise<any[]> => {
return new Promise(async (res, rej) => {
if (users && users.length > 0) {
let requests: any[] = [];
let finalResponse: any[] = [];
if (users.length > batchItemLimit) {
let chunkUserArr: any[] = chunk(users, batchItemLimit);
Promise.all(chunkUserArr.map(async chnkdata => {
requests = [];
chnkdata.map((user: IUserPickerInfo) => {
let upn: string = user.LoginName.split('|')[2];
requests.push({
id: `${user.LoginName}`,
method: 'GET',
responseType: 'blob',
headers: { "Content-Type": "image/jpeg" },
url: `/users/${upn}/photos/$value`
});
});
let photoReq: any = { requests: requests };
let graphRes: any = await this._graphClient.api('$batch').post(photoReq);
finalResponse.push(graphRes);
})).then(() => {
res(finalResponse);
});
} else {
users.map((user: IUserPickerInfo) => {
let upn: string = user.LoginName.split('|')[2];
requests.push({
id: `${user.LoginName}`,
method: 'GET',
responseType: 'blob',
headers: { "Content-Type": "image/jpeg" },
url: `/users/${upn}/photo/$value`
});
});
let photoReq: any = { requests: requests };
finalResponse.push(await this._graphClient.api('$batch').post(photoReq));
res(finalResponse);
}
}
});
}
/**
* Get user info based on UserID
*/
public getUsersInfo = async (userids: string[]): Promise<any[]> => {
return new Promise(async (res, rej) => {
let finalResponse: any[] = [];
let batch = sp.createBatch();
if (userids.length > batchItemLimit) {
let chunkUserArr: any[] = chunk(userids, batchItemLimit);
Promise.all(chunkUserArr.map(async chnkdata => {
batch = sp.createBatch();
finalResponse.push(await this.executeBatch(chnkdata, batch));
})).then(() => {
res(flattenDeep(finalResponse));
});
} else {
batch = sp.createBatch();
finalResponse.push(await this.executeBatch(userids, batch));
res(flattenDeep(finalResponse));
}
});
}
private executeBatch = (chnkdata, batch): Promise<any[]> => {
return new Promise((res, rej) => {
let finalResponse: any[] = [];
batch = sp.createBatch();
chnkdata.map((userid: string) => {
sp.web.siteUsers.getByLoginName(`i:0#.f|membership|${userid}`).inBatch(batch).get().then((userinfo) => {
if (userinfo && userinfo.Title) {
finalResponse.push({
'loginname': userid,
'title': userinfo.Title,
'status': 'Valid'
});
}
}).catch((e) => {
finalResponse.push({
'loginname': userid,
'title': 'User not found!',
'status': 'Invalid'
});
});
});
batch.execute().then(() => {
res(finalResponse);
}).catch(() => {
res(finalResponse);
});
});
}
/**
* Get thumbnail photos for the users.
* @param users List of users
*/
public getAndStoreUserThumbnailPhotos = async (users: IUserPickerInfo[], tempLibId: string): Promise<IAzFuncValues[]> => {
let retVals: IAzFuncValues[] = [];
return new Promise(async (res, rej) => {
let tempLibUrl: string = await this.getLibraryDetails(tempLibId);
await this.checkAndCreateFolder(tempLibUrl);
if (users && users.length > 0) {
let requests: any[] = [];
let finalResponse: any[] = [];
if (users.length > userBatchLimit) {
let chunkUserArr: any[] = chunk(users, userBatchLimit);
Promise.all(chunkUserArr.map(async chnkdata => {
requests = [];
chnkdata.map((user: IUserPickerInfo) => {
let upn: string = user.LoginName.split('|')[2];
requests.push({
id: `${user.LoginName}_1`,
method: 'GET',
responseType: 'blob',
headers: { "Content-Type": "image/jpeg" },
url: `/users/${upn}/photos/48x48/$value`
}, {
id: `${user.LoginName}_2`,
method: 'GET',
responseType: 'blob',
headers: { "Content-Type": "image/jpeg" },
url: `/users/${upn}/photos/96x96/$value`
}, {
id: `${user.LoginName}_3`,
method: 'GET',
responseType: 'blob',
headers: { "Content-Type": "image/jpeg" },
url: `/users/${upn}/photos/240x240/$value`
});
});
let photoReq: any = { requests: requests };
let graphRes: any = await this._graphClient.api('$batch').post(photoReq);
finalResponse.push(graphRes);
})).then(async () => {
retVals = await this.saveThumbnailPhotosInDocLib(finalResponse, tempLibUrl, "Manual");
});
} else {
users.map((user: IUserPickerInfo) => {
let upn: string = user.LoginName.split('|')[2];
requests.push({
id: `${user.LoginName}_1`,
method: 'GET',
responseType: 'blob',
headers: { "Content-Type": "image/jpeg" },
url: `/users/${upn}/photos/48x48/$value`
}, {
id: `${user.LoginName}_2`,
method: 'GET',
responseType: 'blob',
headers: { "Content-Type": "image/jpeg" },
url: `/users/${upn}/photos/96x96/$value`
}, {
id: `${user.LoginName}_3`,
method: 'GET',
responseType: 'blob',
headers: { "Content-Type": "image/jpeg" },
url: `/users/${upn}/photos/240x240/$value`
});
});
let photoReq: any = { requests: requests };
finalResponse.push(await this._graphClient.api('$batch').post(photoReq));
retVals = await this.saveThumbnailPhotosInDocLib(finalResponse, tempLibUrl, "Manual");
}
}
res(retVals);
});
}
/**
* Add thumbnails to the configured document library
*/
private saveThumbnailPhotosInDocLib = async (thumbnails: any[], tempLibName: string, scope: 'Manual' | 'Bulk'): Promise<IAzFuncValues[]> => {
let retVals: IAzFuncValues[] = [];
if (thumbnails && thumbnails.length > 0) {
if (scope === "Manual") {
thumbnails.map(res => {
if (res.responses && res.responses.length > 0) {
res.responses.map(async thumbnail => {
if (!thumbnail.body.error) {
let username: string = thumbnail.id.split('_')[0].split('|')[2];
let userFilename: string = username.replace(/[@.]/g, '_');
let filecontent = this.dataURItoBlob("data:image/jpg;base64," + thumbnail.body);
let partFileName = '';
retVals.push({
userid: username,
picturename: userFilename
});
if (thumbnail.id.indexOf('_1') > 0) partFileName = 'SThumb.jpg';
else if (thumbnail.id.indexOf('_2') > 0) partFileName = "MThumb.jpg";
else if (thumbnail.id.indexOf('_3') > 0) partFileName = "LThumb.jpg";
await sp.web.getFolderByServerRelativeUrl(decodeURI(`${tempLibName}/`))
.files
.add(decodeURI(`${tempLibName}/${userFilename}_` + partFileName), filecontent, true);
}
});
}
});
return retVals;
}
if (scope === "Bulk") {
return new Promise((res, rej) => {
let batch = sp.createBatch();
thumbnails.map(async thumbnail => {
let username: string = thumbnail.name.replace('.' + thumbnail.name.split('.').pop(), '');
let userFilename: string = username.replace(/[@.]/g, '_');
retVals.push({
userid: username,
picturename: userFilename
});
let filecontent_48 = this.dataURItoBlob(thumbnail.Thumb48);
sp.web.getFolderByServerRelativeUrl(decodeURI(`${tempLibName}/`))
.files.inBatch(batch)
.add(decodeURI(`${tempLibName}/${userFilename}_` + 'SThumb.jpg'), filecontent_48, true);
let filecontent_96 = this.dataURItoBlob(thumbnail.Thumb96);
sp.web.getFolderByServerRelativeUrl(decodeURI(`${tempLibName}/`))
.files.inBatch(batch)
.add(decodeURI(`${tempLibName}/${userFilename}_` + 'MThumb.jpg'), filecontent_96, true);
let filecontent_240 = this.dataURItoBlob(thumbnail.Thumb240);
sp.web.getFolderByServerRelativeUrl(decodeURI(`${tempLibName}/`))
.files.inBatch(batch)
.add(decodeURI(`${tempLibName}/${userFilename}_` + 'LThumb.jpg'), filecontent_240, true);
});
batch.execute().then(() => { res(retVals); });
});
}
}
}
/**
* Generate 3 different thumbnails and upload to the temp library.
*/
public generateAndStorePhotoThumbnails = async (fileInfo: any[], tempLibId: string): Promise<IAzFuncValues[]> => {
return new Promise(async (res, rej) => {
if (fileInfo && fileInfo.length > 0) {
let tempLibUrl: string = await this.getLibraryDetails(tempLibId);
Promise.all(fileInfo.map(async file => {
file['Thumb48'] = await imgResize_48.play(URL.createObjectURL(file));
file['Thumb96'] = await imgResize_96.play(URL.createObjectURL(file));
file['Thumb240'] = await imgResize_240.play(URL.createObjectURL(file));
})).then(async () => {
let users: any = await this.saveThumbnailPhotosInDocLib(fileInfo, tempLibUrl, "Bulk");
res(users);
}).catch(err => {
console.log("Error while generating thumbnails: ", err);
res([]);
});
}
});
}
/**
* Create a sync item
*/
public createSyncItem = async (syncType: SyncType): Promise<number> => {
let returnVal: number = 0;
let itemAdded = await this._web.lists.getByTitle(this.Lst_SyncJobs).items.add({
Title: `SyncJob_${moment().format("MMDDYYYYhhmm")}`,
Status: JobStatus.Submitted.toString(),
SyncType: syncType.toString()
});
returnVal = itemAdded.data.Id;
return returnVal;
}
/**
* Update Sync item with the input data to sync
*/
public updateSyncItem = async (itemid: number, inputJson: string) => {
await this._web.lists.getByTitle(this.Lst_SyncJobs).items.getById(itemid).update({
SyncData: inputJson
});
}
/**
* Update Sync item with the error status
*/
public updateSyncItemStatus = async (itemid: number, errMsg: string) => {
await this._web.lists.getByTitle(this.Lst_SyncJobs).items.getById(itemid).update({
Status: JobStatus.Error,
ErrorMessage: errMsg
});
}
/**
* Get all the jobs items
*/
public getAllJobs = async (): Promise<any[]> => {
return await this._web.lists.getByTitle(this.Lst_SyncJobs).items
.select('ID', 'Title', 'SyncedData', 'Status', 'ErrorMessage', 'SyncType', 'Created', 'Author/Title', 'Author/Id', 'Author/EMail')
.expand('Author')
.getAll();
}
/**
* Azure function to update the UPS Photo properties.
*/
public runAzFunction = async (httpClient: HttpClient, inputData: any, azFuncUrl: string, itemid: number) => {
const requestHeaders: Headers = new Headers();
requestHeaders.append("Content-type", "application/json");
requestHeaders.append("Cache-Control", "no-cache");
const postOptions: IHttpClientOptions = {
headers: requestHeaders,
body: `${inputData}`
};
let response: HttpClientResponse = await httpClient.post(azFuncUrl, HttpClient.configurations.v1, postOptions);
if (!response.ok) {
await this.updateSyncItemStatus(itemid, `${response.status} - ${response.statusText}`);
}
console.log("Azure Function executed");
}
/**
* Check and create the required lists
*/
public checkAndCreateLists = async (): Promise<boolean> => {
return new Promise<boolean>(async (res, rej) => {
try {
await this._web.lists.getByTitle(this.Lst_SyncJobs).get();
console.log('Sync Jobs List Exists');
} catch (err) {
console.log("Sync Jobs List doesn't exists, so creating...");
await this._createSyncJobsList();
console.log("Sync Jobs List created");
}
console.log("Checked all lists");
res(true);
});
}
/**
* Create Sync Jobs list
*/
public _createSyncJobsList = async () => {
let listExists = await (await sp.web.lists.ensure(this.Lst_SyncJobs)).list;
await listExists.fields.addMultilineText('SyncData', 6, false, false, false, false, { Required: true, Description: 'Data sent to Azure function for property update.' });
await listExists.fields.addMultilineText('SyncedData', 6, false, false, false, false, { Required: true, Description: 'Data received from Azure function with property update status.' });
await listExists.fields.addChoice('Status', ['Submitted', 'In-Progress', 'Completed', 'Error'], ChoiceFieldFormatType.Dropdown, false, { Required: true, Description: 'Status of the job.' });
await listExists.fields.addChoice('SyncType', ['Manual', 'Bulk'], ChoiceFieldFormatType.Dropdown, false, { Required: true, Description: 'Type of data sent to Azure function.' });
await listExists.fields.addMultilineText('ErrorMessage', 6, false, false, false, false, { Required: false, Description: 'Store the error message while calling Azure function.' });
let allItemsView = await listExists.views.getByTitle('All Items');
let batch = sp.createBatch();
allItemsView.fields.inBatch(batch).add('ID');
allItemsView.fields.inBatch(batch).add('SyncType');
allItemsView.fields.inBatch(batch).add('SyncData');
allItemsView.fields.inBatch(batch).add('SyncedData');
allItemsView.fields.inBatch(batch).add('Status');
allItemsView.fields.inBatch(batch).add('ErrorMessage');
allItemsView.fields.inBatch(batch).move('ID', 0);
await batch.execute();
}
} | the_stack |
import IDisplayContext = etch.drawing.IDisplayContext;
import Point = etch.primitives.Point;
import {IApp} from '../../IApp';
import {SamplerBase} from './SamplerBase';
import {SoundCloudAPI} from '../../Core/Audio/SoundCloud/SoundCloudAPI';
import {SoundCloudTrack} from '../../Core/Audio/SoundCloud/SoundcloudTrack';
declare var App: IApp;
export class Sample extends SamplerBase {
public Sources : Tone.Simpler[];
public Params: SoundcloudParams;
//private WaveForm: number[];
private _FirstRelease: boolean = true;
private _LoadFromShare: boolean = false;
private _FallBackTrack: SoundCloudTrack;
public LoadTimeout: any;
Init(drawTo: IDisplayContext): void {
this.BlockName = App.L10n.Blocks.Source.Blocks.Sample.name;
if (this.Params) {
this._LoadFromShare = true;
setTimeout(() => {
this.FirstSetup();
},100);
}
this.Defaults = {
playbackRate: 0,
detune: 0,
reverse: false,
startPosition: 0,
endPosition: null,
loop: true,
loopStart: 0,
loopEnd: 0,
volume: 11,
track: 'https://files.blokdust.io/impulse-responses/teufelsberg01.wav',
trackName: 'TEUFELSBERG',
user: 'Balance Mastering',
permalink: ''
};
this.PopulateParams();
this.WaveForm = [];
this.SearchResults = [];
this.Searching = false;
this._FallBackTrack = new SoundCloudTrack(this.Params.trackName,this.Params.user,this.Params.track,this.Params.permalink);
super.Init(drawTo);
// Define Outline for HitTest
this.Outline.push(new Point(-1, 0),new Point(0, -1),new Point(1, -1),new Point(2, 0),new Point(1, 1),new Point(0, 1));
//SoundCloudAPI.Monitor();
}
//-------------------------------------------------------------------------------------------
// SETUP
//-------------------------------------------------------------------------------------------
FirstSetup() {
if (this._FirstRelease) {
//this.Search(App.MainScene.SoundcloudPanel.RandomSearch(this));
this.SetBuffers();
//this.DataToBuffer();
this.Envelopes.forEach((e: Tone.AmplitudeEnvelope, i: number)=> {
e = this.Sources[i].envelope;
});
this.Sources.forEach((s: Tone.Simpler) => {
s.connect(this.AudioInput);
});
this._FirstRelease = false;
}
}
//-------------------------------------------------------------------------------------------
// SOUNDCLOUD SEARCH
//-------------------------------------------------------------------------------------------
Search(query: string) {
this.Searching = true;
App.MainScene.OptionsPanel.Animating = true;
this.ResultsPage = 1;
this.SearchResults = [];
SoundCloudAPI.MultiSearch(query, App.Config.SoundCloudMaxTrackLength, this);
}
SetSearchResults(results) {
super.SetSearchResults(results);
this.Searching = false;
App.MainScene.OptionsPanel.Animating = false;
var len = results.length;
for (var i=0; i<len; i++) {
var track = results[i];
this.SearchResults.push(new SoundCloudTrack(track.title, track.user.username, track.uri, track.permalink_url));
}
}
//-------------------------------------------------------------------------------------------
// TRACK LOADING
//-------------------------------------------------------------------------------------------
// LOAD TRACK //
LoadTrack(track, fullUrl?:boolean) {
super.LoadTrack(track,fullUrl);
fullUrl = fullUrl || false;
// select load url, from SC or "picker" function //
if (fullUrl) {
this.Params.track = track.URI;
} else {
this.Params.track = SoundCloudAPI.LoadTrack(track);
}
// update rest of the params //
this.Params.permalink = track.Permalink;
this.Params.trackName = track.TitleShort;
this.Params.user = track.UserShort;
this.Params.reverse = false;
this.WaveForm = [];
// decode track & load up the buffers //
this.SetBuffers();
// Update visuals //
this.RefreshOptionsPanel("animate");
}
// LOAD FAILED, FALL BACK TO LAST //
TrackFallBack() {
this._LoadFromShare = false;
// If fallback is failing, reset fallback to the defaults (to end perpetual load loops) //
if (this.Params.track === this._FallBackTrack.URI) {
this._FallBackTrack = new SoundCloudTrack(this.Defaults.trackName,this.Defaults.user,this.Defaults.track,this.Defaults.permalink);
}
this.LoadTrack(this._FallBackTrack,true);
App.Message("Load Failed: This Track Is Unavailable. Reloading last track.");
}
//-------------------------------------------------------------------------------------------
// BUFFERS
//-------------------------------------------------------------------------------------------
// DECODE LOADED TRACK & SET BUFFERS //
SetBuffers() {
// Stop sound //
this.Sources.forEach((s: any)=> {
s.triggerRelease();
});
// Set load Visual //
App.AnimationsLayer.AddToList(this);
// Load primary buffer //
if (this.PrimaryBuffer) {
this.PrimaryBuffer.dispose();
}
this.PrimaryBuffer = new Tone.Buffer(this.Params.track, (e) => {
// We haven't timed out //
clearTimeout(this.LoadTimeout);
// Reset locators //
var duration = this.GetDuration(this.PrimaryBuffer);
if (!this._LoadFromShare) {
console.log('not load from share');
this.Params.startPosition = 0;
this.Params.endPosition = duration;
this.Params.loopStart = duration * 0.5;
this.Params.loopEnd = duration;
}
// Set this as a fallback if future loads fail //
this._FallBackTrack = new SoundCloudTrack(this.Params.trackName,this.Params.user,this.Params.track,this.Params.permalink);
// Set the source buffers //
this.Sources.forEach((s: Tone.Simpler)=> {
s.player.buffer = e;
s.player.loopStart = this.Params.loopStart;
s.player.loopEnd = this.Params.loopEnd;
});
// Reset reverse buffer //
if (this.ReverseBuffer) {
this.ReverseBuffer = null;
}
// if loaded from save & reverse //
if (this._LoadFromShare && this.Params.reverse) {
this.ReverseTrack();
}
this._LoadFromShare = false;
// Update visuals //
App.AnimationsLayer.RemoveFromList(this);
this.WaveForm = App.Audio.Waveform.GetWaveformFromBuffer(e._buffer,200,5,95);
this.RefreshOptionsPanel();
// If playing, retrigger //
/*if (this.IsPowered()) {
this.TriggerAttack();
}*/
this.RetriggerActiveVoices();
});
// Start / reset loading timeout //
clearTimeout(this.LoadTimeout);
this.LoadTimeout = setTimeout( () => {
this.TrackFallBack();
},(App.Config.SoundCloudLoadTimeout*1000));
//TODO - onerror doesn't seem to work
this.PrimaryBuffer.onerror = () => {
this.TrackFallBack();
};
}
//-------------------------------------------------------------------------------------------
// TRACK REVERSING
//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------
// DRAW
//-------------------------------------------------------------------------------------------
Draw() {
super.Draw();
this.DrawSprite(this.BlockName);
}
//-------------------------------------------------------------------------------------------
// OPTIONS
//-------------------------------------------------------------------------------------------
UpdateOptionsForm() {
super.UpdateOptionsForm();
this.OptionsForm =
{
"name" : App.L10n.Blocks.Source.Blocks.Sample.name,
"parameters" : [
{
"type" : "waveregion",
"name" : "Region",
"setting" :"region",
"props" : {
"value" : 5,
"min" : 0,
"max" : this.GetDuration(this.PrimaryBuffer),
"quantised" : false,
"centered" : false,
"wavearray" : this.WaveForm,
"mode" : this.Params.loop
},"nodes": [
{
"setting": "startPosition",
"value": this.Params.startPosition
},
{
"setting": "endPosition",
"value": this.Params.endPosition
},
{
"setting": "loopStart",
"value": this.Params.loopStart
},
{
"setting": "loopEnd",
"value": this.Params.loopEnd
}
]
},
{
"type" : "sample",
"name" : "Sample",
"setting" :"sample",
"props" : {
"track" : this.Params.trackName,
"user" : this.Params.user,
"permalink" : this.Params.permalink
}
},
{
"type" : "switches",
"name" : "Loop",
"setting" :"loop",
"switches": [
{
"name": "Reverse",
"setting": "reverse",
"value": this.Params.reverse,
"lit" : true,
"mode": "offOn"
},
{
"name": "Looping",
"setting": "loop",
"value": this.Params.loop,
"lit" : true,
"mode": "offOn"
}
]
},
{
"type" : "slider",
"name" : "playback",
"setting" :"playbackRate",
"props" : {
"value" : this.Params.playbackRate,
"min" : -App.Config.PlaybackRange,
"max" : App.Config.PlaybackRange,
"quantised" : false,
"centered" : true
}
}
]
};
}
SetParam(param: string,value: any) {
super.SetParam(param,value);
var val = value;
switch(param) {
case "playbackRate":
this.Params.playbackRate = value;
this.NoteUpdate();
break;
case "reverse":
value = value? true : false;
this.Params[param] = val;
this.ReverseTrack();
break;
case "loop":
value = value? true : false;
this.Sources.forEach((s: Tone.Simpler)=> {
s.player.loop = value;
});
if (value === true && this.IsPowered()) {
this.Sources.forEach((s: Tone.Simpler) => {
s.player.stop();
s.player.start(s.player.startPosition);
});
}
// update display of loop sliders
this.Params[param] = val;
this.RefreshOptionsPanel();
break;
case "loopStart":
this.Sources.forEach((s: Tone.Simpler)=> {
s.player.loopStart = value;
});
break;
case "loopEnd":
this.Sources.forEach((s: Tone.Simpler)=> {
s.player.loopEnd = value;
});
break;
}
this.Params[param] = value;
}
//-------------------------------------------------------------------------------------------
// DISPOSE
//-------------------------------------------------------------------------------------------
Dispose(){
super.Dispose();
}
} | the_stack |
import { Z80Tester } from "./z80-tester";
describe("Disassembler - standard instructions", function () {
this.timeout(10000);
it("Standard instructions 0x00-0x0F work as expected", async () => {
// --- Act
await Z80Tester.Test("nop", 0x00);
await Z80Tester.Test("ld bc,#1234", 0x01, 0x34, 0x12);
await Z80Tester.Test("ld (bc),a", 0x02);
await Z80Tester.Test("inc bc", 0x03);
await Z80Tester.Test("inc b", 0x04);
await Z80Tester.Test("dec b", 0x05);
await Z80Tester.Test("ld b,#23", 0x06, 0x23);
await Z80Tester.Test("rlca", 0x07);
await Z80Tester.Test("ex af,af'", 0x08);
await Z80Tester.Test("add hl,bc", 0x09);
await Z80Tester.Test("ld a,(bc)", 0x0a);
await Z80Tester.Test("dec bc", 0x0b);
await Z80Tester.Test("inc c", 0x0c);
await Z80Tester.Test("dec c", 0x0d);
await Z80Tester.Test("ld c,#23", 0x0e, 0x23);
await Z80Tester.Test("rrca", 0x0f);
});
it("Standard instructions 0x10-0x1F work as expected", async () => {
// --- Act
await Z80Tester.Test("djnz L0002", 0x10, 0x00);
await Z80Tester.Test("djnz L0022", 0x10, 0x20);
await Z80Tester.Test("djnz LFFF2", 0x10, 0xf0);
await Z80Tester.Test("ld de,#1234", 0x11, 0x34, 0x12);
await Z80Tester.Test("ld (de),a", 0x12);
await Z80Tester.Test("inc de", 0x13);
await Z80Tester.Test("inc d", 0x14);
await Z80Tester.Test("dec d", 0x15);
await Z80Tester.Test("ld d,#23", 0x16, 0x23);
await Z80Tester.Test("rla", 0x17);
await Z80Tester.Test("jr L0002", 0x18, 0x00);
await Z80Tester.Test("jr L0022", 0x18, 0x20);
await Z80Tester.Test("jr LFFF2", 0x18, 0xf0);
await Z80Tester.Test("add hl,de", 0x19);
await Z80Tester.Test("ld a,(de)", 0x1a);
await Z80Tester.Test("dec de", 0x1b);
await Z80Tester.Test("inc e", 0x1c);
await Z80Tester.Test("dec e", 0x1d);
await Z80Tester.Test("ld e,#23", 0x1e, 0x23);
await Z80Tester.Test("rra", 0x1f);
});
it("Standard instructions 0x20-0x2F work as expected", async () => {
// --- Act
await Z80Tester.Test("jr nz,L0002", 0x20, 0x00);
await Z80Tester.Test("jr nz,L0022", 0x20, 0x20);
await Z80Tester.Test("jr nz,LFFF2", 0x20, 0xf0);
await Z80Tester.Test("ld hl,#1234", 0x21, 0x34, 0x12);
await Z80Tester.Test("ld (#3456),hl", 0x22, 0x56, 0x34);
await Z80Tester.Test("inc hl", 0x23);
await Z80Tester.Test("inc h", 0x24);
await Z80Tester.Test("dec h", 0x25);
await Z80Tester.Test("ld h,#23", 0x26, 0x23);
await Z80Tester.Test("daa", 0x27);
await Z80Tester.Test("jr z,L0002", 0x28, 0x00);
await Z80Tester.Test("jr z,L0022", 0x28, 0x20);
await Z80Tester.Test("jr z,LFFF2", 0x28, 0xf0);
await Z80Tester.Test("add hl,hl", 0x29);
await Z80Tester.Test("ld hl,(#3456)", 0x2a, 0x56, 0x34);
await Z80Tester.Test("dec hl", 0x2b);
await Z80Tester.Test("inc l", 0x2c);
await Z80Tester.Test("dec l", 0x2d);
await Z80Tester.Test("ld l,#23", 0x2e, 0x23);
await Z80Tester.Test("cpl", 0x2f);
});
it("Standard instructions 0x30-0x3F work as expected", async () => {
// --- Act
await Z80Tester.Test("jr nc,L0002", 0x30, 0x00);
await Z80Tester.Test("jr nc,L0022", 0x30, 0x20);
await Z80Tester.Test("jr nc,LFFF2", 0x30, 0xf0);
await Z80Tester.Test("ld sp,#1234", 0x31, 0x34, 0x12);
await Z80Tester.Test("ld (#3456),a", 0x32, 0x56, 0x34);
await Z80Tester.Test("inc sp", 0x33);
await Z80Tester.Test("inc (hl)", 0x34);
await Z80Tester.Test("dec (hl)", 0x35);
await Z80Tester.Test("ld (hl),#23", 0x36, 0x23);
await Z80Tester.Test("scf", 0x37);
await Z80Tester.Test("jr c,L0002", 0x38, 0x00);
await Z80Tester.Test("jr c,L0022", 0x38, 0x20);
await Z80Tester.Test("jr c,LFFF2", 0x38, 0xf0);
await Z80Tester.Test("add hl,sp", 0x39);
await Z80Tester.Test("ld a,(#3456)", 0x3a, 0x56, 0x34);
await Z80Tester.Test("dec sp", 0x3b);
await Z80Tester.Test("inc a", 0x3c);
await Z80Tester.Test("dec a", 0x3d);
await Z80Tester.Test("ld a,#23", 0x3e, 0x23);
await Z80Tester.Test("ccf", 0x3f);
});
it("Standard instructions 0x40-0x4F work as expected", async () => {
// --- Act
await Z80Tester.Test("ld b,b", 0x40);
await Z80Tester.Test("ld b,c", 0x41);
await Z80Tester.Test("ld b,d", 0x42);
await Z80Tester.Test("ld b,e", 0x43);
await Z80Tester.Test("ld b,h", 0x44);
await Z80Tester.Test("ld b,l", 0x45);
await Z80Tester.Test("ld b,(hl)", 0x46);
await Z80Tester.Test("ld b,a", 0x47);
await Z80Tester.Test("ld c,b", 0x48);
await Z80Tester.Test("ld c,c", 0x49);
await Z80Tester.Test("ld c,d", 0x4a);
await Z80Tester.Test("ld c,e", 0x4b);
await Z80Tester.Test("ld c,h", 0x4c);
await Z80Tester.Test("ld c,l", 0x4d);
await Z80Tester.Test("ld c,(hl)", 0x4e);
await Z80Tester.Test("ld c,a", 0x4f);
});
it("Standard instructions 0x50-0x5F work as expected", async () => {
// --- Act
await Z80Tester.Test("ld d,b", 0x50);
await Z80Tester.Test("ld d,c", 0x51);
await Z80Tester.Test("ld d,d", 0x52);
await Z80Tester.Test("ld d,e", 0x53);
await Z80Tester.Test("ld d,h", 0x54);
await Z80Tester.Test("ld d,l", 0x55);
await Z80Tester.Test("ld d,(hl)", 0x56);
await Z80Tester.Test("ld d,a", 0x57);
await Z80Tester.Test("ld e,b", 0x58);
await Z80Tester.Test("ld e,c", 0x59);
await Z80Tester.Test("ld e,d", 0x5a);
await Z80Tester.Test("ld e,e", 0x5b);
await Z80Tester.Test("ld e,h", 0x5c);
await Z80Tester.Test("ld e,l", 0x5d);
await Z80Tester.Test("ld e,(hl)", 0x5e);
await Z80Tester.Test("ld e,a", 0x5f);
});
it("Standard instructions 0x60-0x6F work as expected", async () => {
// --- Act
await Z80Tester.Test("ld h,b", 0x60);
await Z80Tester.Test("ld h,c", 0x61);
await Z80Tester.Test("ld h,d", 0x62);
await Z80Tester.Test("ld h,e", 0x63);
await Z80Tester.Test("ld h,h", 0x64);
await Z80Tester.Test("ld h,l", 0x65);
await Z80Tester.Test("ld h,(hl)", 0x66);
await Z80Tester.Test("ld h,a", 0x67);
await Z80Tester.Test("ld l,b", 0x68);
await Z80Tester.Test("ld l,c", 0x69);
await Z80Tester.Test("ld l,d", 0x6a);
await Z80Tester.Test("ld l,e", 0x6b);
await Z80Tester.Test("ld l,h", 0x6c);
await Z80Tester.Test("ld l,l", 0x6d);
await Z80Tester.Test("ld l,(hl)", 0x6e);
await Z80Tester.Test("ld l,a", 0x6f);
});
it("Standard instructions 0x70-0x7F work as expected", async () => {
// --- Act
await Z80Tester.Test("ld (hl),b", 0x70);
await Z80Tester.Test("ld (hl),c", 0x71);
await Z80Tester.Test("ld (hl),d", 0x72);
await Z80Tester.Test("ld (hl),e", 0x73);
await Z80Tester.Test("ld (hl),h", 0x74);
await Z80Tester.Test("ld (hl),l", 0x75);
await Z80Tester.Test("halt", 0x76);
await Z80Tester.Test("ld (hl),a", 0x77);
await Z80Tester.Test("ld a,b", 0x78);
await Z80Tester.Test("ld a,c", 0x79);
await Z80Tester.Test("ld a,d", 0x7a);
await Z80Tester.Test("ld a,e", 0x7b);
await Z80Tester.Test("ld a,h", 0x7c);
await Z80Tester.Test("ld a,l", 0x7d);
await Z80Tester.Test("ld a,(hl)", 0x7e);
await Z80Tester.Test("ld a,a", 0x7f);
});
it("Standard instructions 0x80-0x8F work as expected", async () => {
// --- Act
await Z80Tester.Test("add a,b", 0x80);
await Z80Tester.Test("add a,c", 0x81);
await Z80Tester.Test("add a,d", 0x82);
await Z80Tester.Test("add a,e", 0x83);
await Z80Tester.Test("add a,h", 0x84);
await Z80Tester.Test("add a,l", 0x85);
await Z80Tester.Test("add a,(hl)", 0x86);
await Z80Tester.Test("add a,a", 0x87);
await Z80Tester.Test("adc a,b", 0x88);
await Z80Tester.Test("adc a,c", 0x89);
await Z80Tester.Test("adc a,d", 0x8a);
await Z80Tester.Test("adc a,e", 0x8b);
await Z80Tester.Test("adc a,h", 0x8c);
await Z80Tester.Test("adc a,l", 0x8d);
await Z80Tester.Test("adc a,(hl)", 0x8e);
await Z80Tester.Test("adc a,a", 0x8f);
});
it("Standard instructions 0x90-0x9F work as expected", async () => {
// --- Act
await Z80Tester.Test("sub b", 0x90);
await Z80Tester.Test("sub c", 0x91);
await Z80Tester.Test("sub d", 0x92);
await Z80Tester.Test("sub e", 0x93);
await Z80Tester.Test("sub h", 0x94);
await Z80Tester.Test("sub l", 0x95);
await Z80Tester.Test("sub (hl)", 0x96);
await Z80Tester.Test("sub a", 0x97);
await Z80Tester.Test("sbc a,b", 0x98);
await Z80Tester.Test("sbc a,c", 0x99);
await Z80Tester.Test("sbc a,d", 0x9a);
await Z80Tester.Test("sbc a,e", 0x9b);
await Z80Tester.Test("sbc a,h", 0x9c);
await Z80Tester.Test("sbc a,l", 0x9d);
await Z80Tester.Test("sbc a,(hl)", 0x9e);
await Z80Tester.Test("sbc a,a", 0x9f);
});
it("Standard instructions 0xA0-0xAF work as expected", async () => {
// --- Act
await Z80Tester.Test("and b", 0xa0);
await Z80Tester.Test("and c", 0xa1);
await Z80Tester.Test("and d", 0xa2);
await Z80Tester.Test("and e", 0xa3);
await Z80Tester.Test("and h", 0xa4);
await Z80Tester.Test("and l", 0xa5);
await Z80Tester.Test("and (hl)", 0xa6);
await Z80Tester.Test("and a", 0xa7);
await Z80Tester.Test("xor b", 0xa8);
await Z80Tester.Test("xor c", 0xa9);
await Z80Tester.Test("xor d", 0xaa);
await Z80Tester.Test("xor e", 0xab);
await Z80Tester.Test("xor h", 0xac);
await Z80Tester.Test("xor l", 0xad);
await Z80Tester.Test("xor (hl)", 0xae);
await Z80Tester.Test("xor a", 0xaf);
});
it("Standard instructions 0xB0-0xBF work as expected", async () => {
// --- Act
await Z80Tester.Test("or b", 0xb0);
await Z80Tester.Test("or c", 0xb1);
await Z80Tester.Test("or d", 0xb2);
await Z80Tester.Test("or e", 0xb3);
await Z80Tester.Test("or h", 0xb4);
await Z80Tester.Test("or l", 0xb5);
await Z80Tester.Test("or (hl)", 0xb6);
await Z80Tester.Test("or a", 0xb7);
await Z80Tester.Test("cp b", 0xb8);
await Z80Tester.Test("cp c", 0xb9);
await Z80Tester.Test("cp d", 0xba);
await Z80Tester.Test("cp e", 0xbb);
await Z80Tester.Test("cp h", 0xbc);
await Z80Tester.Test("cp l", 0xbd);
await Z80Tester.Test("cp (hl)", 0xbe);
await Z80Tester.Test("cp a", 0xbf);
});
it("Standard instructions 0xC0-0xCF work as expected", async () => {
// --- Act
await Z80Tester.Test("ret nz", 0xc0);
await Z80Tester.Test("pop bc", 0xc1);
await Z80Tester.Test("jp nz,L5678", 0xc2, 0x78, 0x56);
await Z80Tester.Test("jp L5678", 0xc3, 0x78, 0x56);
await Z80Tester.Test("call nz,L5678", 0xc4, 0x78, 0x56);
await Z80Tester.Test("push bc", 0xc5);
await Z80Tester.Test("add a,#34", 0xc6, 0x34);
await Z80Tester.Test("rst #00", 0xc7);
await Z80Tester.Test("ret z", 0xc8);
await Z80Tester.Test("ret", 0xc9);
await Z80Tester.Test("jp z,L5678", 0xca, 0x78, 0x56);
// -- 0xCB is the bit operation prefix
await Z80Tester.Test("call z,L5678", 0xcc, 0x78, 0x56);
await Z80Tester.Test("call L5678", 0xcd, 0x78, 0x56);
await Z80Tester.Test("adc a,#34", 0xce, 0x34);
await Z80Tester.Test("rst #08", 0xcf);
});
it("Standard instructions 0xD0-0xDF work as expected", async () => {
// --- Act
await Z80Tester.Test("ret nc", 0xd0);
await Z80Tester.Test("pop de", 0xd1);
await Z80Tester.Test("jp nc,L5678", 0xd2, 0x78, 0x56);
await Z80Tester.Test("out (#78),a", 0xd3, 0x78);
await Z80Tester.Test("call nc,L5678", 0xd4, 0x78, 0x56);
await Z80Tester.Test("push de", 0xd5);
await Z80Tester.Test("sub #34", 0xd6, 0x34);
await Z80Tester.Test("rst #10", 0xd7);
await Z80Tester.Test("ret c", 0xd8);
await Z80Tester.Test("exx", 0xd9);
await Z80Tester.Test("jp c,L5678", 0xda, 0x78, 0x56);
await Z80Tester.Test("in a,(#78)", 0xdb, 0x78);
await Z80Tester.Test("call c,L5678", 0xdc, 0x78, 0x56);
// -- 0xDD is the IX operation prefix
await Z80Tester.Test("sbc a,#34", 0xde, 0x34);
await Z80Tester.Test("rst #18", 0xdf);
});
it("Standard instructions 0xE0-0xEF work as expected", async () => {
// --- Act
await Z80Tester.Test("ret po", 0xe0);
await Z80Tester.Test("pop hl", 0xe1);
await Z80Tester.Test("jp po,L5678", 0xe2, 0x78, 0x56);
await Z80Tester.Test("ex (sp),hl", 0xe3);
await Z80Tester.Test("call po,L5678", 0xe4, 0x78, 0x56);
await Z80Tester.Test("push hl", 0xe5);
await Z80Tester.Test("and #34", 0xe6, 0x34);
await Z80Tester.Test("rst #20", 0xe7);
await Z80Tester.Test("ret pe", 0xe8);
await Z80Tester.Test("jp (hl)", 0xe9);
await Z80Tester.Test("jp pe,L5678", 0xea, 0x78, 0x56);
await Z80Tester.Test("ex de,hl", 0xeb);
await Z80Tester.Test("call pe,L5678", 0xec, 0x78, 0x56);
// -- 0xED is the extended operation prefix
await Z80Tester.Test("xor #34", 0xee, 0x34);
await Z80Tester.Test("rst #28", 0xef);
});
it("Standard instructions 0xF0-0xFF work as expected", async () => {
// --- Act
await Z80Tester.Test("ret p", 0xf0);
await Z80Tester.Test("pop af", 0xf1);
await Z80Tester.Test("jp p,L5678", 0xf2, 0x78, 0x56);
await Z80Tester.Test("di", 0xf3);
await Z80Tester.Test("call p,L5678", 0xf4, 0x78, 0x56);
await Z80Tester.Test("push af", 0xf5);
await Z80Tester.Test("or #34", 0xf6, 0x34);
await Z80Tester.Test("rst #30", 0xf7);
await Z80Tester.Test("ret m", 0xf8);
await Z80Tester.Test("ld sp,hl", 0xf9);
await Z80Tester.Test("jp m,L5678", 0xfa, 0x78, 0x56);
await Z80Tester.Test("ei", 0xfb);
await Z80Tester.Test("call m,L5678", 0xfc, 0x78, 0x56);
// -- 0xFD is the IY operation prefix
await Z80Tester.Test("cp #34", 0xfe, 0x34);
await Z80Tester.Test("rst #38", 0xff);
});
}); | the_stack |
import {
EnhancedRxState,
NGT_OBJECT_INPUTS_CONTROLLER_PROVIDER,
NGT_OBJECT_INPUTS_WATCHED_CONTROLLER,
NgtAnimationFrameStore,
NgtLoopService,
NgtObject3dInputsController,
NgtObject3dInputsControllerModule,
NgtSobaExtender,
NgtStore,
} from '@angular-three/core';
import { NgtGroupModule } from '@angular-three/core/group';
import {
ChangeDetectionStrategy,
Component,
ContentChildren,
Inject,
Injectable,
Input,
NgModule,
QueryList,
} from '@angular/core';
import { requestAnimationFrame } from '@rx-angular/cdk/zone-less';
import { selectSlice } from '@rx-angular/state';
import { combineLatest, Observable, startWith } from 'rxjs';
import * as THREE from 'three';
type ControlsProto = {
update(): void;
target: THREE.Vector3;
maxDistance: number;
addEventListener: (event: string, callback: (event: unknown) => void) => void;
removeEventListener: (
event: string,
callback: (event: unknown) => void
) => void;
};
export type SizeProps = {
box: THREE.Box3;
size: THREE.Vector3;
center: THREE.Vector3;
distance: number;
};
export interface NgtSobaBoundsState {
group: THREE.Group;
damping: number;
margin: number;
eps: number;
fit: boolean;
clip: boolean;
}
@Injectable()
export class NgtSobaBoundsStore extends EnhancedRxState<
NgtSobaBoundsState,
{ init: void }
> {
#currentAnimating = false;
#currentFocus = new THREE.Vector3();
#currentCamera = new THREE.Vector3();
#currentZoom = 1;
#goalFocus = new THREE.Vector3();
#goalCamera = new THREE.Vector3();
#goalZoom = 1;
#box = new THREE.Box3();
actions = this.create();
constructor(
private store: NgtStore,
private loopService: NgtLoopService,
animationFrameStore: NgtAnimationFrameStore
) {
super();
this.set({
damping: 6,
margin: 1.2,
eps: 0.01,
fit: false,
clip: false,
});
this.holdEffect(
combineLatest([
this.actions.init$,
this.store.select('controls') as unknown as Observable<ControlsProto>,
this.select(selectSlice(['clip', 'fit'])),
]),
([, controls, { clip, fit }]) => {
this.refresh();
if (fit) this.fit();
if (clip) this.clip();
if (controls) {
// Try to prevent drag hijacking
const callback = () => (this.#currentAnimating = false);
controls.addEventListener('start', callback);
return () => controls.removeEventListener('start', callback);
}
return;
}
);
this.holdEffect(this.actions.init$, () => {
const animationUuid = animationFrameStore.register({
callback: ({ delta }) => {
if (this.#currentAnimating) {
const { damping, eps } = this.get();
const camera = this.store.get('camera');
const controls = this.store.get(
'controls'
) as unknown as ControlsProto;
this.#damp(this.#currentFocus, this.#goalFocus, damping, delta);
this.#damp(this.#currentCamera, this.#goalCamera, damping, delta);
this.#currentZoom = THREE.MathUtils.damp(
this.#currentZoom,
this.#goalZoom,
damping,
delta
);
camera.position.copy(this.#currentCamera);
if (this.#isOrthographic(camera)) {
camera.zoom = this.#currentZoom;
camera.updateProjectionMatrix();
}
if (!controls) {
camera.lookAt(this.#currentFocus);
} else {
controls.target.copy(this.#currentFocus);
controls.update();
}
this.loopService.invalidate();
if (
this.#isOrthographic(camera) &&
!(Math.abs(this.#currentZoom - this.#goalZoom) < eps)
)
return;
if (
!this.#isOrthographic(camera) &&
!this.#equals(this.#currentCamera, this.#goalCamera)
)
return;
if (controls && !this.#equals(this.#currentFocus, this.#goalFocus))
return;
this.#currentAnimating = false;
}
},
});
return () => {
animationFrameStore.actions.unsubscriberUuid(animationUuid);
};
});
}
getSize(): SizeProps {
const camera = this.store.get('camera');
const size = this.#box.getSize(new THREE.Vector3());
const center = this.#box.getCenter(new THREE.Vector3());
const maxSize = Math.max(size.x, size.y, size.z);
const fitHeightDistance = this.#isOrthographic(camera)
? maxSize * 4
: maxSize / (2 * Math.atan((Math.PI * camera.fov) / 360));
const fitWidthDistance = this.#isOrthographic(camera)
? maxSize * 4
: fitHeightDistance / camera.aspect;
const distance =
this.get('margin') * Math.max(fitHeightDistance, fitWidthDistance);
return { box: this.#box, size, center, distance };
}
refresh(object?: THREE.Object3D | THREE.Box3) {
const group = this.get('group');
const camera = this.store.get('camera');
const controls = this.store.get('controls') as unknown as ControlsProto;
if (this.#isObject3D(object)) this.#box.setFromObject(object);
else if (this.#isBox3(object)) this.#box.copy(object);
else if (group) this.#box.setFromObject(group);
if (this.#box.isEmpty()) {
const max = camera.position.length() || 10;
this.#box.setFromCenterAndSize(
new THREE.Vector3(),
new THREE.Vector3(max, max, max)
);
}
if (controls?.constructor.name === 'OrthographicTrackballControls') {
const { distance } = this.getSize();
const direction = camera.position
.clone()
.sub(controls.target)
.normalize()
.multiplyScalar(distance);
const newPos = controls.target.clone().add(direction);
camera.position.copy(newPos);
}
return this;
}
clip() {
const camera = this.store.get('camera');
const controls = this.store.get('controls') as unknown as ControlsProto;
const { distance } = this.getSize();
if (controls) controls.maxDistance = distance * 10;
camera.near = distance / 100;
camera.far = distance * 100;
camera.updateProjectionMatrix();
if (controls) controls.update();
return this;
}
fit() {
const { margin, damping } = this.get();
const camera = this.store.get('camera');
const controls = this.store.get('controls') as unknown as ControlsProto;
this.#currentCamera.copy(camera.position);
if (controls) this.#currentFocus.copy(controls.target);
const { center, distance } = this.getSize();
const direction = center
.clone()
.sub(camera.position)
.normalize()
.multiplyScalar(distance);
this.#goalCamera.copy(center).sub(direction);
this.#goalFocus.copy(center);
if (this.#isOrthographic(camera)) {
this.#currentZoom = camera.zoom;
let maxHeight = 0,
maxWidth = 0;
const vertices = [
new THREE.Vector3(this.#box.min.x, this.#box.min.y, this.#box.min.z),
new THREE.Vector3(this.#box.min.x, this.#box.max.y, this.#box.min.z),
new THREE.Vector3(this.#box.min.x, this.#box.min.y, this.#box.max.z),
new THREE.Vector3(this.#box.min.x, this.#box.max.y, this.#box.max.z),
new THREE.Vector3(this.#box.max.x, this.#box.max.y, this.#box.max.z),
new THREE.Vector3(this.#box.max.x, this.#box.max.y, this.#box.min.z),
new THREE.Vector3(this.#box.max.x, this.#box.min.y, this.#box.max.z),
new THREE.Vector3(this.#box.max.x, this.#box.min.y, this.#box.min.z),
];
// Transform the center and each corner to camera space
center.applyMatrix4(camera.matrixWorldInverse);
for (const v of vertices) {
v.applyMatrix4(camera.matrixWorldInverse);
maxHeight = Math.max(maxHeight, Math.abs(v.y - center.y));
maxWidth = Math.max(maxWidth, Math.abs(v.x - center.x));
}
maxHeight *= 2;
maxWidth *= 2;
const zoomForHeight = (camera.top - camera.bottom) / maxHeight;
const zoomForWidth = (camera.right - camera.left) / maxWidth;
this.#goalZoom = Math.min(zoomForHeight, zoomForWidth) / margin;
if (!damping) {
camera.zoom = this.#goalZoom;
camera.updateProjectionMatrix();
}
}
if (damping) {
this.#currentAnimating = true;
} else {
camera.position.copy(this.#goalCamera);
camera.lookAt(this.#goalFocus);
if (controls) {
controls.target.copy(this.#goalFocus);
controls.update();
}
this.loopService.invalidate();
}
// if (onFitRef.current) onFitRef.current(this.getSize());
return this;
}
#equals(a: THREE.Vector3, b: THREE.Vector3) {
const eps = this.get('eps');
return (
Math.abs(a.x - b.x) < eps &&
Math.abs(a.y - b.y) < eps &&
Math.abs(a.z - b.z) < eps
);
}
#damp(v: THREE.Vector3, t: THREE.Vector3, lambda: number, delta: number) {
v.x = THREE.MathUtils.damp(v.x, t.x, lambda, delta);
v.y = THREE.MathUtils.damp(v.y, t.y, lambda, delta);
v.z = THREE.MathUtils.damp(v.z, t.z, lambda, delta);
}
#isOrthographic(camera: THREE.Camera): camera is THREE.OrthographicCamera {
return camera && (camera as THREE.OrthographicCamera).isOrthographicCamera;
}
#isObject3D(object: unknown): object is THREE.Object3D {
return !!object && (object as THREE.Object3D).isObject3D;
}
#isBox3(object: unknown): object is THREE.Box3 {
return !!object && (object as THREE.Box3).isBox3;
}
}
@Component({
selector: 'ngt-soba-bounds',
template: `
<ngt-group
(ready)="object = $event; sobaSoundsStore.set({ group: $event })"
(animateReady)="animateReady.emit({ entity: object, state: $event })"
[object3dInputsController]="objectInputsController"
>
<ng-content></ng-content>
</ngt-group>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
NGT_OBJECT_INPUTS_CONTROLLER_PROVIDER,
NgtSobaBoundsStore,
{
provide: NgtSobaExtender,
useExisting: NgtSobaBounds,
},
],
})
export class NgtSobaBounds extends NgtSobaExtender<THREE.Group> {
@Input() set damping(damping: number) {
this.sobaSoundsStore.set({ damping });
}
@Input() set fit(fit: boolean) {
this.sobaSoundsStore.set({ fit });
}
@Input() set clip(clip: boolean) {
this.sobaSoundsStore.set({ clip });
}
@Input() set margin(margin: number) {
this.sobaSoundsStore.set({ margin });
}
@Input() set eps(eps: number) {
this.sobaSoundsStore.set({ eps });
}
@ContentChildren(NgtObject3dInputsController) set children(
v: QueryList<NgtObject3dInputsController>
) {
requestAnimationFrame(() => {
this.sobaSoundsStore.hold(
combineLatest([
v.changes.pipe(startWith(v)),
this.sobaSoundsStore.select('group'),
]),
([controllers, group]: [
QueryList<NgtObject3dInputsController>,
THREE.Group
]) => {
controllers.forEach((controller) => {
controller.appendTo = () => group;
});
}
);
});
}
constructor(
@Inject(NGT_OBJECT_INPUTS_WATCHED_CONTROLLER)
public objectInputsController: NgtObject3dInputsController,
public sobaSoundsStore: NgtSobaBoundsStore
) {
super();
}
ngOnInit() {
this.sobaSoundsStore.actions.init();
}
}
@NgModule({
declarations: [NgtSobaBounds],
exports: [NgtSobaBounds, NgtObject3dInputsControllerModule],
imports: [NgtGroupModule],
})
export class NgtSobaBoundsModule {} | the_stack |
import { TestOptions, VexFlowTests } from './vexflow_test_helpers';
import { Annotation } from 'annotation';
import { Beam } from 'beam';
import { Bend } from 'bend';
import { Flow } from 'flow';
import { FontGlyph } from 'font';
import { Formatter } from 'formatter';
import { Note } from 'note';
import { Registry } from 'registry';
import { Stave } from 'stave';
import { StaveConnector } from 'staveconnector';
import { StaveNote } from 'stavenote';
import { Voice } from 'voice';
import { MockTickable } from './mocks';
const FormatterTests = {
Start(): void {
QUnit.module('Formatter');
test('TickContext Building', buildTickContexts);
const run = VexFlowTests.runTests;
run('Notehead padding', noteHeadPadding);
run('Justification and alignment with accidentals', accidentalJustification);
run('Long measure taking full space', longMeasureProblems);
run('Vertical alignment - few unaligned beats', unalignedNoteDurations1);
run('Vertical alignment - many unaligned beats', unalignedNoteDurations2, { globalSoftmax: false });
run('Vertical alignment - many unaligned beats (global softmax)', unalignedNoteDurations2, { globalSoftmax: true });
run('StaveNote - Justification', justifyStaveNotes);
run('Notes with Tab', notesWithTab);
run('Multiple Staves - Justified', multiStaves, { debug: true });
run('Softmax', softMax);
run('Mixtime', mixTime);
run('Tight', tightNotes1);
run('Tight 2', tightNotes2);
run('Annotations', annotations);
run('Proportional Formatting - No Justification', proportional, { justify: false, debug: true, iterations: 0 });
run('Proportional Formatting - No Tuning', proportional, { debug: true, iterations: 0 });
run('Proportional Formatting (20 iterations)', proportional, { debug: true, iterations: 20, alpha: 0.5 });
},
};
function buildTickContexts(): void {
function createTickable(beat: number) {
return new MockTickable().setTicks(beat);
}
const BEAT = (1 * Flow.RESOLUTION) / 4;
const tickables1 = [
createTickable(BEAT).setWidth(10),
createTickable(BEAT * 2).setWidth(20),
createTickable(BEAT).setWidth(30),
];
const tickables2 = [
createTickable(BEAT * 2).setWidth(10),
createTickable(BEAT).setWidth(20),
createTickable(BEAT).setWidth(30),
];
const voice1 = new Voice(Flow.TIME4_4);
const voice2 = new Voice(Flow.TIME4_4);
voice1.addTickables(tickables1);
voice2.addTickables(tickables2);
const formatter = new Formatter();
const tContexts = formatter.createTickContexts([voice1, voice2]);
equal(tContexts.list.length, 4, 'Voices should have four tick contexts');
throws(() => formatter.getMinTotalWidth(), /NoMinTotalWidth/, 'Expected to throw exception');
ok(formatter.preCalculateMinTotalWidth([voice1, voice2]), 'Successfully runs preCalculateMinTotalWidth');
equal(formatter.getMinTotalWidth(), 88, 'Get minimum total width without passing voices');
formatter.preFormat();
equal(formatter.getMinTotalWidth(), 88, 'Minimum total width');
equal(tickables1[0].getX(), tickables2[0].getX(), 'First notes of both voices have the same X');
equal(tickables1[2].getX(), tickables2[2].getX(), 'Last notes of both voices have the same X');
ok(
tickables1[1].getX() < tickables2[1].getX(),
'Second note of voice 2 is to the right of the second note of voice 1'
);
}
function noteHeadPadding(options: TestOptions): void {
const registry = new Registry();
Registry.enableDefaultRegistry(registry);
const f = VexFlowTests.makeFactory(options, 600, 300);
const score = f.EasyScore();
score.set({ time: '9/8' });
const notes1 = score.notes('(d5 f5)/8,(c5 e5)/8,(d5 f5)/8,(c5 e5)/2.');
const beams = [new Beam(notes1.slice(0, 3), true)];
const voice1 = new Voice().setMode(Voice.Mode.SOFT);
const notes2 = score.notes('(g4 an4)/2.,(g4 a4)/4.', { clef: 'treble' });
const voice2 = new Voice().setMode(Voice.Mode.SOFT);
voice2.addTickables(notes2);
voice1.addTickables(notes1);
const formatter = f.Formatter().joinVoices([voice1]).joinVoices([voice2]);
const width = formatter.preCalculateMinTotalWidth([voice1, voice2]);
formatter.format([voice1, voice2], width);
const staveWidth = width + Stave.defaultPadding;
const stave1 = f.Stave({ y: 50, width: staveWidth });
const stave2 = f.Stave({ y: 150, width: staveWidth });
stave1.draw();
stave2.draw();
voice1.draw(f.getContext(), stave1);
voice2.draw(f.getContext(), stave2);
beams.forEach((b) => b.setContext(f.getContext()).draw());
ok(true);
}
function longMeasureProblems(options: TestOptions): void {
const registry = new Registry();
Registry.enableDefaultRegistry(registry);
const f = VexFlowTests.makeFactory(options, 1500, 300);
const score = f.EasyScore();
score.set({ time: '4/4' });
const notes1 = score.notes(
'b4/4,b4/8,b4/8,b4/4,b4/4,b4/2,b4/2,b4/4,b4/8,b4/8,b4/4,b4/4,b4/2,b4/2,b4/4,b4/8,b4/8,b4/4,b4/4,b4/2,b4/2,b4/4,b4/2,b4/8,b4/8'
);
const voice1 = new Voice().setMode(Voice.Mode.SOFT);
const notes2 = score.notes(
'd3/4,(ab3 f4)/2,d3/4,ab3/4,d3/2,ab3/4,d3/4,ab3/2,d3/4,ab3/4,d3/2,ab3/4,d3/4,ab3/2,d3/4,ab3/4,d3/2,ab3/4,d4/4,d4/2,d4/4',
{ clef: 'bass' }
);
const voice2 = new Voice().setMode(Voice.Mode.SOFT);
voice2.addTickables(notes2);
voice1.addTickables(notes1);
const formatter = f.Formatter().joinVoices([voice1]).joinVoices([voice2]);
const width = formatter.preCalculateMinTotalWidth([voice1, voice2]);
formatter.format([voice1, voice2], width);
const stave1 = f.Stave({ y: 50, width: width + Stave.defaultPadding });
const stave2 = f.Stave({ y: 200, width: width + Stave.defaultPadding });
stave1.draw();
stave2.draw();
voice1.draw(f.getContext(), stave1);
voice2.draw(f.getContext(), stave2);
ok(true);
}
function accidentalJustification(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 600, 300);
const score = f.EasyScore();
const notes11 = score.notes('a4/2, a4/4, a4/8, ab4/16, an4/16');
const voice11 = score.voice(notes11, { time: '4/4' });
const notes21 = score.notes('c4/2, d4/8, d4/8, e4/8, e4/8');
const voice21 = score.voice(notes21, { time: '4/4' });
let beams = Beam.generateBeams(notes11.slice(2));
beams = beams.concat(beams, Beam.generateBeams(notes21.slice(1, 3)));
beams = beams.concat(Beam.generateBeams(notes21.slice(3)));
const formatter = f.Formatter({ softmaxFactor: 100 }).joinVoices([voice11]).joinVoices([voice21]);
const width = formatter.preCalculateMinTotalWidth([voice11, voice21]);
const stave11 = f.Stave({ y: 20, width: width + Stave.defaultPadding });
const stave21 = f.Stave({ y: 130, width: width + Stave.defaultPadding });
formatter.format([voice11, voice21], width);
const ctx = f.getContext();
stave11.setContext(ctx).draw();
stave21.setContext(ctx).draw();
voice11.draw(ctx, stave11);
voice21.draw(ctx, stave21);
beams.forEach((b) => b.setContext(ctx).draw());
ok(true);
}
function unalignedNoteDurations1(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 600, 250);
const score = f.EasyScore();
const notes11 = [
new StaveNote({ keys: ['a/4'], duration: '8' }),
new StaveNote({ keys: ['b/4'], duration: '4' }),
new StaveNote({ keys: ['b/4'], duration: '8' }),
];
const notes21 = [
new StaveNote({ keys: ['a/4'], duration: '16' }),
new StaveNote({ keys: ['b/4.'], duration: '4' }),
new StaveNote({ keys: ['a/4'], duration: '8d' }).addDotToAll(),
];
const ctx = f.getContext();
const voice11 = score.voice(notes11, { time: '2/4' }).setMode(Voice.Mode.SOFT);
const voice21 = score.voice(notes21, { time: '2/4' }).setMode(Voice.Mode.SOFT);
const beams21 = Beam.generateBeams(notes21);
const beams11 = Beam.generateBeams(notes11);
const formatter = new Formatter();
formatter.joinVoices([voice11]);
formatter.joinVoices([voice21]);
const width = formatter.preCalculateMinTotalWidth([voice11, voice21]);
const stave11 = f.Stave({ y: 20, width: width + Stave.defaultPadding });
const stave21 = f.Stave({ y: 130, width: width + Stave.defaultPadding });
formatter.format([voice11, voice21], width);
stave11.setContext(ctx).draw();
stave21.setContext(ctx).draw();
voice11.draw(ctx, stave11);
voice21.draw(ctx, stave21);
beams21.forEach((b) => b.setContext(ctx).draw());
beams11.forEach((b) => b.setContext(ctx).draw());
ok(voice11.getTickables()[1].getX() > voice21.getTickables()[1].getX());
}
function unalignedNoteDurations2(options: TestOptions): void {
const notes1 = [
new StaveNote({ keys: ['b/4'], duration: '8r' }),
new StaveNote({ keys: ['g/4'], duration: '16' }),
new StaveNote({ keys: ['c/5'], duration: '16' }),
new StaveNote({ keys: ['e/5'], duration: '16' }),
new StaveNote({ keys: ['g/4'], duration: '16' }),
new StaveNote({ keys: ['c/5'], duration: '16' }),
new StaveNote({ keys: ['e/5'], duration: '16' }),
new StaveNote({ keys: ['b/4'], duration: '8r' }),
new StaveNote({ keys: ['g/4'], duration: '16' }),
new StaveNote({ keys: ['c/5'], duration: '16' }),
new StaveNote({ keys: ['e/5'], duration: '16' }),
new StaveNote({ keys: ['g/4'], duration: '16' }),
new StaveNote({ keys: ['c/5'], duration: '16' }),
new StaveNote({ keys: ['e/5'], duration: '16' }),
];
const notes2 = [
new StaveNote({ keys: ['a/4'], duration: '16r' }),
new StaveNote({ keys: ['e/4.'], duration: '8d' }),
new StaveNote({ keys: ['e/4'], duration: '4' }),
new StaveNote({ keys: ['a/4'], duration: '16r' }),
new StaveNote({ keys: ['e/4.'], duration: '8d' }),
new StaveNote({ keys: ['e/4'], duration: '4' }),
];
const f = VexFlowTests.makeFactory(options, 750, 280);
const context = f.getContext();
const voice1 = new Voice({ num_beats: 4, beat_value: 4 });
voice1.addTickables(notes1);
const voice2 = new Voice({ num_beats: 4, beat_value: 4 });
voice2.addTickables(notes2);
const formatter = new Formatter({ softmaxFactor: 100, globalSoftmax: options.params.globalSoftmax });
formatter.joinVoices([voice1]);
formatter.joinVoices([voice2]);
const width = formatter.preCalculateMinTotalWidth([voice1, voice2]);
formatter.format([voice1, voice2], width);
const stave1 = new Stave(10, 40, width + Stave.defaultPadding);
const stave2 = new Stave(10, 100, width + Stave.defaultPadding);
stave1.setContext(context).draw();
stave2.setContext(context).draw();
voice1.draw(context, stave1);
voice2.draw(context, stave2);
ok(voice1.getTickables()[1].getX() > voice2.getTickables()[1].getX());
}
function justifyStaveNotes(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 520, 280);
const ctx = f.getContext();
const score = f.EasyScore();
let y = 30;
function justifyToWidth(width: number) {
f.Stave({ y: y }).addClef('treble');
const voices = [
score.voice(score.notes('(cbb4 en4 a4)/2, (d4 e4 f4)/8, (d4 f4 a4)/8, (cn4 f#4 a4)/4', { stem: 'down' })),
score.voice(score.notes('(bb4 e#5 a5)/4, (d5 e5 f5)/2, (c##5 fb5 a5)/4', { stem: 'up' })),
];
f.Formatter().joinVoices(voices).format(voices, width);
// Show the the width of notes via a horizontal line with red, green, yellow, blue, gray indicators.
voices[0].getTickables().forEach((note) => Note.plotMetrics(ctx, note, y + 140)); // Bottom line.
voices[1].getTickables().forEach((note) => Note.plotMetrics(ctx, note, y - 20)); // Top Line
y += 210;
}
justifyToWidth(520);
f.draw();
ok(true);
}
function notesWithTab(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 420, 580);
const score = f.EasyScore();
let y = 10;
function justifyToWidth(width: number) {
const stave = f.Stave({ y: y }).addClef('treble');
const voice = score.voice(score.notes('d#4/2, (c4 d4)/8, d4/8, (c#4 e4 a4)/4', { stem: 'up' }));
y += 100;
f.TabStave({ y: y }).addTabGlyph().setNoteStartX(stave.getNoteStartX());
const tabVoice = score.voice([
f.TabNote({ positions: [{ str: 3, fret: 6 }], duration: '2' }).addModifier(new Bend('Full'), 0),
f
.TabNote({
positions: [
{ str: 2, fret: 3 },
{ str: 3, fret: 5 },
],
duration: '8',
})
.addModifier(new Bend('Unison'), 1),
f.TabNote({ positions: [{ str: 3, fret: 7 }], duration: '8' }),
f.TabNote({
positions: [
{ str: 3, fret: 6 },
{ str: 4, fret: 7 },
{ str: 2, fret: 5 },
],
duration: '4',
}),
]);
f.Formatter().joinVoices([voice]).joinVoices([tabVoice]).format([voice, tabVoice], width);
y += 150;
}
justifyToWidth(0);
justifyToWidth(300);
f.draw();
ok(true);
}
function multiStaves(options: TestOptions): void {
// Two helper functions to calculate the glyph's width.
// Should these be static methods in Glyph or Font?
function glyphPixels(): number {
return 96 * (38 / (Flow.DEFAULT_FONT_STACK[0].getResolution() * 72));
}
function glyphWidth(vexGlyph: string): number {
const glyph: FontGlyph = Flow.DEFAULT_FONT_STACK[0].getGlyphs()[vexGlyph];
return (glyph.x_max - glyph.x_min) * glyphPixels();
}
const f = VexFlowTests.makeFactory(options, 600, 400);
const ctx = f.getContext();
const score = f.EasyScore();
//////////////////////////////////////////////////////////////////////////////////////////////////
// Draw 3 Staves (one measure each).
const notes11 = score.notes('f4/4, d4/8, g4/4, eb4/8');
const notes21 = score.notes('d4/8, d4, d4, d4, e4, eb4');
const notes31 = score.notes('a5/8, a5, a5, a5, a5, a5', { stem: 'down' });
let voices = [
score.voice(notes11, { time: '6/8' }),
score.voice(notes21, { time: '6/8' }),
score.voice(notes31, { time: '6/8' }),
];
let formatter = f.Formatter();
voices.forEach((v) => formatter.joinVoices([v]));
let width = formatter.preCalculateMinTotalWidth(voices);
formatter.format(voices, width);
let beams = [
new Beam(notes21.slice(0, 3), true),
new Beam(notes21.slice(3, 6), true),
new Beam(notes31.slice(0, 3), true),
new Beam(notes31.slice(3, 6), true),
];
const staveYs = [20, 130, 250];
let staveWidth = width + glyphWidth('gClef') + glyphWidth('timeSig8') + Stave.defaultPadding;
let staves = [
f.Stave({ y: staveYs[0], width: staveWidth }).addClef('treble').addTimeSignature('6/8'),
f.Stave({ y: staveYs[1], width: staveWidth }).addClef('treble').addTimeSignature('6/8'),
f.Stave({ y: staveYs[2], width: staveWidth }).addClef('bass').addTimeSignature('6/8'),
];
f.StaveConnector({
top_stave: staves[1],
bottom_stave: staves[2],
type: 'brace',
});
for (let i = 0; i < staves.length; ++i) {
staves[i].setContext(ctx).draw();
voices[i].draw(ctx, staves[i]);
}
beams.forEach((beam) => beam.setContext(ctx).draw());
//////////////////////////////////////////////////////////////////////////////////////////////////
// Draw 3 more staves (one measure each).
// These are adjacent to the first set of staves, representing the second measure of each stave.
const notes12 = score.notes('ab4/4, bb4/8, (cb5 eb5)/4[stem="down"], d5/8[stem="down"]');
const notes22 = score.notes('(eb4 ab4)/4., (c4 eb4 ab4)/4, db5/8', { stem: 'up' });
const notes32 = score.notes('a5/8, a5, a5, a5, a5, a5', { stem: 'down' });
voices = [
score.voice(notes12, { time: '6/8' }),
score.voice(notes22, { time: '6/8' }),
score.voice(notes32, { time: '6/8' }),
];
formatter = f.Formatter();
voices.forEach((v) => formatter.joinVoices([v]));
width = formatter.preCalculateMinTotalWidth(voices);
const staveX = staves[0].getX() + staves[0].getWidth();
staveWidth = width + Stave.defaultPadding;
staves = [
f.Stave({ x: staveX, y: staveYs[0], width: staveWidth }),
f.Stave({ x: staveX, y: staveYs[1], width: staveWidth }),
f.Stave({ x: staveX, y: staveYs[2], width: staveWidth }),
];
formatter.format(voices, width);
beams = [
// Add beams to each group of 3 notes.
new Beam(notes32.slice(0, 3), true),
new Beam(notes32.slice(3, 6), true),
];
for (let i = 0; i < staves.length; ++i) {
staves[i].setContext(ctx).draw();
voices[i].draw(ctx, staves[i]);
voices[i].getTickables().forEach((note) => Note.plotMetrics(ctx, note, staveYs[i] - 20));
}
beams.forEach((beam) => beam.setContext(ctx).draw());
ok(true);
}
function proportional(options: TestOptions): void {
const debug = options.params.debug;
Registry.enableDefaultRegistry(new Registry());
const f = VexFlowTests.makeFactory(options, 650, 750);
const system = f.System({
x: 50,
autoWidth: true,
debugFormatter: debug,
noJustification: !(options.params.justify === undefined && true),
formatIterations: options.params.iterations,
details: { alpha: options.params.alpha },
});
const score = f.EasyScore();
const voices = [
score.notes('c5/8, c5'),
score.tuplet(score.notes('a4/8, a4, a4'), { notes_occupied: 2 }),
score.notes('c5/16, c5, c5, c5'),
score.tuplet(score.notes('a4/16, a4, a4, a4, a4'), { notes_occupied: 4 }),
score.tuplet(score.notes('a4/32, a4, a4, a4, a4, a4, a4'), { notes_occupied: 8 }),
];
const createVoice = (notes: StaveNote[]) => score.voice(notes, { time: '1/4' });
const createStave = (voice: Voice) =>
system
.addStave({ voices: [voice], debugNoteMetrics: debug })
.addClef('treble')
.addTimeSignature('1/4');
voices.map(createVoice).forEach(createStave);
system.addConnector().setType(StaveConnector.type.BRACKET);
f.draw();
// Debugging: Show how many elements of each type we have added.
// const typeMap = Registry.getDefaultRegistry().index.type;
// const table = Object.keys(typeMap).map((typeName) => typeName + ': ' + Object.keys(typeMap[typeName]).length);
// console.log(table);
Registry.disableDefaultRegistry();
ok(true);
}
function softMax(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 550, 500);
f.getContext().scale(0.8, 0.8);
function draw(y: number, factor: number): void {
const score = f.EasyScore();
const system = f.System({
x: 100,
y,
details: { softmaxFactor: factor },
autoWidth: true,
});
system
.addStave({
voices: [
score.voice(
score
.notes('C#5/h, a4/q')
.concat(score.beam(score.notes('Abb4/8, A4/8')))
.concat(score.beam(score.notes('A4/16, A#4, A4, Ab4/32, A4'))),
{ time: '5/4' }
),
],
})
.addClef('treble')
.addTimeSignature('5/4');
f.draw();
ok(true);
}
draw(50, 1);
draw(150, 2);
draw(250, 10);
draw(350, 20);
draw(450, 200);
}
function mixTime(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 400 + Stave.defaultPadding, 250);
f.getContext().scale(0.8, 0.8);
const score = f.EasyScore();
const system = f.System({
details: { softmaxFactor: 100 },
autoWidth: true,
debugFormatter: true,
});
system
.addStave({
voices: [score.voice(score.notes('C#5/q, B4').concat(score.beam(score.notes('A4/8, E4, C4, D4'))))],
})
.addClef('treble')
.addTimeSignature('4/4');
system
.addStave({
voices: [score.voice(score.notes('C#5/q, B4, B4').concat(score.tuplet(score.beam(score.notes('A4/8, E4, C4')))))],
})
.addClef('treble')
.addTimeSignature('4/4');
f.draw();
ok(true);
}
function tightNotes1(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 440, 250);
f.getContext().scale(0.8, 0.8);
const score = f.EasyScore();
const system = f.System({
autoWidth: true,
debugFormatter: true,
details: { maxIterations: 10 },
});
system
.addStave({
voices: [
score.voice(score.beam(score.notes('B4/16, B4, B4, B4, B4, B4, B4, B4')).concat(score.notes('B4/q, B4'))),
],
})
.addClef('treble')
.addTimeSignature('4/4');
system
.addStave({
voices: [
score.voice(score.notes('B4/q, B4').concat(score.beam(score.notes('B4/16, B4, B4, B4, B4, B4, B4, B4')))),
],
})
.addClef('treble')
.addTimeSignature('4/4');
f.draw();
ok(true);
}
function tightNotes2(options: TestOptions): void {
const f = VexFlowTests.makeFactory(options, 440, 250);
f.getContext().scale(0.8, 0.8);
const score = f.EasyScore();
const system = f.System({
autoWidth: true,
debugFormatter: true,
});
system
.addStave({
voices: [
score.voice(score.beam(score.notes('B4/16, B4, B4, B4, B4, B4, B4, B4')).concat(score.notes('B4/q, B4'))),
],
})
.addClef('treble')
.addTimeSignature('4/4');
system
.addStave({
voices: [score.voice(score.notes('B4/w'))],
})
.addClef('treble')
.addTimeSignature('4/4');
f.draw();
ok(true);
}
function annotations(options: TestOptions): void {
const pageWidth = 916;
const pageHeight = 600;
const f = VexFlowTests.makeFactory(options, pageWidth, pageHeight);
const context = f.getContext();
const lyrics1 = ['ipso', 'ipso-', 'ipso', 'ipso', 'ipsoz', 'ipso-', 'ipso', 'ipso', 'ipso', 'ip', 'ipso'];
const lyrics2 = ['ipso', 'ipso-', 'ipsoz', 'ipso', 'ipso', 'ipso-', 'ipso', 'ipso', 'ipso', 'ip', 'ipso'];
const smar = [
{
sm: 5,
width: 550,
lyrics: lyrics1,
title: '550px,softMax:5',
},
{
sm: 10,
width: 550,
lyrics: lyrics2,
title: '550px,softmax:10,different word order',
},
{
sm: 5,
width: 550,
lyrics: lyrics2,
title: '550px,softmax:5',
},
{
sm: 100,
width: 550,
lyrics: lyrics2,
title: '550px,softmax:100',
},
];
const rowSize = 140;
const beats = 12;
const beatsPer = 8;
const beamGroup = 3;
const durations = ['8d', '16', '8', '8d', '16', '8', '8d', '16', '8', '4', '8'];
const beams: Beam[] = [];
let y = 40;
smar.forEach((sm) => {
const stave = new Stave(10, y, sm.width);
const notes: StaveNote[] = [];
let iii = 0;
context.fillText(sm.title, 100, y);
y += rowSize;
durations.forEach((dd) => {
const note = new StaveNote({ keys: ['b/4'], duration: dd });
if (dd.indexOf('d') >= 0) {
note.addDotToAll();
}
if (sm.lyrics.length > iii) {
note.addAnnotation(
0,
new Annotation(sm.lyrics[iii])
.setVerticalJustification(Annotation.VerticalJustify.BOTTOM)
.setFont('Times', 12, 'normal')
);
}
notes.push(note);
iii += 1;
});
notes.forEach((note) => {
if (note.getDuration().indexOf('d') >= 0) {
note.addDotToAll();
}
});
// Don't beam the last group
let notesToBeam: StaveNote[] = [];
notes.forEach((note) => {
if (note.getIntrinsicTicks() < 4096) {
notesToBeam.push(note);
if (notesToBeam.length >= beamGroup) {
beams.push(new Beam(notesToBeam));
notesToBeam = [];
}
} else {
notesToBeam = [];
}
});
const voice1 = new Voice({ num_beats: beats, beat_value: beatsPer }).setMode(Voice.Mode.SOFT).addTickables(notes);
const fmt = new Formatter({ softmaxFactor: sm.sm, maxIterations: 2 }).joinVoices([voice1]);
fmt.format([voice1], sm.width - 11);
stave.setContext(context).draw();
voice1.draw(context, stave);
beams.forEach((b) => b.setContext(context).draw());
});
ok(true);
}
export { FormatterTests }; | the_stack |
import { Contracts, Utils as AppUtils } from "@arkecosystem/core-kernel";
import {
Builders as MagistrateBuilders,
Interfaces as MagistrateInterfaces,
} from "@arkecosystem/core-magistrate-crypto";
import { Identities, Interfaces, Managers, Transactions, Types, Utils } from "@arkecosystem/crypto";
import secrets from "../internal/passphrases.json";
import { getWalletNonce } from "./generic";
const defaultPassphrase: string = secrets[0];
interface IPassphrasePair {
passphrase: string;
secondPassphrase: string;
}
// todo: replace this by the use of real factories
export class TransactionFactory {
protected builder: any;
protected app: Contracts.Kernel.Application;
private network: Types.NetworkName = "testnet";
private networkConfig: Interfaces.NetworkConfig | undefined;
private nonce: Utils.BigNumber | undefined;
private fee: Utils.BigNumber | undefined;
private timestamp: number | undefined;
private passphrase: string = defaultPassphrase;
private secondPassphrase: string | undefined;
private passphraseList: string[] | undefined;
private passphrasePairs: IPassphrasePair[] | undefined;
private version: number | undefined;
private senderPublicKey: string | undefined;
private expiration: number | undefined;
private vendorField: string | undefined;
protected constructor(app?: Contracts.Kernel.Application) {
// @ts-ignore - this is only needed because of the "getNonce"
// method so we don't care if it is undefined in certain scenarios
this.app = app;
}
public static initialize(app?: Contracts.Kernel.Application): TransactionFactory {
return new TransactionFactory(app);
}
public transfer(recipientId?: string, amount: number = 2 * 1e8, vendorField?: string): TransactionFactory {
const builder = Transactions.BuilderFactory.transfer()
.amount(Utils.BigNumber.make(amount).toFixed())
.recipientId(recipientId || Identities.Address.fromPassphrase(defaultPassphrase));
if (vendorField) {
builder.vendorField(vendorField);
}
this.builder = builder;
return this;
}
public secondSignature(secondPassphrase?: string): TransactionFactory {
this.builder = Transactions.BuilderFactory.secondSignature().signatureAsset(
secondPassphrase || defaultPassphrase,
);
return this;
}
public delegateRegistration(username?: string): TransactionFactory {
const builder = Transactions.BuilderFactory.delegateRegistration();
if (username) {
builder.usernameAsset(username);
}
this.builder = builder;
return this;
}
public delegateResignation(): TransactionFactory {
this.builder = Transactions.BuilderFactory.delegateResignation();
return this;
}
public vote(publicKey?: string): TransactionFactory {
this.builder = Transactions.BuilderFactory.vote().votesAsset([
`+${publicKey || Identities.PublicKey.fromPassphrase(defaultPassphrase)}`,
]);
return this;
}
public unvote(publicKey?: string): TransactionFactory {
this.builder = Transactions.BuilderFactory.vote().votesAsset([
`-${publicKey || Identities.PublicKey.fromPassphrase(defaultPassphrase)}`,
]);
return this;
}
public multiSignature(participants?: string[], min?: number): TransactionFactory {
let passphrases: string[] | undefined;
if (!participants) {
passphrases = [secrets[0], secrets[1], secrets[2]];
}
participants = participants || [
Identities.PublicKey.fromPassphrase(secrets[0]),
Identities.PublicKey.fromPassphrase(secrets[1]),
Identities.PublicKey.fromPassphrase(secrets[2]),
];
this.builder = Transactions.BuilderFactory.multiSignature().multiSignatureAsset({
publicKeys: participants,
min: min || participants.length,
});
if (passphrases) {
this.withPassphraseList(passphrases);
}
this.withSenderPublicKey(participants[0]);
return this;
}
public ipfs(ipfsId: string): TransactionFactory {
this.builder = Transactions.BuilderFactory.ipfs().ipfsAsset(ipfsId);
return this;
}
public htlcLock(
lockAsset: Interfaces.IHtlcLockAsset,
recipientId?: string,
amount: number = 2 * 1e8,
): TransactionFactory {
const builder = Transactions.BuilderFactory.htlcLock()
.htlcLockAsset(lockAsset)
.amount(Utils.BigNumber.make(amount).toFixed())
.recipientId(recipientId || Identities.Address.fromPassphrase(defaultPassphrase));
this.builder = builder;
return this;
}
public htlcClaim(claimAsset: Interfaces.IHtlcClaimAsset): TransactionFactory {
this.builder = Transactions.BuilderFactory.htlcClaim().htlcClaimAsset(claimAsset);
return this;
}
public htlcRefund(refundAsset: Interfaces.IHtlcRefundAsset): TransactionFactory {
this.builder = Transactions.BuilderFactory.htlcRefund().htlcRefundAsset(refundAsset);
return this;
}
public multiPayment(payments: Array<{ recipientId: string; amount: string }>): TransactionFactory {
const builder = Transactions.BuilderFactory.multiPayment();
for (const payment of payments) {
builder.addPayment(payment.recipientId, payment.amount);
}
this.builder = builder;
return this;
}
public businessRegistration(
businessRegistrationAsset: MagistrateInterfaces.IBusinessRegistrationAsset,
): TransactionFactory {
const businessRegistrationBuilder = new MagistrateBuilders.BusinessRegistrationBuilder();
businessRegistrationBuilder.businessRegistrationAsset(businessRegistrationAsset);
this.builder = businessRegistrationBuilder;
return this;
}
public businessResignation(): TransactionFactory {
this.builder = new MagistrateBuilders.BusinessResignationBuilder();
return this;
}
public businessUpdate(businessUpdateAsset: MagistrateInterfaces.IBusinessUpdateAsset): TransactionFactory {
const businessUpdateBuilder = new MagistrateBuilders.BusinessUpdateBuilder();
businessUpdateBuilder.businessUpdateAsset(businessUpdateAsset);
this.builder = businessUpdateBuilder;
return this;
}
public bridgechainRegistration(
bridgechainRegistrationAsset: MagistrateInterfaces.IBridgechainRegistrationAsset,
): TransactionFactory {
const bridgechainRegistrationBuilder = new MagistrateBuilders.BridgechainRegistrationBuilder();
bridgechainRegistrationBuilder.bridgechainRegistrationAsset(bridgechainRegistrationAsset);
this.builder = bridgechainRegistrationBuilder;
return this;
}
public bridgechainResignation(registeredBridgechainId: string): TransactionFactory {
const bridgechainResignationBuilder = new MagistrateBuilders.BridgechainResignationBuilder();
bridgechainResignationBuilder.bridgechainResignationAsset(registeredBridgechainId);
this.builder = bridgechainResignationBuilder;
return this;
}
public bridgechainUpdate(bridgechainUpdateAsset: MagistrateInterfaces.IBridgechainUpdateAsset): TransactionFactory {
const bridgechainUpdateBuilder = new MagistrateBuilders.BridgechainUpdateBuilder();
bridgechainUpdateBuilder.bridgechainUpdateAsset(bridgechainUpdateAsset);
this.builder = bridgechainUpdateBuilder;
return this;
}
public entity(entityAsset: MagistrateInterfaces.IEntityAsset): TransactionFactory {
const entityBuilder = new MagistrateBuilders.EntityBuilder();
entityBuilder.asset(entityAsset);
this.builder = entityBuilder;
return this;
}
public withFee(fee: number): TransactionFactory {
this.fee = Utils.BigNumber.make(fee);
return this;
}
public withTimestamp(timestamp: number): TransactionFactory {
this.timestamp = timestamp;
return this;
}
public withNetwork(network: Types.NetworkName): TransactionFactory {
this.network = network;
return this;
}
public withNetworkConfig(networkConfig: Interfaces.NetworkConfig): TransactionFactory {
this.networkConfig = networkConfig;
return this;
}
public withHeight(height: number): TransactionFactory {
Managers.configManager.setHeight(height);
return this;
}
public withSenderPublicKey(sender: string): TransactionFactory {
this.senderPublicKey = sender;
return this;
}
public withNonce(nonce: Utils.BigNumber): TransactionFactory {
this.nonce = nonce;
return this;
}
public withExpiration(expiration: number): TransactionFactory {
this.expiration = expiration;
return this;
}
public withVersion(version: number): TransactionFactory {
this.version = version;
return this;
}
public withVendorField(vendorField: string): TransactionFactory {
this.vendorField = vendorField;
return this;
}
public withPassphrase(passphrase: string): TransactionFactory {
this.passphrase = passphrase;
return this;
}
public withSecondPassphrase(secondPassphrase: string): TransactionFactory {
this.secondPassphrase = secondPassphrase;
return this;
}
public withPassphraseList(passphrases: string[]): TransactionFactory {
this.passphraseList = passphrases;
return this;
}
public withPassphrasePair(passphrases: IPassphrasePair): TransactionFactory {
this.passphrase = passphrases.passphrase;
this.secondPassphrase = passphrases.secondPassphrase;
return this;
}
public withPassphrasePairs(passphrases: IPassphrasePair[]): TransactionFactory {
this.passphrasePairs = passphrases;
return this;
}
public create(quantity = 1): Interfaces.ITransactionData[] {
return this.make<Interfaces.ITransactionData>(quantity, "getStruct");
}
public createOne(): Interfaces.ITransactionData {
return this.create(1)[0];
}
public build(quantity = 1): Interfaces.ITransaction[] {
return this.make<Interfaces.ITransaction>(quantity, "build");
}
public getNonce(): Utils.BigNumber {
if (this.nonce) {
return this.nonce;
}
AppUtils.assert.defined<string>(this.senderPublicKey);
return getWalletNonce(this.app, this.senderPublicKey);
}
/* istanbul ignore next */
private make<T>(quantity = 1, method: string): T[] {
if (this.passphrasePairs && this.passphrasePairs.length) {
return this.passphrasePairs.map(
(passphrasePair: IPassphrasePair) =>
this.withPassphrase(passphrasePair.passphrase)
.withSecondPassphrase(passphrasePair.secondPassphrase)
.sign<T>(quantity, method)[0],
);
}
return this.sign<T>(quantity, method);
}
private sign<T>(quantity: number, method: string): T[] {
if (this.networkConfig !== undefined) {
Managers.configManager.setConfig(this.networkConfig);
} else {
Managers.configManager.setFromPreset(this.network);
}
// // ensure we use aip11
// Managers.configManager.getMilestone().aip11 = true;
// this.builder.data.version = 2;
if (!this.senderPublicKey) {
this.senderPublicKey = Identities.PublicKey.fromPassphrase(this.passphrase);
}
const transactions: T[] = [];
let nonce = this.getNonce();
for (let i = 0; i < quantity; i++) {
if (this.builder.constructor.name === "TransferBuilder") {
// @FIXME: when we use any of the "withPassphrase*" methods the builder will
// always remember the previous vendor field instead generating a new one on each iteration
const vendorField: string = this.builder.data.vendorField;
if (!vendorField || (vendorField && vendorField.startsWith("Test Transaction"))) {
this.builder.vendorField(`Test Transaction ${i + 1}`);
}
}
if (this.builder.constructor.name === "DelegateRegistrationBuilder") {
// @FIXME: when we use any of the "withPassphrase*" methods the builder will
// always remember the previous username instead generating a new one on each iteration
if (!this.builder.data.asset.delegate.username) {
this.builder = Transactions.BuilderFactory.delegateRegistration().usernameAsset(
this.getRandomUsername(),
);
}
}
if (this.version) {
this.builder.version(this.version);
}
if (this.builder.data.version > 1) {
nonce = nonce.plus(1);
this.builder.nonce(nonce);
}
if (this.fee) {
this.builder.fee(this.fee.toFixed());
}
if (this.timestamp) {
this.builder.data.timestamp = this.timestamp;
}
if (this.expiration) {
this.builder.expiration(this.expiration);
}
if (this.vendorField) {
this.builder.vendorField(this.vendorField);
}
this.builder.senderPublicKey(this.senderPublicKey);
const isDevelop: boolean = !["mainnet", "devnet"].includes(Managers.configManager.get("network.name"));
const aip11: boolean = Managers.configManager.getMilestone().aip11;
const htlcEnabled: boolean = Managers.configManager.getMilestone().htlcEnabled;
if (this.builder.data.version === 1 && aip11) {
Managers.configManager.getMilestone().aip11 = false;
Managers.configManager.getMilestone().htlcEnabled = false;
} /* istanbul ignore else */ else if (isDevelop) {
Managers.configManager.getMilestone().aip11 = true;
Managers.configManager.getMilestone().htlcEnabled = htlcEnabled;
}
let sign = true;
if (this.passphraseList && this.passphraseList.length) {
for (let i = 0; i < this.passphraseList.length; i++) {
this.builder.multiSign(this.passphraseList[i], i);
}
sign = this.builder.constructor.name === "MultiSignatureBuilder";
}
if (sign) {
this.builder.sign(this.passphrase);
if (this.secondPassphrase) {
this.builder.secondSign(this.secondPassphrase);
}
}
const transaction = this.builder[method]();
/* istanbul ignore else */
if (isDevelop) {
Managers.configManager.getMilestone().aip11 = true;
Managers.configManager.getMilestone().htlcEnabled = true;
}
transactions.push(transaction);
}
return transactions;
}
private getRandomUsername(): string {
return Math.random().toString(36).toLowerCase();
}
} | the_stack |
import {
attr,
nullableNumberConverter,
SyntheticViewTemplate,
} from "@microsoft/fast-element";
import { keyEnter } from "@microsoft/fast-web-utilities";
import type { StartEndOptions } from "..";
import { FoundationElement } from "../foundation-element";
import type {
FoundationElementDefinition,
FoundationElementTemplate,
} from "../foundation-element";
import type { DayFormat, MonthFormat, WeekdayFormat, YearFormat } from "./date-formatter";
import { DateFormatter } from "./date-formatter";
/**
* Information about a month
* @public
*/
export type MonthInfo = {
month: number;
year: number;
length: number;
start: number;
};
/**
* Calendar information needed for rendering
* including the next and previous months
* @public
*/
export type CalendarInfo = MonthInfo & {
previous: MonthInfo;
next: MonthInfo;
};
/**
* Caldendar date info
* used to represent a date
* @public
*/
export type CalendarDateInfo = {
day: number;
month: number;
year: number;
disabled?: boolean;
selected?: boolean;
};
/**
* Calendar configuration options
* @public
*/
export type CalendarOptions = FoundationElementDefinition &
StartEndOptions & {
title?:
| FoundationElementTemplate<
SyntheticViewTemplate<any, Calendar>,
CalendarOptions
>
| SyntheticViewTemplate
| string;
};
/**
* Calendar component
* @public
*/
export class Calendar extends FoundationElement {
/**
* date formatter utitlity for getting localized strings
* @public
*/
public dateFormatter: DateFormatter = new DateFormatter();
/**
* Readonly attribute for turning off data-grid
* @public
*/
@attr({ mode: "boolean" })
public readonly: boolean = false;
/**
* String repesentation of the full locale including market, calendar type and numbering system
* @public
*/
@attr
public locale: string = "en-US";
private localeChanged(): void {
this.dateFormatter.locale = this.locale;
}
/**
* Month to display
* @public
*/
@attr({ converter: nullableNumberConverter })
public month: number = new Date().getMonth() + 1;
/**
* Year of the month to display
* @public
*/
@attr({ converter: nullableNumberConverter })
public year: number = new Date().getFullYear();
/**
* Format style for the day
* @public
*/
@attr({ attribute: "day-format", mode: "fromView" })
public dayFormat: DayFormat = "numeric";
private dayFormatChanged(): void {
this.dateFormatter.dayFormat = this.dayFormat;
}
/**
* Format style for the week day labels
* @public
*/
@attr({ attribute: "weekday-format", mode: "fromView" })
public weekdayFormat: WeekdayFormat = "short";
private weekdayFormatChanged(): void {
this.dateFormatter.weekdayFormat = this.weekdayFormat;
}
/**
* Format style for the month label
* @public
*/
@attr({ attribute: "month-format", mode: "fromView" })
public monthFormat: MonthFormat = "long";
private monthFormatChanged(): void {
this.dateFormatter.monthFormat = this.monthFormat;
}
/**
* Format style for the year used in the title
* @public
*/
@attr({ attribute: "year-format", mode: "fromView" })
public yearFormat: YearFormat = "numeric";
private yearFormatChanged(): void {
this.dateFormatter.yearFormat = this.yearFormat;
}
/**
* Minimum number of weeks to show for the month
* This can be used to normalize the calendar view
* when changing or across multiple calendars
* @public
*/
@attr({ attribute: "min-weeks", converter: nullableNumberConverter })
public minWeeks: number = 0;
/**
* A list of dates that should be shown as disabled
* @public
*/
@attr({ attribute: "disabled-dates" })
public disabledDates: string = "";
/**
* A list of dates that should be shown as highlighted
* @public
*/
@attr({ attribute: "selected-dates" })
public selectedDates: string = "";
/**
* The number of miliseconds in a day
* @internal
*/
private oneDayInMs: number = 86400000;
/**
* Gets data needed to render about a calendar month as well as the previous and next months
* @param year - year of the calendar
* @param month - month of the calendar
* @returns - an object with data about the current and 2 surrounding months
* @public
*/
public getMonthInfo(
month: number = this.month,
year: number = this.year
): CalendarInfo {
const getFirstDay: (Date) => number = (date: Date) =>
new Date(date.getFullYear(), date.getMonth(), 1).getDay();
const getLength = date => {
const nextMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1);
return new Date(nextMonth.getTime() - this.oneDayInMs).getDate();
};
const thisMonth: Date = new Date(year, month - 1);
const nextMonth: Date = new Date(year, month);
const previousMonth: Date = new Date(year, month - 2);
return {
length: getLength(thisMonth),
month,
start: getFirstDay(thisMonth),
year,
previous: {
length: getLength(previousMonth),
month: previousMonth.getMonth() + 1,
start: getFirstDay(previousMonth),
year: previousMonth.getFullYear(),
},
next: {
length: getLength(nextMonth),
month: nextMonth.getMonth() + 1,
start: getFirstDay(nextMonth),
year: nextMonth.getFullYear(),
},
};
}
/**
* A list of calendar days
* @param info - an object containing the information needed to render a calendar month
* @param minWeeks - minimum number of weeks to show
* @returns a list of days in a calendar month
* @public
*/
public getDays(
info: CalendarInfo = this.getMonthInfo(),
minWeeks: number = this.minWeeks
): CalendarDateInfo[][] {
minWeeks = minWeeks > 10 ? 10 : minWeeks;
const { start, length, previous, next } = info;
const days: CalendarDateInfo[][] = [];
let dayCount = 1 - start;
while (
dayCount < length + 1 ||
days.length < minWeeks ||
days[days.length - 1].length % 7 !== 0
) {
const { month, year } =
dayCount < 1 ? previous : dayCount > length ? next : info;
const day =
dayCount < 1
? previous.length + dayCount
: dayCount > length
? dayCount - length
: dayCount;
const dateString = `${month}-${day}-${year}`;
const disabled = this.dateInString(dateString, this.disabledDates);
const selected = this.dateInString(dateString, this.selectedDates);
const date: CalendarDateInfo = {
day,
month,
year,
disabled,
selected,
};
const target = days[days.length - 1];
if (days.length === 0 || target.length % 7 === 0) {
days.push([date]);
} else {
target.push(date);
}
dayCount++;
}
return days;
}
/**
* A helper function that checks if a date exists in a list of dates
* @param date - A date objec that includes the day, month and year
* @param datesString - a comma separated list of dates
* @returns - Returns true if it found the date in the list of dates
* @public
*/
public dateInString(date: Date | string, datesString: string): boolean {
const dates = datesString.split(",").map(str => str.trim());
date =
typeof date === "string"
? date
: `${date.getMonth() + 1}-${date.getDate()}-${date.getFullYear()}`;
return dates.some(d => d === date);
}
/**
* Creates a class string for the day container
* @param date - date of the calendar cell
* @returns - string of class names
* @public
*/
public getDayClassNames(date: CalendarDateInfo, todayString?: string): string {
const { day, month, year, disabled, selected } = date;
const today = todayString === `${month}-${day}-${year}`;
const inactive = this.month !== month;
return [
"day",
today && "today",
inactive && "inactive",
disabled && "disabled",
selected && "selected",
]
.filter(Boolean)
.join(" ");
}
/**
* Returns a list of weekday labels
* @returns An array of weekday text and full text if abbreviated
* @public
*/
public getWeekdayText(): { text: string; abbr?: string }[] {
const weekdayText: {
text: string;
abbr?: string;
}[] = this.dateFormatter.getWeekdays().map(text => ({ text }));
if (this.weekdayFormat !== "long") {
const longText = this.dateFormatter.getWeekdays("long");
weekdayText.forEach((weekday, index) => {
weekday.abbr = longText[index];
});
}
return weekdayText;
}
/**
* Emits the "date-select" event with the day, month and year.
* @param date - Date cell
* @public
*/
public handleDateSelect(event: Event, day: CalendarDateInfo): void {
event.preventDefault;
this.$emit("dateselected", day);
}
/**
* Handles keyboard events on a cell
* @param event - Keyboard event
* @param date - Date of the cell selected
*/
public handleKeydown(event: KeyboardEvent, date: CalendarDateInfo): boolean {
if (event.key === keyEnter) {
this.handleDateSelect(event, date);
}
return true;
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.