text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as utils from "./utilities/utils"; describe("ecjson properties to ts", () => { describe("primitive property", () => { const testCases: utils.PropertyTestCase[] = [ // Test Case: Class with binary property { testName: `Class with binary property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="BinaryProp" typeName="binary"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { binaryProp?: any; }`, ], }, // Test Case: Class with point3d type { testName: `Class with point3d property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="Point3dProp" typeName="point3d"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), new RegExp(`import { (?=.*\\b(Point3d)\\b).* } from "@itwin/core-geometry";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { point3dProp?: Point3d; }`, ], }, // Test Case: Class with point2d type { testName: `Class with point2d property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="Point2dProp" typeName="point2d"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), new RegExp(`import { (?=.*\\b(Point2d)\\b).* } from "@itwin/core-geometry";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { point2dProp?: Point2d; }`, ], }, // Test Case: Class with bool type { testName: `Class with bool property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="BoolProp" typeName="bool"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { boolProp?: boolean; }`, ], }, // Test Case: Class with int type { testName: `Class with int property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="IntProp" typeName="int"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { intProp?: number; }`, ], }, // Test Case: Class with double type { testName: `Class with double property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="DoubleProp" typeName="double"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { doubleProp?: number; }`, ], }, // Test Case: Class with datetime { testName: `Class with datetime property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="DateTimeProp" typeName="dateTime"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { dateTimeProp?: Date; }`, ], }, // Test Case: Class with string { testName: `Class with string property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="StringProp" typeName="string"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { stringProp?: string; }`, ], }, // Test Case: Class with long { testName: `Class with long property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="LongProp" typeName="long"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { longProp?: any; }`, ], }]; utils.testGeneratedTypescriptProperty(testCases); }); describe("navigation", () => { const testCases: utils.PropertyTestCase[] = [ // Test Case: Class with navigation { testName: `Class with navigation property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECSchemaReference name="CoreCustomAttributes" version="01.00.00" alias="CoreCA"/> <ECSchemaReference name="BisCore" version="01.00.00" alias="bis"/> <ECEntityClass typeName="TestClass" modifier="None"> <ECNavigationProperty propertyName="NavProp" relationshipName="bis:ElementScopesCode" direction="backward"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { (?=.*\\b(EntityProps)\\b)(?=.*\\b(RelatedElementProps)\\b).* } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { navProp?: RelatedElementProps; }`, ], }]; utils.testGeneratedTypescriptProperty(testCases); }); describe("struct property", () => { const testCases: utils.PropertyTestCase[] = [ // Test Case: Class with struct { testName: `Class with struct property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECStructClass typeName="DerivedStruct" modifier="None"> <ECProperty propertyName="IntProp" typeName="int"/> <ECProperty propertyName="DoubleProp" typeName="double"/> </ECStructClass> <ECEntityClass typeName="TestClass" modifier="None"> <ECStructProperty propertyName="StructProp" typeName="DerivedStruct"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { structProp?: DerivedStruct; }`, ], }, // Test Case: Class with struct in reference schema { testName: `Class with struct property in reference schema`, referenceXmls: [ `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="RefTest" alias="ref" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECStructClass typeName="DerivedStruct" modifier="None"> <ECProperty propertyName="IntProp" typeName="int"/> <ECProperty propertyName="DoubleProp" typeName="double"/> </ECStructClass> </ECSchema>`, ], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECSchemaReference name="RefTest" version="01.00.00" alias="ref"/> <ECEntityClass typeName="TestClass" modifier="None"> <ECStructProperty propertyName="StructProp" typeName="ref:DerivedStruct"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), new RegExp(`import { DerivedStruct } from "./RefTestElementProps";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { structProp?: DerivedStruct; }`, ], }, ]; utils.testGeneratedTypescriptProperty(testCases); }); describe("primitive array property", () => { const testCases: utils.PropertyTestCase[] = [ // Test Case: Class with primitive array property { testName: `Class with primitive array property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="TestClass" modifier="None"> <ECArrayProperty propertyName="BinaryArrayProp" typeName="binary" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="BoolArrayProp" typeName="bool" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="DoubleArrayProp" typeName="double" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="IntArrayProp" typeName="int" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="Point2dArrayProp" typeName="point2d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="Point3dArrayProp" typeName="point3d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="StringArrayProp" typeName="string" minOccurs="0" maxOccurs="unbounded"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), new RegExp(`import { (?=.*\\b(Point2d)\\b)(?=.*\\b(Point3d)\\b).* } from "@itwin/core-geometry";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { binaryArrayProp?: any[]; boolArrayProp?: boolean[]; doubleArrayProp?: number[]; intArrayProp?: number[]; point2dArrayProp?: Point2d[]; point3dArrayProp?: Point3d[]; stringArrayProp?: string[]; }`, ], }]; utils.testGeneratedTypescriptProperty(testCases); }); describe("struct array property", () => { const testCases: utils.PropertyTestCase[] = [ // Test Case: Class with struct array property { testName: `Class with struct array property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECStructClass typeName="TestStruct" modifier="None"> <ECProperty propertyName="IntProp" typeName="int"/> <ECProperty propertyName="DoubleProp" typeName="double"/> </ECStructClass> <ECEntityClass typeName="TestClass" modifier="None"> <ECStructArrayProperty propertyName="StructArrayProp" typeName="TestStruct" minOccurs="0" maxOccurs="unbounded"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { structArrayProp?: TestStruct[]; }`, ], }, // Test Case: Class with struct array property in reference schema { testName: `Class with struct array property in reference schema`, referenceXmls: [ `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="RefTest" alias="ref" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECStructClass typeName="TestStruct" modifier="None"> <ECProperty propertyName="IntProp" typeName="int"/> <ECProperty propertyName="DoubleProp" typeName="double"/> </ECStructClass> </ECSchema>`, ], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECSchemaReference name="RefTest" version="01.00.00" alias="ref"/> <ECEntityClass typeName="TestClass" modifier="None"> <ECStructArrayProperty propertyName="StructArrayProp" typeName="ref:TestStruct" minOccurs="0" maxOccurs="unbounded"/> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), new RegExp(`import { TestStruct } from "./RefTestElementProps";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { structArrayProp?: TestStruct[]; }`, ], }, ]; utils.testGeneratedTypescriptProperty(testCases); }); describe("do not add custom handled properties", () => { const testCases: utils.PropertyTestCase[] = [ // Test Case: Class with struct array property { testName: `Class with struct array property`, referenceXmls: [], schemaXml: `<?xml version="1.0" encoding="utf-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECSchemaReference name="CoreCustomAttributes" version="01.00.00" alias="CoreCA"/> <ECSchemaReference name="BisCore" version="01.00.00" alias="bis"/> <ECStructClass typeName="TestStruct" modifier="None"> <ECProperty propertyName="IntProp" typeName="int"/> </ECStructClass> <ECEntityClass typeName="TestClass" modifier="None"> <ECProperty propertyName="StringProp" typeName="string"> <ECCustomAttributes> <CustomHandledProperty xmlns="BisCore.01.00.00"/> </ECCustomAttributes> </ECProperty> <ECProperty propertyName="IntProp" typeName="int"/> <ECStructArrayProperty propertyName="StructArrayProp" typeName="TestStruct" minOccurs="0" maxOccurs="unbounded"/> <ECStructArrayProperty propertyName="StructCustomHandledArrayProp" typeName="TestStruct" minOccurs="0" maxOccurs="unbounded"> <ECCustomAttributes> <CustomHandledProperty xmlns="BisCore.01.00.00"/> </ECCustomAttributes> </ECStructArrayProperty> <ECNavigationProperty propertyName="NavProp" relationshipName="bis:ElementScopesCode" direction="backward"> <ECCustomAttributes> <CustomHandledProperty xmlns="BisCore.01.00.00"/> </ECCustomAttributes> </ECNavigationProperty> </ECEntityClass> </ECSchema>`, expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`), ], expectedPropsTs: [utils.dedent` export interface TestClassProps extends EntityProps { intProp?: number; structArrayProp?: TestStruct[]; }`, ], }]; utils.testGeneratedTypescriptProperty(testCases); }); });
the_stack
import type { Heap } from "../structsGenerator/consts"; /** --- struct number start --- **/ export function number_type_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 0) / 8]; } export function number_type_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 0) / 8] = value); } export const number_type_place = 0; export const number_type_ctor = Float64Array; export function number_value_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 8) / 8]; } export function number_value_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 8) / 8] = value); } export const number_value_place = 8; export const number_value_ctor = Float64Array; export function number_set_all( heap: Heap, structPointer: number, type: number, value: number ) { heap.f64[(structPointer + 0) / 8] = type; heap.f64[(structPointer + 8) / 8] = value; } export const number_size = 16; /** --- struct number end --- **/ /** --- struct bigint start --- **/ export function bigint_type_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 0) / 8]; } export function bigint_type_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 0) / 8] = value); } export const bigint_type_place = 0; export const bigint_type_ctor = Float64Array; export function bigint_value_get(heap: Heap, structPointer: number) { return heap.u64[(structPointer + 8) / 8]; } export function bigint_value_set( heap: Heap, structPointer: number, value: bigint ) { return (heap.u64[(structPointer + 8) / 8] = value); } export const bigint_value_place = 8; export const bigint_value_ctor = BigUint64Array; export function bigint_set_all( heap: Heap, structPointer: number, type: number, value: bigint ) { heap.f64[(structPointer + 0) / 8] = type; heap.u64[(structPointer + 8) / 8] = value; } export const bigint_size = 16; /** --- struct bigint end --- **/ /** --- struct date start --- **/ export function date_type_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 0) / 8]; } export function date_type_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 0) / 8] = value); } export const date_type_place = 0; export const date_type_ctor = Float64Array; export function date_refsCount_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 8) / 4]; } export function date_refsCount_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 8) / 4] = value); } export const date_refsCount_place = 8; export const date_refsCount_ctor = Uint32Array; export function date___padding___get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 12) / 4]; } export function date___padding___set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 12) / 4] = value); } export const date___padding___place = 12; export const date___padding___ctor = Uint32Array; export function date_timestamp_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 16) / 8]; } export function date_timestamp_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 16) / 8] = value); } export const date_timestamp_place = 16; export const date_timestamp_ctor = Float64Array; export function date_set_all( heap: Heap, structPointer: number, type: number, refsCount: number, __padding__: number, timestamp: number ) { heap.f64[(structPointer + 0) / 8] = type; heap.u32[(structPointer + 8) / 4] = refsCount; heap.u32[(structPointer + 12) / 4] = __padding__; heap.f64[(structPointer + 16) / 8] = timestamp; } export const date_size = 24; /** --- struct date end --- **/ /** --- struct array start --- **/ export function array_type_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 0) / 8]; } export function array_type_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 0) / 8] = value); } export const array_type_place = 0; export const array_type_ctor = Float64Array; export function array_refsCount_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 8) / 4]; } export function array_refsCount_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 8) / 4] = value); } export const array_refsCount_place = 8; export const array_refsCount_ctor = Uint32Array; export function array_dataspacePointer_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 12) / 4]; } export function array_dataspacePointer_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 12) / 4] = value); } export const array_dataspacePointer_place = 12; export const array_dataspacePointer_ctor = Uint32Array; export function array_length_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 16) / 4]; } export function array_length_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 16) / 4] = value); } export const array_length_place = 16; export const array_length_ctor = Uint32Array; export function array_allocatedLength_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 20) / 4]; } export function array_allocatedLength_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 20) / 4] = value); } export const array_allocatedLength_place = 20; export const array_allocatedLength_ctor = Uint32Array; export function array_set_all( heap: Heap, structPointer: number, type: number, refsCount: number, dataspacePointer: number, length: number, allocatedLength: number ) { heap.f64[(structPointer + 0) / 8] = type; heap.u32[(structPointer + 8) / 4] = refsCount; heap.u32[(structPointer + 12) / 4] = dataspacePointer; heap.u32[(structPointer + 16) / 4] = length; heap.u32[(structPointer + 20) / 4] = allocatedLength; } export const array_size = 24; /** --- struct array end --- **/ /** --- struct object start --- **/ export function object_type_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 0) / 8]; } export function object_type_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 0) / 8] = value); } export const object_type_place = 0; export const object_type_ctor = Float64Array; export function object_refsCount_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 8) / 4]; } export function object_refsCount_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 8) / 4] = value); } export const object_refsCount_place = 8; export const object_refsCount_ctor = Uint32Array; export function object_pointerToHashMap_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 12) / 4]; } export function object_pointerToHashMap_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 12) / 4] = value); } export const object_pointerToHashMap_place = 12; export const object_pointerToHashMap_ctor = Uint32Array; export function object_set_all( heap: Heap, structPointer: number, type: number, refsCount: number, pointerToHashMap: number ) { heap.f64[(structPointer + 0) / 8] = type; heap.u32[(structPointer + 8) / 4] = refsCount; heap.u32[(structPointer + 12) / 4] = pointerToHashMap; } export const object_size = 16; /** --- struct object end --- **/ /** --- struct string start --- **/ export function string_type_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 0) / 8]; } export function string_type_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 0) / 8] = value); } export const string_type_place = 0; export const string_type_ctor = Float64Array; export function string_refsCount_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 8) / 4]; } export function string_refsCount_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 8) / 4] = value); } export const string_refsCount_place = 8; export const string_refsCount_ctor = Uint32Array; export function string_bytesLength_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 12) / 4]; } export function string_bytesLength_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 12) / 4] = value); } export const string_bytesLength_place = 12; export const string_bytesLength_ctor = Uint32Array; export function string_charsPointer_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 16) / 4]; } export function string_charsPointer_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 16) / 4] = value); } export const string_charsPointer_place = 16; export const string_charsPointer_ctor = Uint32Array; export function string_set_all( heap: Heap, structPointer: number, type: number, refsCount: number, bytesLength: number, charsPointer: number ) { heap.f64[(structPointer + 0) / 8] = type; heap.u32[(structPointer + 8) / 4] = refsCount; heap.u32[(structPointer + 12) / 4] = bytesLength; heap.u32[(structPointer + 16) / 4] = charsPointer; } export const string_size = 20; /** --- struct string end --- **/ /** --- struct typeOnly start --- **/ export function typeOnly_type_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 0) / 8]; } export function typeOnly_type_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 0) / 8] = value); } export const typeOnly_type_place = 0; export const typeOnly_type_ctor = Float64Array; export function typeOnly_set_all( heap: Heap, structPointer: number, type: number ) { heap.f64[(structPointer + 0) / 8] = type; } export const typeOnly_size = 8; /** --- struct typeOnly end --- **/ /** --- struct typeAndRc start --- **/ export function typeAndRc_type_get(heap: Heap, structPointer: number) { return heap.f64[(structPointer + 0) / 8]; } export function typeAndRc_type_set( heap: Heap, structPointer: number, value: number ) { return (heap.f64[(structPointer + 0) / 8] = value); } export const typeAndRc_type_place = 0; export const typeAndRc_type_ctor = Float64Array; export function typeAndRc_refsCount_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 8) / 4]; } export function typeAndRc_refsCount_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 8) / 4] = value); } export const typeAndRc_refsCount_place = 8; export const typeAndRc_refsCount_ctor = Uint32Array; export function typeAndRc_set_all( heap: Heap, structPointer: number, type: number, refsCount: number ) { heap.f64[(structPointer + 0) / 8] = type; heap.u32[(structPointer + 8) / 4] = refsCount; } export const typeAndRc_size = 12; /** --- struct typeAndRc end --- **/ /** --- struct linkedList start --- **/ export function linkedList_END_POINTER_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 0) / 4]; } export function linkedList_END_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 0) / 4] = value); } export const linkedList_END_POINTER_place = 0; export const linkedList_END_POINTER_ctor = Uint32Array; export function linkedList_START_POINTER_get( heap: Heap, structPointer: number ) { return heap.u32[(structPointer + 4) / 4]; } export function linkedList_START_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 4) / 4] = value); } export const linkedList_START_POINTER_place = 4; export const linkedList_START_POINTER_ctor = Uint32Array; export function linkedList_set_all( heap: Heap, structPointer: number, END_POINTER: number, START_POINTER: number ) { heap.u32[(structPointer + 0) / 4] = END_POINTER; heap.u32[(structPointer + 4) / 4] = START_POINTER; } export const linkedList_size = 8; /** --- struct linkedList end --- **/ /** --- struct linkedListItem start --- **/ export function linkedListItem_NEXT_POINTER_get( heap: Heap, structPointer: number ) { return heap.u32[(structPointer + 0) / 4]; } export function linkedListItem_NEXT_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 0) / 4] = value); } export const linkedListItem_NEXT_POINTER_place = 0; export const linkedListItem_NEXT_POINTER_ctor = Uint32Array; export function linkedListItem_VALUE_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 4) / 4]; } export function linkedListItem_VALUE_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 4) / 4] = value); } export const linkedListItem_VALUE_place = 4; export const linkedListItem_VALUE_ctor = Uint32Array; export function linkedListItem_set_all( heap: Heap, structPointer: number, NEXT_POINTER: number, VALUE: number ) { heap.u32[(structPointer + 0) / 4] = NEXT_POINTER; heap.u32[(structPointer + 4) / 4] = VALUE; } export const linkedListItem_size = 8; /** --- struct linkedListItem end --- **/ /** --- struct hashmap start --- **/ export function hashmap_ARRAY_POINTER_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 0) / 4]; } export function hashmap_ARRAY_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 0) / 4] = value); } export const hashmap_ARRAY_POINTER_place = 0; export const hashmap_ARRAY_POINTER_ctor = Uint32Array; export function hashmap_LINKED_LIST_POINTER_get( heap: Heap, structPointer: number ) { return heap.u32[(structPointer + 4) / 4]; } export function hashmap_LINKED_LIST_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 4) / 4] = value); } export const hashmap_LINKED_LIST_POINTER_place = 4; export const hashmap_LINKED_LIST_POINTER_ctor = Uint32Array; export function hashmap_LINKED_LIST_SIZE_get( heap: Heap, structPointer: number ) { return heap.u32[(structPointer + 8) / 4]; } export function hashmap_LINKED_LIST_SIZE_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 8) / 4] = value); } export const hashmap_LINKED_LIST_SIZE_place = 8; export const hashmap_LINKED_LIST_SIZE_ctor = Uint32Array; export function hashmap_CAPACITY_get(heap: Heap, structPointer: number) { return heap.u8[(structPointer + 12) / 1]; } export function hashmap_CAPACITY_set( heap: Heap, structPointer: number, value: number ) { return (heap.u8[(structPointer + 12) / 1] = value); } export const hashmap_CAPACITY_place = 12; export const hashmap_CAPACITY_ctor = Uint8Array; export function hashmap_USED_CAPACITY_get(heap: Heap, structPointer: number) { return heap.u8[(structPointer + 13) / 1]; } export function hashmap_USED_CAPACITY_set( heap: Heap, structPointer: number, value: number ) { return (heap.u8[(structPointer + 13) / 1] = value); } export const hashmap_USED_CAPACITY_place = 13; export const hashmap_USED_CAPACITY_ctor = Uint8Array; export function hashmap_set_all( heap: Heap, structPointer: number, ARRAY_POINTER: number, LINKED_LIST_POINTER: number, LINKED_LIST_SIZE: number, CAPACITY: number, USED_CAPACITY: number ) { heap.u32[(structPointer + 0) / 4] = ARRAY_POINTER; heap.u32[(structPointer + 4) / 4] = LINKED_LIST_POINTER; heap.u32[(structPointer + 8) / 4] = LINKED_LIST_SIZE; heap.u8[(structPointer + 12) / 1] = CAPACITY; heap.u8[(structPointer + 13) / 1] = USED_CAPACITY; } export const hashmap_size = 14; /** --- struct hashmap end --- **/ /** --- struct hashmapNode start --- **/ export function hashmapNode_VALUE_POINTER_get( heap: Heap, structPointer: number ) { return heap.u32[(structPointer + 0) / 4]; } export function hashmapNode_VALUE_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 0) / 4] = value); } export const hashmapNode_VALUE_POINTER_place = 0; export const hashmapNode_VALUE_POINTER_ctor = Uint32Array; export function hashmapNode_NEXT_NODE_POINTER_get( heap: Heap, structPointer: number ) { return heap.u32[(structPointer + 4) / 4]; } export function hashmapNode_NEXT_NODE_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 4) / 4] = value); } export const hashmapNode_NEXT_NODE_POINTER_place = 4; export const hashmapNode_NEXT_NODE_POINTER_ctor = Uint32Array; export function hashmapNode_KEY_POINTER_get(heap: Heap, structPointer: number) { return heap.u32[(structPointer + 8) / 4]; } export function hashmapNode_KEY_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 8) / 4] = value); } export const hashmapNode_KEY_POINTER_place = 8; export const hashmapNode_KEY_POINTER_ctor = Uint32Array; export function hashmapNode_LINKED_LIST_ITEM_POINTER_get( heap: Heap, structPointer: number ) { return heap.u32[(structPointer + 12) / 4]; } export function hashmapNode_LINKED_LIST_ITEM_POINTER_set( heap: Heap, structPointer: number, value: number ) { return (heap.u32[(structPointer + 12) / 4] = value); } export const hashmapNode_LINKED_LIST_ITEM_POINTER_place = 12; export const hashmapNode_LINKED_LIST_ITEM_POINTER_ctor = Uint32Array; export function hashmapNode_set_all( heap: Heap, structPointer: number, VALUE_POINTER: number, NEXT_NODE_POINTER: number, KEY_POINTER: number, LINKED_LIST_ITEM_POINTER: number ) { heap.u32[(structPointer + 0) / 4] = VALUE_POINTER; heap.u32[(structPointer + 4) / 4] = NEXT_NODE_POINTER; heap.u32[(structPointer + 8) / 4] = KEY_POINTER; heap.u32[(structPointer + 12) / 4] = LINKED_LIST_ITEM_POINTER; } export const hashmapNode_size = 16; /** --- struct hashmapNode end --- **/
the_stack
import {ITranslationMessagesFileFactory} from '../api/i-translation-messages-file-factory'; import {ITranslationMessagesFile} from '../api/i-translation-messages-file'; import {ITransUnit} from '../api/i-trans-unit'; import {FORMAT_XTB, FILETYPE_XTB, FORMAT_XMB} from '../api/constants'; import {format} from 'util'; import {DOMUtilities} from './dom-utilities'; import {AbstractTranslationMessagesFile} from './abstract-translation-messages-file'; import {XtbTransUnit} from './xtb-trans-unit'; import {AbstractTransUnit} from './abstract-trans-unit'; /** * Created by martin on 23.05.2017. * xtb-File access. * xtb is the translated counterpart to xmb. */ export class XtbFile extends AbstractTranslationMessagesFile implements ITranslationMessagesFile { // attached master file, if any // used as source to determine state ... private _masterFile: ITranslationMessagesFile; // an xmb-file /** * Create an xmb-File from source. * @param _translationMessageFileFactory factory to create a translation file (xtb) for the xmb file * @param xmlString file content * @param path Path to file * @param encoding optional encoding of the xml. * This is read from the file, but if you know it before, you can avoid reading the file twice. * @param optionalMaster in case of xmb the master file, that contains the original texts. * (this is used to support state infos, that are based on comparing original with translated version) * @return XmbFile */ constructor(private _translationMessageFileFactory: ITranslationMessagesFileFactory, xmlString: string, path: string, encoding: string, optionalMaster?: { xmlContent: string, path: string, encoding: string }) { super(); this._warnings = []; this._numberOfTransUnitsWithMissingId = 0; this.initializeFromContent(xmlString, path, encoding, optionalMaster); } private initializeFromContent(xmlString: string, path: string, encoding: string, optionalMaster?: { xmlContent: string, path: string, encoding: string }): XtbFile { this.parseContent(xmlString, path, encoding); if (this._parsedDocument.getElementsByTagName('translationbundle').length !== 1) { throw new Error(format('File "%s" seems to be no xtb file (should contain a translationbundle element)', path)); } if (optionalMaster) { try { this._masterFile = this._translationMessageFileFactory.createFileFromFileContent( FORMAT_XMB, optionalMaster.xmlContent, optionalMaster.path, optionalMaster.encoding); // check, wether this can be the master ... const numberInMaster = this._masterFile.numberOfTransUnits(); const myNumber = this.numberOfTransUnits(); if (numberInMaster !== myNumber) { this._warnings.push(format( '%s trans units found in master, but this file has %s. Check if it is the correct master', numberInMaster, myNumber)); } } catch (error) { throw new Error(format('File "%s" seems to be no xmb file. An xtb file needs xmb as master file.', optionalMaster.path)); } } return this; } protected initializeTransUnits() { this.transUnits = []; const transUnitsInFile = this._parsedDocument.getElementsByTagName('translation'); for (let i = 0; i < transUnitsInFile.length; i++) { const msg = transUnitsInFile.item(i); const id = msg.getAttribute('id'); if (!id) { this._warnings.push(format('oops, msg without "id" found in master, please check file %s', this._filename)); } let masterUnit: ITransUnit = null; if (this._masterFile) { masterUnit = this._masterFile.transUnitWithId(id); } this.transUnits.push(new XtbTransUnit(msg, id, this, <AbstractTransUnit> masterUnit)); } } /** * File format as it is used in config files. * Currently 'xlf', 'xlf2', 'xmb', 'xtb' * Returns one of the constants FORMAT_.. */ public i18nFormat(): string { return FORMAT_XTB; } /** * File type. * Here 'XTB' */ public fileType(): string { return FILETYPE_XTB; } /** * return tag names of all elements that have mixed content. * These elements will not be beautified. * Typical candidates are source and target. */ protected elementsWithMixedContent(): string[] { return ['translation']; } /** * Get source language. * Unsupported in xmb/xtb. * Try to guess it from master filename if any.. * @return source language. */ public sourceLanguage(): string { if (this._masterFile) { return this._masterFile.sourceLanguage(); } else { return null; } } /** * Edit the source language. * Unsupported in xmb/xtb. * @param language language */ public setSourceLanguage(language: string) { // do nothing, xtb has no notation for this. } /** * Get target language. * @return target language. */ public targetLanguage(): string { const translationbundleElem = DOMUtilities.getFirstElementByTagName(this._parsedDocument, 'translationbundle'); if (translationbundleElem) { return translationbundleElem.getAttribute('lang'); } else { return null; } } /** * Edit the target language. * @param language language */ public setTargetLanguage(language: string) { const translationbundleElem = DOMUtilities.getFirstElementByTagName(this._parsedDocument, 'translationbundle'); if (translationbundleElem) { translationbundleElem.setAttribute('lang', language); } } /** * Add a new trans-unit to this file. * The trans unit stems from another file. * It copies the source content of the tu to the target content too, * depending on the values of isDefaultLang and copyContent. * So the source can be used as a dummy translation. * (used by xliffmerge) * @param foreignTransUnit the trans unit to be imported. * @param isDefaultLang Flag, wether file contains the default language. * Then source and target are just equal. * The content will be copied. * State will be final. * @param copyContent Flag, wether to copy content or leave it empty. * Wben true, content will be copied from source. * When false, content will be left empty (if it is not the default language). * @param importAfterElement optional (since 1.10) other transunit (part of this file), that should be used as ancestor. * Newly imported trans unit is then inserted directly after this element. * If not set or not part of this file, new unit will be imported at the end. * If explicity set to null, new unit will be imported at the start. * @return the newly imported trans unit (since version 1.7.0) * @throws an error if trans-unit with same id already is in the file. */ importNewTransUnit(foreignTransUnit: ITransUnit, isDefaultLang: boolean, copyContent: boolean, importAfterElement?: ITransUnit) : ITransUnit { if (this.transUnitWithId(foreignTransUnit.id)) { throw new Error(format('tu with id %s already exists in file, cannot import it', foreignTransUnit.id)); } const newMasterTu = (<AbstractTransUnit> foreignTransUnit).cloneWithSourceAsTarget(isDefaultLang, copyContent, this); const translationbundleElem = DOMUtilities.getFirstElementByTagName(this._parsedDocument, 'translationbundle'); if (!translationbundleElem) { throw new Error(format('File "%s" seems to be no xtb file (should contain a translationbundle element)', this._filename)); } const translationElement = translationbundleElem.ownerDocument.createElement('translation'); translationElement.setAttribute('id', foreignTransUnit.id); let newContent = (copyContent || isDefaultLang) ? foreignTransUnit.sourceContent() : ''; if (!(<AbstractTransUnit> foreignTransUnit).isICUMessage(newContent)) { newContent = this.getNewTransUnitTargetPraefix() + newContent + this.getNewTransUnitTargetSuffix(); } DOMUtilities.replaceContentWithXMLContent(translationElement, newContent); const newTu = new XtbTransUnit(translationElement, foreignTransUnit.id, this, newMasterTu); let inserted = false; let isAfterElementPartOfFile = false; if (!!importAfterElement) { const insertionPoint = this.transUnitWithId(importAfterElement.id); if (!!insertionPoint) { isAfterElementPartOfFile = true; } } if (importAfterElement === undefined || (importAfterElement && !isAfterElementPartOfFile)) { translationbundleElem.appendChild(newTu.asXmlElement()); inserted = true; } else if (importAfterElement === null) { const firstTranslationElement = DOMUtilities.getFirstElementByTagName(this._parsedDocument, 'translation'); if (firstTranslationElement) { DOMUtilities.insertBefore(newTu.asXmlElement(), firstTranslationElement); inserted = true; } else { // no trans-unit, empty file, so add to bundle at end translationbundleElem.appendChild(newTu.asXmlElement()); inserted = true; } } else { const refUnitElement = DOMUtilities.getElementByTagNameAndId(this._parsedDocument, 'translation', importAfterElement.id); if (refUnitElement) { DOMUtilities.insertAfter(newTu.asXmlElement(), refUnitElement); inserted = true; } } if (inserted) { this.lazyInitializeTransUnits(); this.transUnits.push(newTu); this.countNumbers(); return newTu; } else { return null; } } /** * Create a new translation file for this file for a given language. * Normally, this is just a copy of the original one. * But for XMB the translation file has format 'XTB'. * @param lang Language code * @param filename expected filename to store file * @param isDefaultLang Flag, wether file contains the default language. * Then source and target are just equal. * The content will be copied. * State will be final. * @param copyContent Flag, wether to copy content or leave it empty. * Wben true, content will be copied from source. * When false, content will be left empty (if it is not the default language). */ public createTranslationFileForLang(lang: string, filename: string, isDefaultLang: boolean, copyContent: boolean) : ITranslationMessagesFile { throw new Error(format('File "%s", xtb files are not translatable, they are already translations', filename)); } }
the_stack
import { Metadata } from '../../decorator/metadata/metadata' import { alterCollectionPropertyMetadataForSingleItem, PropertyMetadata, } from '../../decorator/metadata/property-metadata.model' import { curry } from '../../helper/curry.function' import { isPlainObject } from '../../helper/is-plain-object.function' import { toDbOne } from '../../mapper/mapper' import { Attribute, Attributes } from '../../mapper/type/attribute.type' import { typeOf } from '../../mapper/util' import { resolveAttributeNames } from './functions/attribute-names.function' import { isFunctionOperator } from './functions/is-function-operator.function' import { isNoParamFunctionOperator } from './functions/is-no-param-function-operator.function' import { operatorParameterArity } from './functions/operator-parameter-arity.function' import { uniqueAttributeValueName } from './functions/unique-attribute-value-name.function' import { ConditionOperator } from './type/condition-operator.type' import { Expression } from './type/expression.type' import { validateAttributeType } from './update-expression-builder' import { dynamicTemplate } from './util' /** * @hidden */ type BuildFilterFn = ( attributePath: string, namePlaceholder: string, valuePlaceholder: string, attributeNames: Record<string, string>, values: any[], existingValueNames: string[] | undefined, propertyMetadata: PropertyMetadata<any> | undefined, ) => Expression /** * see http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html */ /** * Will walk the object tree recursively and removes all items which do not satisfy the filterFn * @param obj * @param {(value: any) => boolean} filterFn * @returns {any} * @hidden */ export function deepFilter(obj: any, filterFn: (value: any) => boolean): any { if (Array.isArray(obj)) { const returnArr: any[] = [] obj.forEach((i) => { const item = deepFilter(i, filterFn) if (item !== null) { returnArr.push(item) } }) return returnArr.length ? returnArr : null } else if (obj instanceof Set) { const returnArr: any[] = [] Array.from(obj).forEach((i) => { const item = deepFilter(i, filterFn) if (item !== null) { returnArr.push(item) } }) return returnArr.length ? new Set(returnArr) : null } else if (isPlainObject(obj)) { const returnObj: Record<string, any> = {} for (const key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key] const item = deepFilter(value, filterFn) if (item !== null) { returnObj[key] = item } } } return Object.keys(returnObj).length ? returnObj : null } else { if (filterFn(obj)) { return obj } else { return null } } } /** * Will create a condition which can be added to a request using the param object. * It will create the expression statement and the attribute names and values. * * @param {string} attributePath * @param {ConditionOperator} operator * @param {any[]} values Depending on the operator the amount of values differs * @param {string[]} existingValueNames If provided the existing names are used to make sure we have a unique name for the current attributePath * @param {Metadata<any>} metadata If provided we use the metadata to define the attribute name and use it to map the given value(s) to attributeValue(s) * @returns {Expression} * @hidden */ export function buildFilterExpression( attributePath: string, operator: ConditionOperator, values: any[], existingValueNames: string[] | undefined, metadata: Metadata<any> | undefined, ): Expression { // metadata get rid of undefined values values = deepFilter(values, (value) => value !== undefined) // check if provided values are valid for given operator validateForOperator(operator, values) // load property metadata if model metadata was provided let propertyMetadata: PropertyMetadata<any> | undefined if (metadata) { propertyMetadata = metadata.forProperty(attributePath) } /* * resolve placeholder and valuePlaceholder names (same as attributePath if it not already exists) * myProp -> #myProp for name placeholder and :myProp for value placeholder * * person[0] -> #person: person * person.list[0].age -> #person: person, #attr: attr, #age: age * person.age */ const resolvedAttributeNames = resolveAttributeNames(attributePath, metadata) const valuePlaceholder = uniqueAttributeValueName(attributePath, existingValueNames) /* * build the statement */ let buildFilterFn: BuildFilterFn switch (operator) { case 'IN': buildFilterFn = buildInConditionExpression break case 'BETWEEN': buildFilterFn = buildBetweenConditionExpression break default: buildFilterFn = curry(buildDefaultConditionExpression)(operator) } return buildFilterFn( attributePath, resolvedAttributeNames.placeholder, valuePlaceholder, resolvedAttributeNames.attributeNames, values, existingValueNames, propertyMetadata, ) } /** * IN expression is unlike all the others property the operand is an array of unwrapped values (not attribute values) * * @param {string} attributePath * @param {string[]} values * @param {string[]} existingValueNames * @param {PropertyMetadata<any>} propertyMetadata * @returns {Expression} * @hidden */ function buildInConditionExpression( attributePath: string, namePlaceholder: string, valuePlaceholder: string, attributeNames: Record<string, string>, values: any[], existingValueNames: string[] | undefined, propertyMetadata: PropertyMetadata<any> | undefined, ): Expression { const attributeValues: Attributes<any> = (<any[]>values[0]) .map((value) => toDbOne(value, propertyMetadata)) .reduce((result, mappedValue: Attribute | null, index: number) => { if (mappedValue !== null) { validateAttributeType('IN condition', mappedValue, 'S', 'N', 'B') result[`${valuePlaceholder}_${index}`] = mappedValue } return result }, <Attributes<any>>{}) const inStatement = (<any[]>values[0]).map((value: any, index: number) => `${valuePlaceholder}_${index}`).join(', ') return { statement: `${namePlaceholder} IN (${inStatement})`, attributeNames, attributeValues, } } /** * @hidden */ function buildBetweenConditionExpression( attributePath: string, namePlaceholder: string, valuePlaceholder: string, attributeNames: Record<string, string>, values: string[], existingValueNames: string[] | undefined, propertyMetadata: PropertyMetadata<any> | undefined, ): Expression { const attributeValues: Attributes<any> = {} const mappedValue1 = toDbOne(values[0], propertyMetadata) const mappedValue2 = toDbOne(values[1], propertyMetadata) if (mappedValue1 === null || mappedValue2 === null) { throw new Error('make sure to provide an actual value for te BETWEEN operator') } ;[mappedValue1, mappedValue2].forEach((mv) => validateAttributeType('between', mv, 'S', 'N', 'B')) const value2Placeholder = uniqueAttributeValueName(attributePath, [valuePlaceholder].concat(existingValueNames || [])) const statement = `${namePlaceholder} BETWEEN ${valuePlaceholder} AND ${value2Placeholder}` attributeValues[valuePlaceholder] = mappedValue1 attributeValues[value2Placeholder] = mappedValue2 return { statement, attributeNames, attributeValues, } } /** * @hidden */ function buildDefaultConditionExpression( operator: ConditionOperator, attributePath: string, namePlaceholder: string, valuePlaceholder: string, attributeNames: Record<string, string>, values: any[], existingValueNames: string[] | undefined, propertyMetadata: PropertyMetadata<any> | undefined, ): Expression { let statement: string let hasValue = true if (isFunctionOperator(operator)) { if (isNoParamFunctionOperator(operator)) { statement = `${operator} (${namePlaceholder})` hasValue = false } else { statement = `${operator} (${namePlaceholder}, ${valuePlaceholder})` } } else { statement = [namePlaceholder, operator, valuePlaceholder].join(' ') } const attributeValues: Attributes<any> = {} if (hasValue) { let attribute: Attribute | null if (operator === 'contains' || operator === 'not_contains') { attribute = toDbOne(values[0], alterCollectionPropertyMetadataForSingleItem(propertyMetadata)) validateAttributeType(`${operator} condition`, attribute, 'N', 'S', 'B') } else { attribute = toDbOne(values[0], propertyMetadata) switch (operator) { case 'begins_with': validateAttributeType(`${operator} condition`, attribute, 'S', 'B') break case '<': case '<=': case '>': case '>=': validateAttributeType(`${operator} condition`, attribute, 'N', 'S', 'B') break } } if (attribute) { attributeValues[valuePlaceholder] = attribute } } return { statement, attributeNames, attributeValues, } } /** * Every operator requires a predefined arity of parameters, this method checks for the correct arity and throws an Error * if not correct * * @param operator * @param values The values which will be applied to the operator function implementation, not every operator requires values * @throws {Error} error Throws an error if the amount of values won't match the operator function parameter arity or * the given values is not an array * @hidden */ function validateForOperator(operator: ConditionOperator, values?: any[]) { validateArity(operator, values) /* * validate values if operator supports values */ if (!isFunctionOperator(operator) || (isFunctionOperator(operator) && !isNoParamFunctionOperator(operator))) { if (values && Array.isArray(values) && values.length) { validateValues(operator, values) } else { throw new Error( dynamicTemplate(ERR_ARITY_DEFAULT, { parameterArity: operatorParameterArity(operator), operator }), ) } } } // tslint:disable:no-invalid-template-strings /* * error messages for arity issues */ /** * @hidden */ export const ERR_ARITY_IN = 'expected ${parameterArity} value(s) for operator ${operator}, this is not the right amount of method parameters for this operator (IN operator requires one value of array type)' /** * @hidden */ export const ERR_ARITY_DEFAULT = 'expected ${parameterArity} value(s) for operator ${operator}, this is not the right amount of method parameters for this operator' // tslint:enable:no-invalid-template-strings /** * @hidden */ function validateArity(operator: ConditionOperator, values?: any[]) { if (values === null || values === undefined) { if (isFunctionOperator(operator) && !isNoParamFunctionOperator(operator)) { // the operator needs some values to work throw new Error( dynamicTemplate(ERR_ARITY_DEFAULT, { parameterArity: operatorParameterArity(operator), operator }), ) } } else if (values && Array.isArray(values)) { const parameterArity = operatorParameterArity(operator) // check for correct amount of values if (values.length !== parameterArity) { switch (operator) { case 'IN': throw new Error(dynamicTemplate(ERR_ARITY_IN, { parameterArity, operator })) default: throw new Error(dynamicTemplate(ERR_ARITY_DEFAULT, { parameterArity, operator })) } } } } /* * error message for wrong operator values */ // tslint:disable:no-invalid-template-strings /** * @hidden */ export const ERR_VALUES_BETWEEN_TYPE = 'both values for operator BETWEEN must have the same type, got ${value1} and ${value2}' /** * @hidden */ export const ERR_VALUES_IN = 'the provided value for IN operator must be an array' // tslint:enable:no-invalid-template-strings /** * Every operator has some constraints about the values it supports, this method makes sure everything is fine for given * operator and values * @hidden */ function validateValues(operator: ConditionOperator, values: any[]) { // some additional operator dependent validation switch (operator) { case 'BETWEEN': // values must be the same type if (typeOf(values[0]) !== typeOf(values[1])) { throw new Error( dynamicTemplate(ERR_VALUES_BETWEEN_TYPE, { value1: typeOf(values[0]), value2: typeOf(values[1]) }), ) } break case 'IN': if (!Array.isArray(values[0])) { throw new Error(ERR_VALUES_IN) } } }
the_stack
import { GoslingTrackModel } from '../gosling-track-model'; import { Channel } from '../gosling.schema'; import { group } from 'd3-array'; import { getValueUsingChannel, IsStackedMark } from '../gosling.schema.guards'; import { cartesianToPolar } from '../utils/polar'; // Merge with the one in the `utils/text-style.ts` export const TEXT_STYLE_GLOBAL = { fontSize: '12px', fontFamily: 'sans-serif', // 'Arial', fontWeight: 'normal', fill: 'black', background: 'white', lineJoin: 'round', stroke: '#ffffff', strokeThickness: 0 }; export function drawText(HGC: any, trackInfo: any, tile: any, tm: GoslingTrackModel) { /* track spec */ const spec = tm.spec(); /* data */ const data = tm.data(); /* track size */ const [trackWidth, trackHeight] = trackInfo.dimensions; /* circular parameters */ const circular = spec.layout === 'circular'; const trackInnerRadius = spec.innerRadius ?? 220; const trackOuterRadius = spec.outerRadius ?? 300; // TODO: should be smaller than Math.min(width, height) const startAngle = spec.startAngle ?? 0; const endAngle = spec.endAngle ?? 360; const trackRingSize = trackOuterRadius - trackInnerRadius; const tcx = trackWidth / 2.0; const tcy = trackHeight / 2.0; /* row separation */ const rowCategories = (tm.getChannelDomainArray('row') as string[]) ?? ['___SINGLE_ROW___']; const rowHeight = trackHeight / rowCategories.length; /* styles */ const dx = spec.style?.dx ?? 0; const dy = spec.style?.dy ?? 0; /* render */ if (IsStackedMark(spec)) { if (circular) { // TODO: Not supported for circular layouts yet. return; } const rowGraphics = tile.graphics; // new HGC.libraries.PIXI.Graphics(); // only one row for stacked marks const genomicChannel = tm.getGenomicChannel(); if (!genomicChannel || !genomicChannel.field) { console.warn('Genomic field is not provided in the specification'); return; } const pivotedData = group(data, d => d[genomicChannel.field as string]); const xKeys = [...pivotedData.keys()]; // TODO: users may want to align rows by values xKeys.forEach(k => { let prevYEnd = 0; pivotedData.get(k)?.forEach(d => { const text = tm.encodedPIXIProperty('text', d); const color = tm.encodedPIXIProperty('color', d); const x = tm.encodedPIXIProperty('x', d) + dx; const xe = tm.encodedPIXIProperty('xe', d) + dx; const cx = tm.encodedPIXIProperty('x-center', d) + dx; const y = tm.encodedPIXIProperty('y', d) + dy; const size = tm.encodedPIXIProperty('size', d); const stroke = tm.encodedPIXIProperty('stroke', d); const strokeWidth = tm.encodedPIXIProperty('strokeWidth', d); const opacity = tm.encodedPIXIProperty('opacity', d); if (cx < 0 || cx > trackWidth) { // we do not draw texts that are out of the view return; } if (trackInfo.textsBeingUsed > 1000) { // prevent from drawing too many text elements for the performance return; } /* text styles */ const localTextStyle = { ...TEXT_STYLE_GLOBAL, fontSize: size ?? (spec.style?.textFontSize ? `${spec.style?.textFontSize}px` : TEXT_STYLE_GLOBAL.fontSize), stroke: stroke ?? spec.style?.textStroke ?? TEXT_STYLE_GLOBAL.stroke, strokeThickness: strokeWidth ?? spec.style?.textStrokeWidth ?? TEXT_STYLE_GLOBAL.strokeThickness, fontWeight: spec.style?.textFontWeight ?? TEXT_STYLE_GLOBAL.fontWeight }; const textStyleObj = new HGC.libraries.PIXI.TextStyle(localTextStyle); let textGraphic; if (trackInfo.textGraphics.length > trackInfo.textsBeingUsed) { textGraphic = trackInfo.textGraphics[trackInfo.textsBeingUsed]; textGraphic.style.fill = color; textGraphic.visible = true; textGraphic.text = text; textGraphic.alpha = 1; } else { textGraphic = new HGC.libraries.PIXI.Text(text, { ...localTextStyle, fill: color }); trackInfo.textGraphics.push(textGraphic); } const metric = HGC.libraries.PIXI.TextMetrics.measureText(text, textStyleObj); trackInfo.textsBeingUsed++; const alphaTransition = tm.markVisibility(d, { ...metric, zoomLevel: trackInfo._xScale.invert(trackWidth) - trackInfo._xScale.invert(0) }); const actualOpacity = Math.min(alphaTransition, opacity); if (!text || actualOpacity === 0) { trackInfo.textsBeingUsed--; textGraphic.visible = false; return; } textGraphic.alpha = actualOpacity; textGraphic.resolution = 8; textGraphic.updateText(); textGraphic.texture.baseTexture.scaleMode = HGC.libraries.PIXI.SCALE_MODES.LINEAR; // or .NEAREST const sprite = new HGC.libraries.PIXI.Sprite(textGraphic.texture); sprite.x = x; sprite.y = rowHeight - y - prevYEnd; sprite.width = xe - x; sprite.height = y; rowGraphics.addChild(sprite); prevYEnd += y; }); }); } else { rowCategories.forEach(rowCategory => { // we are separately drawing each row so that y scale can be more effectively shared across tiles without rerendering from the bottom const rowGraphics = tile.graphics; const rowPosition = tm.encodedValue('row', rowCategory); data.filter( d => !getValueUsingChannel(d, spec.row as Channel) || (getValueUsingChannel(d, spec.row as Channel) as string) === rowCategory ).forEach(d => { const text = tm.encodedPIXIProperty('text', d); const color = tm.encodedPIXIProperty('color', d); const cx = tm.encodedPIXIProperty('x-center', d) + dx; const y = tm.encodedPIXIProperty('y', d) + dy; const size = tm.encodedPIXIProperty('size', d); const stroke = tm.encodedPIXIProperty('stroke', d); const strokeWidth = tm.encodedPIXIProperty('strokeWidth', d); const opacity = tm.encodedPIXIProperty('opacity', d); if (cx < 0 || cx > trackWidth) { // we do not draw texts that are out of the view return; } if (trackInfo.textsBeingUsed > 1000) { // prevent from drawing too many text elements for the performance return; } /* text styles */ const localTextStyle = { ...TEXT_STYLE_GLOBAL, fontSize: size ?? (spec.style?.textFontSize ? `${spec.style?.textFontSize}px` : TEXT_STYLE_GLOBAL.fontSize), stroke: stroke ?? spec.style?.textStroke ?? TEXT_STYLE_GLOBAL.stroke, strokeThickness: strokeWidth ?? spec.style?.textStrokeWidth ?? TEXT_STYLE_GLOBAL.strokeThickness, fontWeight: spec.style?.textFontWeight ?? TEXT_STYLE_GLOBAL.fontWeight }; const textStyleObj = new HGC.libraries.PIXI.TextStyle(localTextStyle); let textGraphic; if (trackInfo.textGraphics.length > trackInfo.textsBeingUsed) { textGraphic = trackInfo.textGraphics[trackInfo.textsBeingUsed]; textGraphic.style.fill = color; textGraphic.visible = true; textGraphic.text = text; textGraphic.alpha = 1; } else { textGraphic = new HGC.libraries.PIXI.Text(text, { ...localTextStyle, fill: color }); trackInfo.textGraphics.push(textGraphic); } const metric = HGC.libraries.PIXI.TextMetrics.measureText(text, textStyleObj); trackInfo.textsBeingUsed++; const alphaTransition = tm.markVisibility(d, { ...metric, zoomLevel: trackInfo._xScale.invert(trackWidth) - trackInfo._xScale.invert(0) }); const actualOpacity = Math.min(alphaTransition, opacity); if (!text || actualOpacity === 0) { trackInfo.textsBeingUsed--; textGraphic.visible = false; return; } textGraphic.alpha = actualOpacity; textGraphic.anchor.x = !spec.style?.textAnchor || spec.style?.textAnchor === 'middle' ? 0.5 : spec.style.textAnchor === 'start' ? 0 : 1; textGraphic.anchor.y = 0.5; if (circular) { const r = trackOuterRadius - ((rowPosition + rowHeight - y) / trackHeight) * trackRingSize; const centerPos = cartesianToPolar(cx, trackWidth, r, tcx, tcy, startAngle, endAngle); textGraphic.x = centerPos.x; textGraphic.y = centerPos.y; textGraphic.resolution = 4; const txtStyle = new HGC.libraries.PIXI.TextStyle(textStyleObj); const metric = HGC.libraries.PIXI.TextMetrics.measureText(textGraphic.text, txtStyle); // scale the width of text label so that its width is the same when converted into circular form const tw = (metric.width / (2 * r * Math.PI)) * trackWidth; let [minX, maxX] = [cx - tw / 2.0, cx + tw / 2.0]; // make sure not to place the label on the origin if (minX < 0) { const gap = -minX; minX = 0; maxX += gap; } else if (maxX > trackWidth) { const gap = maxX - trackWidth; maxX = trackWidth; minX -= gap; } const ropePoints: number[] = []; for (let i = maxX; i >= minX; i -= tw / 10.0) { const p = cartesianToPolar(i, trackWidth, r, tcx, tcy, startAngle, endAngle); ropePoints.push(new HGC.libraries.PIXI.Point(p.x, p.y)); } textGraphic.updateText(); const rope = new HGC.libraries.PIXI.SimpleRope(textGraphic.texture, ropePoints); rope.alpha = actualOpacity; rowGraphics.addChild(rope); } else { textGraphic.position.x = cx; textGraphic.position.y = rowPosition + rowHeight - y; rowGraphics.addChild(textGraphic); } }); }); } }
the_stack
import assert from 'assert'; import Node, { SourceRange, NLAnnotationMap, AnnotationMap, AnnotationSpec, implAnnotationsToSource, nlAnnotationsToSource, } from './base'; import { cleanKind } from '../utils'; import { DeviceSelector, InputParam } from './invocation'; import { Statement } from './statement'; import { FunctionDef } from './function_def'; import { OldSlot, AbstractSlot } from './slots'; import NodeVisitor from './visitor'; import { TokenStream } from '../new-syntax/tokenstream'; import List from '../utils/list'; // Class definitions export type ClassMember = FunctionDef | MixinImportStmt | EntityDef; type FunctionMap = { [key : string] : FunctionDef }; interface ClassMemberSpec { imports ?: MixinImportStmt[]; entities ?: EntityDef[]; queries ?: FunctionMap; actions ?: FunctionMap; } interface ClassConstructOptions { is_abstract ?: boolean; } /** * The definition of a ThingTalk class. * */ export class ClassDef extends Statement { name : string; kind : string; extends : string[]; imports : MixinImportStmt[]; entities : EntityDef[]; queries : FunctionMap; actions : FunctionMap; nl_annotations : NLAnnotationMap; impl_annotations : AnnotationMap; /** * If the class is an abstract class. */ readonly is_abstract : boolean; /** * Construct a new class definition. * * @param location - the position of this node in the source code * @param kind - the class identifier in Thingpedia * @param _extends - parent classes (if any) * @param members - the class members including queries, actions, entities, imports * @param [members.imports=[]] - import statements in this class * @param [members.entities=[]] - entity declarations in this class * @param [members.queries={}] - query functions in this class * @param [members.actions={}] - action functions in this class * @param annotations - annotations of the class * @param [annotations.nl={}] - natural language annotations of the class (translatable annotations) * @param [annotations.impl={}] - implementation annotations of the class * @param options - additional options for the class * @param [options.is_abstract=false] - `true` if this is an abstract class which has no implementation */ constructor(location : SourceRange|null, kind : string, _extends : string[]|null, members : ClassMemberSpec, annotations : AnnotationSpec, options ?: ClassConstructOptions) { super(location); this.name = kind; this.kind = kind; // load parent classes assert(_extends === null || Array.isArray(_extends)); if (_extends === null) _extends = []; this.extends = _extends; // load class members this.imports = members.imports || []; this.entities = members.entities || []; this.queries = members.queries || {}; this.actions = members.actions || {}; this._adjustParentPointers(); // load annotations assert(typeof annotations.nl === 'undefined' || typeof annotations.nl === 'object'); assert(typeof annotations.impl === 'undefined' || typeof annotations.impl === 'object'); this.nl_annotations = annotations.nl || {}; this.impl_annotations = annotations.impl || {}; // load additional options this.is_abstract = !!(options && options.is_abstract); } toSource() : TokenStream { let list : TokenStream = List.concat('class', '@' + this.kind); if (this.extends.length > 0) list = List.concat(list, 'extends', List.join(this.extends.map((e) => List.singleton('@' + e)), ',')); let first = true; list = List.concat(list, nlAnnotationsToSource(this.nl_annotations), implAnnotationsToSource(this.impl_annotations), ' ', '{', '\n', '\t+'); for (const import_ of this.imports) { if (first) first = false; else list = List.concat(list, '\n'); list = List.concat(list, import_.toSource(), '\n'); } for (const entity of this.entities) { if (first) first = false; else list = List.concat(list, '\n'); list = List.concat(list, entity.toSource(), '\n'); } for (const q in this.queries) { if (first) first = false; else list = List.concat(list, '\n'); list = List.concat(list, this.queries[q].toSource(), '\n'); } for (const a in this.actions) { if (first) first = false; else list = List.concat(list, '\n'); list = List.concat(list, this.actions[a].toSource(), '\n'); } list = List.concat(list, '\t-', '}'); if (this.is_abstract) list = List.concat('abstract', list); return list; } *iterateSlots() : Generator<OldSlot, void> { } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitClassDef(this)) { for (const import_ of this.imports) import_.visit(visitor); for (const entity of this.entities) entity.visit(visitor); for (const query in this.queries) this.queries[query].visit(visitor); for (const action in this.actions) this.actions[action].visit(visitor); } visitor.exit(this); } private _adjustParentPointers() { for (const name in this.queries) this.queries[name].setClass(this); for (const name in this.actions) this.actions[name].setClass(this); } /** * Get a function defined in this class with the given type and name. * * @param {string} type - the function type, either `query` or `action` * @param {string} name - the function name * @return {module.Ast.FunctionDef|undefined} the function definition, or `undefined` * if the function does not exist */ getFunction(type : 'query'|'action', name : string) : FunctionDef|undefined { if (type === 'query') return this.queries[name]; else return this.actions[name]; } /** * Read and normalize an implementation annotation from this class. * * @param {string} name - the annotation name * @return {any|undefined} the annotation normalized value, or `undefined` if the * annotation is not present */ getImplementationAnnotation<T>(name : string) : T|undefined { if (Object.prototype.hasOwnProperty.call(this.impl_annotations, name)) return this.impl_annotations[name].toJS() as T; else return undefined; } /** * Read a natural-language annotation from this class. * * @param {string} name - the annotation name * @return {any|undefined} the annotation value, or `undefined` if the * annotation is not present */ getNaturalLanguageAnnotation<T>(name : string) : T|undefined { if (Object.prototype.hasOwnProperty.call(this.nl_annotations, name)) return this.nl_annotations[name] as T; else return undefined; } /** * Clone the class definition. * * @return {Ast.ClassDef} the cloned class definition */ clone() : ClassDef { // clone members const imports = this.imports.map((i) => i.clone()); const entities = this.entities.map((e) => e.clone()); const queries : FunctionMap = {}; const actions : FunctionMap = {}; for (const name in this.queries) queries[name] = this.queries[name].clone(); for (const name in this.actions) actions[name] = this.actions[name].clone(); const members = { imports, entities, queries, actions }; // clone annotations const nl : NLAnnotationMap = {}; Object.assign(nl, this.nl_annotations); const impl : AnnotationMap = {}; Object.assign(impl, this.impl_annotations); const annotations = { nl, impl }; // clone other options const options = { is_abstract: this.is_abstract }; return new ClassDef(this.location, this.kind, this.extends, members, annotations, options); } /** * The `loader` mixin for this class, if one is present * */ get loader() : MixinImportStmt|undefined { return this.imports.find((i) => i.facets.includes('loader')); } /** * The `config` mixin for this class, if one is present * */ get config() : MixinImportStmt|undefined { return this.imports.find((i) => i.facets.includes('config')); } /** * The canonical form of this class. * * This is is the preferred property to use as a user visible name for devices of * this class. It will never be null or undefined: if the `#_[canonical]` annotation * is missing, a default will be computed from the class name. */ get canonical() : string { return this.nl_annotations.canonical || cleanKind(this.kind); } /** * The natural language annotations of the class * * @deprecated metadata is deprecated. Use nl_annotations instead. */ get metadata() : NLAnnotationMap { return this.nl_annotations; } /** * The implementation annotations of the class * * @deprecated annotations is deprecated. Use impl_annotations instead. */ get annotations() : AnnotationMap { return this.impl_annotations; } /** * Read and normalize an annotation from this class. * * @param {string} name - the annotation name * @return {any|undefined} the annotation normalized value, or `undefined` if the * annotation is not present * @deprecated getAnnotation is deprecated and should not be used. Use {@link Ast.ClassDef.getImplementationAnnotation} instead. */ getAnnotation<T>(name : string) : T|undefined { return this.getImplementationAnnotation<T>(name); } } /** * A `import` statement that imports a mixin inside a ThingTalk class. * * Mixins add implementation functionality to ThingTalk classes, such as specifying * how the class is loaded (which language, which format, which version of the SDK) * and how devices are configured. */ export class MixinImportStmt extends Node { facets : string[]; module : string; in_params : InputParam[]; /** * Construct a new mixin import statement. * * @param location - the position of this node in the source code * @param facets - which facets to import from the mixin (`config`, `auth`, `loader`, ...) * @param module - the mixin identifier to import * @param in_params - input parameters to pass to the mixin */ constructor(location : SourceRange|null, facets : string[], module : string, in_params : InputParam[]) { super(location); assert(Array.isArray(facets)); this.facets = facets; assert(typeof module === 'string'); this.module = module; assert(Array.isArray(in_params)); this.in_params = in_params; } toSource() : TokenStream { return List.concat('import', List.join(this.facets.map((f) => List.singleton(f)), ','), ' ', 'from', ' ', '@' + this.module, '(', List.join(this.in_params.map((ip) => ip.toSource()), ','), ')', ';'); } clone() : MixinImportStmt { return new MixinImportStmt( this.location, this.facets.slice(0), this.module, this.in_params.map((p) => p.clone()) ); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitMixinImportStmt(this)) { for (const in_param of this.in_params) in_param.visit(visitor); } visitor.exit(this); } } /** * An `entity` statement inside a ThingTalk class. * */ export class EntityDef extends Node { isEntityDef = true; /** * The entity name. */ name : string; extends : string[]; /** * The entity metadata (translatable annotations). */ nl_annotations : NLAnnotationMap; /** * The entity annotations. */ impl_annotations : AnnotationMap; /** * Construct a new entity declaration. * * @param location - the position of this node in the source code * @param name - the entity name (the part after the ':') * @param extends - the parent entity type, if any (this can be a fully qualified name with ':', or just the part after ':') * @param annotations - annotations of the entity type * @param [annotations.nl={}] - natural-language annotations (translatable annotations) * @param [annotations.impl={}] - implementation annotations */ constructor(location : SourceRange|null, name : string, _extends : string[]|string|null, annotations : AnnotationSpec) { super(location); this.name = name; _extends = typeof _extends === 'string' ? [_extends] : _extends; this.extends = _extends || []; this.nl_annotations = annotations.nl || {}; this.impl_annotations = annotations.impl || {}; } toSource() : TokenStream { if (this.extends.length > 0) { const _extends = this.extends.map((e) => e.includes(':') ? `^^${e}` : e); return List.concat('entity', ' ', this.name, 'extends', List.join(_extends.map((e) => List.singleton(e)), ','), '\t+', nlAnnotationsToSource(this.nl_annotations), implAnnotationsToSource(this.impl_annotations), '\t-', ';'); } else { return List.concat('entity', ' ', this.name, '\t+', nlAnnotationsToSource(this.nl_annotations), implAnnotationsToSource(this.impl_annotations), '\t-', ';'); } } /** * Clone this entity and return a new object with the same properties. * * @return the new instance */ clone() : EntityDef { const nl : NLAnnotationMap = {}; Object.assign(nl, this.nl_annotations); const impl : AnnotationMap = {}; Object.assign(impl, this.impl_annotations); return new EntityDef(this.location, this.name, this.extends, { nl, impl }); } /** * Read and normalize an implementation annotation from this entity definition. * * @param {string} name - the annotation name * @return {any|undefined} the annotation normalized value, or `undefined` if the * annotation is not present */ getImplementationAnnotation<T>(name : string) : T|undefined { if (Object.prototype.hasOwnProperty.call(this.impl_annotations, name)) return this.impl_annotations[name].toJS() as T; else return undefined; } /** * Read a natural-language annotation from this entity definition. * * @param {string} name - the annotation name * @return {any|undefined} the annotation value, or `undefined` if the * annotation is not present */ getNaturalLanguageAnnotation(name : string) : any|undefined { if (Object.prototype.hasOwnProperty.call(this.nl_annotations, name)) return this.nl_annotations[name]; else return undefined; } visit(visitor : NodeVisitor) : void { visitor.enter(this); visitor.visitEntityDef(this); visitor.exit(this); } }
the_stack
import ConduitGrpcSdk, { ConduitModelOptions, ConduitModelOptionsPermModifyType, ConduitSchema, ConduitSchemaExtension, GrpcError, ParsedRouterRequest, TYPE, UnparsedRouterResponse, } from '@conduitplatform/grpc-sdk'; import { status } from '@grpc/grpc-js'; import { isNil, merge, isEmpty } from 'lodash'; import { validateSchemaInput } from '../utils/utilities'; import { SchemaController } from '../controllers/cms/schema.controller'; import { CustomEndpointController } from '../controllers/customEndpoints/customEndpoint.controller'; import { DatabaseAdapter } from '../adapters/DatabaseAdapter'; import { MongooseSchema } from '../adapters/mongoose-adapter/MongooseSchema'; import { SequelizeSchema } from '../adapters/sequelize-adapter/SequelizeSchema'; import { ParsedQuery } from '../interfaces'; const escapeStringRegexp = require('escape-string-regexp'); type _ConduitSchema = Omit<ConduitSchema, 'schemaOptions'> & { modelOptions: ConduitModelOptions; _id: string; }; const SYSTEM_SCHEMAS = ['CustomEndpoints', '_PendingSchemas']; // DeclaredSchemas is not a DeclaredSchema export class SchemaAdmin { constructor( private readonly grpcSdk: ConduitGrpcSdk, private readonly database: DatabaseAdapter<MongooseSchema | SequelizeSchema>, private readonly schemaController: SchemaController, private readonly customEndpointController: CustomEndpointController, ) {} async getSchema(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const query: ParsedQuery = { _id: call.request.params.id, name: { $nin: SYSTEM_SCHEMAS }, }; const requestedSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findOne(query); if (isNil(requestedSchema)) { throw new GrpcError(status.NOT_FOUND, 'Schema does not exist'); } return requestedSchema; } async getSchemas(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const { search, sort, enabled, owner } = call.request.params; const skip = call.request.params.skip ?? 0; const limit = call.request.params.limit ?? 25; let query: ParsedQuery = { name: { $nin: SYSTEM_SCHEMAS } }; if (owner && owner.length !== 0) { query = { $and: [query, { ownerModule: { $in: owner } }], }; } let identifier; if (!isNil(search)) { identifier = escapeStringRegexp(search); query['name'] = { $regex: `.*${identifier}.*`, $options: 'i' }; } if (!isNil(enabled)) { const enabledQuery = { $or: [ { ownerModule: { $ne: 'database' } }, { 'modelOptions.conduit.cms.enabled': true }, ], }; const disabledQuery = { 'modelOptions.conduit.cms.enabled': false }; query = { $and: [query, enabled ? enabledQuery : disabledQuery], }; } const schemasPromise = await this.database .getSchemaModel('_DeclaredSchema') .model.findMany(query, skip, limit, sort); const documentsCountPromise = await this.database .getSchemaModel('_DeclaredSchema') .model.countDocuments(query); const [schemas, count] = await Promise.all([schemasPromise, documentsCountPromise]); return { schemas, count }; } async getSchemasExtensions(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const { skip } = call.request.params ?? 0; const { limit } = call.request.params ?? 25; const query = '{}'; const schemaAdapter = this.database.getSchemaModel('_DeclaredSchema'); const schemasExtensionsPromise = schemaAdapter.model.findMany( query, skip, limit, 'name extensions', undefined, ); const totalCountPromise = schemaAdapter.model.countDocuments(query); const [schemasExtensions, totalCount] = await Promise.all([ schemasExtensionsPromise, totalCountPromise, ]).catch((e: Error) => { throw new GrpcError(status.INTERNAL, e.message); }); return { schemasExtensions, totalCount }; } async createSchema(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const { name, fields, modelOptions, permissions } = call.request.params; const enabled = call.request.params.enabled ?? true; const crudOperations = call.request.params.crudOperations; if (name.indexOf('-') >= 0 || name.indexOf(' ') >= 0) { throw new GrpcError( status.INVALID_ARGUMENT, 'Names cannot include spaces and - characters', ); } const errorMessage = validateSchemaInput(name, fields, modelOptions, enabled); if (!isNil(errorMessage)) { throw new GrpcError(status.INVALID_ARGUMENT, errorMessage); } if ( permissions && permissions.canModify && !ConduitModelOptionsPermModifyType.includes(permissions.canModify) ) { throw new GrpcError( status.INVALID_ARGUMENT, `canModify permission must be one of: ${ConduitModelOptionsPermModifyType.join( ', ', )}`, ); } const existingSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findOne({ name }); if (existingSchema) { throw new GrpcError(status.ALREADY_EXISTS, 'Schema name is already in use!'); } Object.assign(fields, { _id: TYPE.ObjectId, createdAt: TYPE.Date, updatedAt: TYPE.Date, }); const schemaOptions = isNil(modelOptions) ? { conduit: { cms: { enabled, crudOperations } } } : { ...modelOptions, conduit: { cms: { enabled, crudOperations } } }; schemaOptions.conduit.permissions = permissions; // database sets missing perms to defaults return this.schemaController.createSchema( new ConduitSchema(name, fields, schemaOptions), ); } async patchSchema(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { let { id, name, fields, modelOptions, permissions, crudOperations, } = call.request.params; if (!isNil(name) && name !== '') { throw new GrpcError( status.INVALID_ARGUMENT, 'Name of existing schema cannot be edited', ); } const requestedSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findOne({ ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: id, }); if (isNil(requestedSchema)) { throw new GrpcError(status.NOT_FOUND, 'Schema does not exist'); } const errorMessage = validateSchemaInput(requestedSchema.name, fields, modelOptions); if (!isNil(errorMessage)) { throw new GrpcError(status.INTERNAL, errorMessage); } if (permissions) { this.patchSchemaPerms(requestedSchema, permissions); } requestedSchema.name = name ? name : requestedSchema.name; requestedSchema.fields = fields ? fields : requestedSchema.fields; const enabled = call.request.params.enabled ?? requestedSchema.modelOptions.conduit.cms.enabled; crudOperations = call.request.params.crudOperations ?? requestedSchema.modelOptions.conduit.cms.crudOperations; requestedSchema.modelOptions = merge(requestedSchema.modelOptions, modelOptions, { conduit: { cms: { enabled, crudOperations } }, }); const updatedSchema = await this.database.createCustomSchemaFromAdapter( new ConduitSchema( requestedSchema.name, requestedSchema.fields, requestedSchema.modelOptions, ), ); if (isNil(updatedSchema)) { throw new GrpcError(status.INTERNAL, 'Could not update schema'); } // Mongoose requires that schemas are re-created in order to update them if (enabled) { await this.schemaController.createSchema( new ConduitSchema( updatedSchema.originalSchema.name, updatedSchema.originalSchema.fields, updatedSchema.originalSchema.schemaOptions, ), ); } return updatedSchema.originalSchema; } async deleteSchema(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const { id, deleteData } = call.request.params; const requestedSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findOne({ ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: id, }); if (isNil(requestedSchema)) { throw new GrpcError(status.NOT_FOUND, 'Schema does not exist'); } // Temp: error out until Admin handles this case const endpoints = await this.database .getSchemaModel('CustomEndpoints') .model.findMany({ selectedSchema: id, }); if (!isNil(endpoints) && endpoints.length !== 0) { throw new GrpcError( status.ABORTED, 'Cannot delete schema because it is used by a custom endpoint', ); } await this.database .getSchemaModel('_DeclaredSchema') .model.deleteOne(requestedSchema); await this.database .getSchemaModel('CustomEndpoints') .model.deleteMany({ selectedSchema: id }); const message = await this.database.deleteSchema( requestedSchema.name, deleteData, 'database', ); this.schemaController.refreshRoutes(); this.customEndpointController.refreshEndpoints(); return message; } async deleteSchemas(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const { ids, deleteData } = call.request.params; if (ids.length === 0) { // array check is required throw new GrpcError( status.INVALID_ARGUMENT, 'Argument ids is required and must be a non-empty array!', ); } const requestedSchemas = await this.database .getSchemaModel('_DeclaredSchema') .model.findMany({ ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: { $in: ids }, }); if (requestedSchemas.length === 0) { throw new GrpcError(status.NOT_FOUND, 'ids array contains invalid ids'); } const foundSchemas = await this.database .getSchemaModel('_DeclaredSchema') .model.countDocuments({ ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: { $in: ids }, }); if (foundSchemas !== requestedSchemas.length) { throw new GrpcError(status.NOT_FOUND, 'ids array contains invalid ids'); } for (const schema of requestedSchemas) { const endpoints = await this.database .getSchemaModel('CustomEndpoints') .model.countDocuments({ selectedSchema: schema._id, }); if (!isNil(endpoints) && endpoints > 0) { // Temp: error out until Admin handles this case throw new GrpcError( status.ABORTED, 'Cannot delete schema because it is used by a custom endpoint', ); } await this.database.deleteSchema(schema.name, deleteData, 'database'); } await this.database .getSchemaModel('_DeclaredSchema') .model.deleteMany({ _id: { $in: ids } }); await this.database .getSchemaModel('CustomEndpoints') .model.deleteMany({ selectedSchema: { $in: ids } }); this.schemaController.refreshRoutes(); this.customEndpointController.refreshEndpoints(); return 'Schemas successfully deleted'; } async toggleSchema(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const requestedSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findOne({ ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: call.request.params.id, }); if (isNil(requestedSchema)) { throw new GrpcError(status.NOT_FOUND, 'Schema does not exist'); } requestedSchema.modelOptions.conduit.cms.enabled = !requestedSchema.modelOptions .conduit.cms.enabled; const updatedSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findByIdAndUpdate(requestedSchema._id, requestedSchema); if (isNil(updatedSchema)) { throw new GrpcError( status.INTERNAL, `Could not ${ requestedSchema.modelOptions.conduit.cms.enabled ? 'enable' : 'disable' } schema`, ); } await this.database .getSchemaModel('CustomEndpoints') .model.updateMany( { selectedSchema: call.request.params.id }, { enabled: requestedSchema.modelOptions.conduit.cms.enabled }, ); if (!requestedSchema.modelOptions.conduit.cms.enabled) { this.schemaController.refreshRoutes(); } this.customEndpointController.refreshEndpoints(); return { name: updatedSchema.name, enabled: updatedSchema.modelOptions.conduit.cms.enabled, }; } async toggleSchemas(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const { ids, enabled } = call.request.params; if (ids.length === 0) { // array check is required throw new GrpcError( status.INVALID_ARGUMENT, 'Argument ids is required and must be a non-empty array!', ); } const requestedSchemas = await this.database .getSchemaModel('_DeclaredSchema') .model.findMany({ ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: { $in: ids }, }); if (isNil(requestedSchemas)) { throw new GrpcError(status.NOT_FOUND, 'ids array contains invalid ids'); } const foundDocumentsCount = await this.database .getSchemaModel('_DeclaredSchema') .model.countDocuments({ ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: { $in: ids }, }); if (foundDocumentsCount !== requestedSchemas.length) { throw new GrpcError(status.NOT_FOUND, 'ids array contains invalid ids'); } const updatedSchemas = await this.database .getSchemaModel('_DeclaredSchema') .model.updateMany( { ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: { $in: ids }, }, { 'modelOptions.conduit.cms.enabled': enabled }, ); if (isNil(updatedSchemas)) { throw new GrpcError( status.INTERNAL, `Could not ${enabled ? 'enable' : 'disable'} schemas`, ); } await this.database .getSchemaModel('CustomEndpoints') .model.updateMany({ selectedSchema: { $in: ids } }, { enabled: enabled }); if (!enabled) { this.schemaController.refreshRoutes(); } this.customEndpointController.refreshEndpoints(); return { updatedSchemas, enabled, }; } async setSchemaExtension(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const requestedSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findOne({ _id: call.request.params.schemaId }); if (!requestedSchema) { throw new GrpcError(status.NOT_FOUND, 'Schema does not exist'); } const extension = new ConduitSchemaExtension( requestedSchema.name, call.request.params.fields, ); let base = await this.database.getBaseSchema(requestedSchema.name); await this.database .setSchemaExtension(base, 'database', extension.modelSchema) .catch((e: Error) => { throw new GrpcError(status.INTERNAL, e.message); }); return this.database.getSchema(requestedSchema.name); } async setSchemaPerms(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { let { id, extendable, canCreate, canModify, canDelete } = call.request.params; const requestedSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findOne({ ownerModule: 'database', name: { $nin: SYSTEM_SCHEMAS }, _id: id, }); if (isNil(requestedSchema)) { throw new GrpcError(status.NOT_FOUND, 'Schema does not exist'); } this.patchSchemaPerms(requestedSchema, { extendable, canCreate, canModify, canDelete, }); const updatedSchema = await this.database .getSchemaModel('_DeclaredSchema') .model.findByIdAndUpdate(requestedSchema._id, requestedSchema); if (isNil(updatedSchema)) { throw new GrpcError(status.INTERNAL, 'Could not update schema permissions'); } return 'Schema permissions updated successfully'; } async getSchemaOwners(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const modules: string[] = []; const schemas = await this.database .getSchemaModel('_DeclaredSchema') .model.findMany({}, undefined, undefined, 'ownerModule'); schemas.forEach((schema: ConduitSchema) => { if (!modules.includes(schema.ownerModule)) modules.push(schema.ownerModule); }); return { modules }; } async getIntrospectionStatus( call: ParsedRouterRequest, ): Promise<UnparsedRouterResponse> { const foreignSchemas = Array.from(this.database.foreignSchemaCollections); const importedSchemas: string[] = ( await this.database .getSchemaModel('_DeclaredSchema') .model.findMany({ 'modelOptions.conduit.imported': true }) ).map((schema: ConduitSchema) => schema.collectionName); return { foreignSchemas, foreignSchemaCount: foreignSchemas.length, importedSchemas, importedSchemaCount: importedSchemas.length, }; } async introspectDatabase(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const introspectedSchemas = await this.database.introspectDatabase(); await Promise.all( introspectedSchemas.map(async (schema: ConduitSchema) => { if (isEmpty(schema.fields)) return null; await this.database.getSchemaModel('_PendingSchemas').model.create( JSON.stringify({ name: schema.name, fields: schema.fields, modelOptions: schema.schemaOptions, ownerModule: schema.ownerModule, extensions: (schema as any).extensions, }), ); }), ); return 'Schemas successfully introspected'; } async getPendingSchema(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const query: ParsedQuery = { _id: call.request.params.id }; const requestedSchema = await this.database .getSchemaModel('_PendingSchemas') .model.findOne(query); if (isNil(requestedSchema)) { throw new GrpcError(status.NOT_FOUND, 'Pending schema does not exist'); } return requestedSchema; } async getPendingSchemas(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const { search, sort } = call.request.params; const skip = call.request.params.skip ?? 0; const limit = call.request.params.limit ?? 25; let query = {}; if (!isNil(search)) { const identifier = escapeStringRegexp(search); query = { name: { $regex: `.*${identifier}.*`, $options: 'i' } }; } const schemasPromise = this.database .getSchemaModel('_PendingSchemas') .model.findMany(query, skip, limit, undefined, sort); const schemasCountPromise = this.database .getSchemaModel('_PendingSchemas') .model.countDocuments(query); const [schemas, count] = await Promise.all([schemasPromise, schemasCountPromise]); return { schemas, count }; } async finalizeSchemas(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> { const schemas: _ConduitSchema[] = Object.values(call.request.params.schemas); if (schemas.length === 0) { // array check is required throw new GrpcError( status.INVALID_ARGUMENT, 'Argument schemas is required and must be a non-empty array!', ); } const schemaNames = schemas.map(schema => schema.name); await Promise.all( schemas.map(async (schema: _ConduitSchema) => { const recreatedSchema = new ConduitSchema( schema.name, schema.fields, schema.modelOptions, ); if (isNil(recreatedSchema.fields)) return null; recreatedSchema.ownerModule = 'database'; const defaultCrudOperations = { create: { enabled: false, authenticated: false }, read: { enabled: false, authenticated: false }, update: { enabled: false, authenticated: false }, delete: { enabled: false, authenticated: false }, }; const defaultPermissions = { extendable: false, canCreate: false, canModify: 'Nothing', canDelete: false, }; recreatedSchema.schemaOptions.conduit = merge( recreatedSchema.schemaOptions.conduit, { imported: true, noSync: true, cms: { enabled: recreatedSchema.schemaOptions.conduit?.cms?.enabled ?? true, crudOperations: recreatedSchema.schemaOptions.conduit?.cms?.crudOperations ? merge( defaultCrudOperations, recreatedSchema.schemaOptions.conduit.cms.crudOperations, ) : defaultCrudOperations, }, permissions: recreatedSchema.schemaOptions.conduit?.permissions ? merge( defaultPermissions, recreatedSchema.schemaOptions.conduit.permissions, ) : defaultPermissions, }, ); await this.database.createSchemaFromAdapter(recreatedSchema, true); }), ); await this.database .getSchemaModel('_PendingSchemas') .model.deleteMany({ name: { $in: schemaNames } }); return `${schemas.length} ${ schemas.length > 1 ? 'schemas' : 'schema' } finalized successfully`; } private patchSchemaPerms( schema: _ConduitSchema, // @ts-ignore perms: ConduitModelOptions['conduit']['permissions'], ) { if ( perms!.canModify && !ConduitModelOptionsPermModifyType.includes(perms!.canModify) ) { throw new GrpcError( status.INVALID_ARGUMENT, `canModify permission must be one of: ${ConduitModelOptionsPermModifyType.join( ', ', )}`, ); } schema.modelOptions.conduit!.permissions!.extendable = perms!.extendable ?? schema.modelOptions.conduit!.permissions!.extendable; schema.modelOptions.conduit!.permissions!.canCreate = perms!.canCreate ?? schema.modelOptions.conduit!.permissions!.canCreate; schema.modelOptions.conduit!.permissions!.canModify = perms!.canModify ?? schema.modelOptions.conduit!.permissions!.canModify; schema.modelOptions.conduit!.permissions!.canDelete = perms!.canDelete ?? schema.modelOptions.conduit!.permissions!.canDelete; } }
the_stack
import * as yup from "yup"; import * as t from "io-ts"; import { CredentialBody } from "google-auth-library"; export const gcpConfigSchema = yup.object({ projectId: yup.string(), certManagerServiceAccount: yup.string(), externalDNSServiceAccount: yup.string(), cortexServiceAccount: yup.string(), lokiServiceAccount: yup.string() }); export type GCPConfig = yup.InferType<typeof gcpConfigSchema>; export const serviceAccountSchema = yup .object({ auth_uri: yup.string().required(), auth_provider_x509_cert_url: yup.string().required(), client_email: yup.string().required(), client_id: yup.string().required(), client_x509_cert_url: yup.string().required(), private_key: yup.string().required(), private_key_id: yup.string().required(), project_id: yup.string().required(), type: yup.string().required(), token_uri: yup.string().required() }) .noUnknown() .defined(); export type GCPServiceAccount = CredentialBody; export const gcpAuthOptionsSchema = yup .object({ projectId: yup.string().required("must provide projectId"), credentials: serviceAccountSchema.required() }) .defined(); export type GCPAuthOptions = yup.InferType<typeof gcpAuthOptionsSchema>; export type BigtableDeploymentType = "development" | "production"; export type BigtableStorageType = "hdd" | "ssd"; // GKE cluster status constants export const ERROR = "ERROR"; export const DEGRADED = "DEGRADED"; export const STOPPING = "STOPPING"; export const RECONCILING = "RECONCILING"; export const RUNNING = "RUNNING"; export const PROVISIONING = "PROVISIONING"; export const STATUS_UNSPECIFIED = "STATUS_UNSPECIFIED"; // GKE NetworkProviders export const PROVIDER_UNSPECIFIED = "PROVIDER_UNSPECIFIED"; export const CALICO = "CALICO"; // GKE etcd encryption export const ENCRYPTED = "ENCRYPTED"; export const DECRYPTED = "DECRYPTED"; // Also has UNKNOWN type too but it's already declared below // GKE node taints export const EFFECT_UNSPECIFIED = "EFFECT_UNSPECIFIED"; export const NO_SCHEDULE = "NO_SCHEDULE"; export const PREFER_NO_SCHEDULE = "PREFER_NO_SCHEDULE"; export const NO_EXECUTE = "NO_EXECUTE"; // GKE node StatusConditions export const UNKNOWN = "UNKNOWN"; export const GCE_STOCKOUT = "GCE_STOCKOUT"; export const GKE_SERVICE_ACCOUNT_DELETED = "GKE_SERVICE_ACCOUNT_DELETED"; export const GCE_QUOTA_EXCEEDED = "GCE_QUOTA_EXCEEDED"; export const SET_BY_OPERATOR = "SET_BY_OPERATOR"; export const CLOUD_KMS_KEY_ERROR = "CLOUD_KMS_KEY_ERROR"; const nodePoolConfig = t.interface({ machineType: t.string, diskSizeGb: t.number, oauthScopes: t.array(t.string), serviceAccount: t.string, metadata: t.any, imageType: t.string, labels: t.any, localSsdCount: t.number, tags: t.array(t.string), preemptible: t.boolean, accelerators: t.array( t.partial( t.interface({ acceleratorCount: t.string, acceleratorType: t.string }).props ) ), diskType: t.string, minCpuPlatform: t.string, taints: t.array( t.partial( t.interface({ key: t.string, value: t.string, effect: t.keyof({ EFFECT_UNSPECIFIED: null, NO_SCHEDULE: null, PREFER_NO_SCHEDULE: null, NO_EXECUTE: null }) }).props ) ), shieldedInstanceConfig: t.partial( t.interface({ enableSecureBoot: t.boolean, enableIntegrityMonitoring: t.boolean }).props ) }); export const nodePool = t.interface({ name: t.string, config: t.partial(nodePoolConfig.props), initialNodeCount: t.number, selfLink: t.string, version: t.string, instanceGroupUrls: t.array(t.string), status: t.keyof({ ERROR: null, DEGRADED: null, STOPPING: null, RECONCILING: null, RUNNING: null, PROVISIONING: null, STATUS_UNSPECIFIED: null }), statusMessage: t.string, autoscaling: t.partial( t.interface({ enabled: t.boolean, minNodeCount: t.number, maxNodeCount: t.number, autoprovisioned: t.boolean }).props ), management: t.partial( t.interface({ autoUpgrade: t.boolean, autoRepair: t.boolean, upgradeOptions: t.partial( t.interface({ autoUpgradeStartTime: t.string, description: t.string }).props ) }).props ), maxPodsConstraint: t.partial( t.interface({ maxPodsPerNode: t.string }).props ), conditions: t.array( t.partial( t.interface({ code: t.keyof({ UNKNOWN: null, GCE_STOCKOUT: null, GKE_SERVICE_ACCOUNT_DELETED: null, GCE_QUOTA_EXCEEDED: null, SET_BY_OPERATOR: null, CLOUD_KMS_KEY_ERROR: null }), message: t.string }).props ) ), podIpv4CidrSize: t.number }); export const partialNodePool = t.partial(nodePool.props); export const gkeCluster = t.partial( t.interface({ name: t.string, description: t.string, releaseChannel: t.partial( t.interface({ channel: t.keyof({ RAPID: null, REGULAR: null, STABLE: null }) }).props ), masterAuth: t.partial( t.interface({ username: t.string, password: t.string, clientCertificateConfig: t.partial( t.interface({ issueClientCertificate: t.boolean }).props ), clusterCaCertificate: t.string, clientCertificate: t.string, clientKey: t.string }).props ), loggingService: t.string, monitoringService: t.string, network: t.string, clusterIpv4Cidr: t.string, addonsConfig: t.partial( t.interface({ httpLoadBalancing: t.partial( t.interface({ disabled: t.boolean }).props ), horizontalPodAutoscaling: t.partial( t.interface({ disabled: t.boolean }).props ), networkPolicyConfig: t.partial( t.interface({ disabled: t.boolean }).props ) }).props ), subnetwork: t.string, nodePools: t.array(partialNodePool), locations: t.array(t.string), enableKubernetesAlpha: t.boolean, resourceLabels: t.unknown, labelFingerprint: t.string, legacyAbac: t.partial( t.interface({ enabled: t.boolean }).props ), networkPolicy: t.partial( t.interface({ provider: t.keyof({ CALICO: null, PROVIDER_UNSPECIFIED: null }), enabled: t.boolean }).props ), ipAllocationPolicy: t.partial( t.interface({ useIpAliases: t.boolean, createSubnetwork: t.boolean, subnetworkName: t.string, clusterSecondaryRangeName: t.string, servicesSecondaryRangeName: t.string, clusterIpv4CidrBlock: t.string, nodeIpv4CidrBlock: t.string, servicesIpv4CidrBlock: t.string, tpuIpv4CidrBlock: t.string }).props ), masterAuthorizedNetworksConfig: t.partial( t.interface({ enabled: t.boolean, cidrBlocks: t.array( t.partial( t.interface({ displayName: t.string, cidrBlock: t.string }).props ) ) }).props ), maintenancePolicy: t.partial( t.interface({ window: t.interface({ dailyMaintenanceWindow: t.partial( t.interface({ startTime: t.string, duration: t.string }).props ) }) }).props ), binaryAuthorization: t.partial( t.interface({ enabled: t.boolean }).props ), autoscaling: t.partial( t.interface({ enableNodeAutoprovisioning: t.boolean, resourceLimits: t.array( t.partial( t.interface({ resourceType: t.string, minimum: t.string, maximum: t.string }).props ) ), autoprovisioningNodePoolDefaults: t.partial( t.interface({ oauthScopes: t.array(t.string), serviceAccount: t.string }).props ), autoprovisioningLocations: t.array(t.string) }).props ), networkConfig: t.partial( t.interface({ network: t.string, subnetwork: t.string, enableIntraNodeVisibility: t.boolean }).props ), resourceUsageExportConfig: t.partial( t.interface({ bigqueryDestination: t.partial( t.interface({ datasetId: t.string }).props ), enableNetworkEgressMetering: t.boolean, consumptionMeteringConfig: t.partial( t.interface({ enabled: t.boolean }).props ) }).props ), authenticatorGroupsConfig: t.partial( t.interface({ enabled: t.boolean, securityGroup: t.string }).props ), privateClusterConfig: t.partial( t.interface({ enablePrivateNodes: t.boolean, enablePrivateEndpoint: t.boolean, masterIpv4CidrBlock: t.string, privateEndpoint: t.string, publicEndpoint: t.string }).props ), databaseEncryption: t.partial( t.interface({ state: t.keyof({ UNKNOWN: null, ENCRYPTED: null, DECRYPTED: null }), keyName: t.string }).props ), verticalPodAutoscaling: t.partial( t.interface({ enabled: t.boolean }).props ), // https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters workloadIdentityConfig: t.partial( t.interface({ workloadPool: t.string }).props ), selfLink: t.string, endpoint: t.string, initialClusterVersion: t.string, currentMasterVersion: t.string, createTime: t.string, status: t.keyof({ ERROR: null, DEGRADED: null, STOPPING: null, RECONCILING: null, RUNNING: null, PROVISIONING: null, STATUS_UNSPECIFIED: null, DOES_NOT_EXIST: null, UNKNOWN: null }), statusMessage: t.string, nodeIpv4CidrSize: t.number, servicesIpv4Cidr: t.string, expireTime: t.string, location: t.string, enableTpu: t.boolean, tpuIpv4CidrBlock: t.string, conditions: t.array( t.partial( t.interface({ code: t.keyof({ UNKNOWN: null, GCE_STOCKOUT: null, GKE_SERVICE_ACCOUNT_DELETED: null, GCE_QUOTA_EXCEEDED: null, SET_BY_OPERATOR: null, CLOUD_KMS_KEY_ERROR: null, DOES_NOT_EXIST: null }), message: t.string }).props ) ) }).props ); export const network = t.interface({ cidr: t.string, subnet: t.string }); export type GKECluster = t.TypeOf<typeof gkeCluster>; export type Network = t.TypeOf<typeof network>;
the_stack
import { sum } from "lodash-es" import { Polyhedron, Face, Edge, VertexArg, Cap } from "math/polyhedra" import Classical, { Operation as OpName } from "data/specs/Classical" import Composite from "data/specs/Composite" import { makeOpPair, combineOps, Pose } from "./operationPairs" import Operation, { SolidArgs, OpArgs } from "./Operation" import { Vec3D, getCentroid, angleBetween } from "math/geom" import { getGeometry, FacetOpts, getTransformedVertices, } from "./operationUtils" // TODO move this to a util import { getCantellatedFace, getCantellatedEdgeFace } from "./resizeOps" function getSharpenFaces(polyhedron: Polyhedron) { const faceType = polyhedron.smallestFace().numSides return polyhedron.faces.filter((f) => f.numSides === faceType) } /** * Returns the point to sharpen given parameters in the following setup: * result * / ^ * / | * p2___f.normal * / * p1 * */ function getSharpenPoint(face: Face, p1: Vec3D, p2: Vec3D) { const ray = face.normalRay() const theta1 = angleBetween(p1, p2, ray) const theta2 = Math.PI - theta1 const dist = ray.distanceTo(p1) * Math.tan(theta2) return ray.getPointAtDistance(dist) } function getSharpenPointEdge(face: Face, edge: Edge) { return getSharpenPoint(face, edge.midpoint(), edge.twinFace().centroid()) } function getAvgInradius(specs: Classical, geom: Polyhedron) { let faces: Face[] if (specs.isRectified()) { faces = [geom.faceWithNumSides(3), geom.faceWithNumSides(specs.data.family)] } else if (specs.isBevelled()) { faces = [ geom.faceWithNumSides(6), geom.faceWithNumSides(2 * specs.data.family), ] } else if (specs.isCantellated()) { faces = [ geom.faceWithNumSides(3), getCantellatedFace(geom, specs.data.family), ] } else { throw new Error(`Invalid specs: ${specs.name()}`) } return sum(faces.map((f) => f.distanceToCenter())) / faces.length } interface TrioOpArgs<Op, Opts = any> { operation: Op pose(solid: SolidArgs<Classical>, opts: Opts): Pose transformer( solid: SolidArgs<Classical>, opts: Opts, result: Classical, ): VertexArg[] options?(entry: Classical): Opts } interface TrioArgs<L, M, R> { left: TrioOpArgs<L> middle: Omit<TrioOpArgs<M>, "transformer"> right: TrioOpArgs<R> } /** * Create a trio of truncation OpPairs: truncate, cotruncate, and rectify. * Given the functions to use for operations, poses, and transformers, * generate the triplet of OpPairs to use. */ function makeTruncateTrio<L extends OpName, M extends OpName, R extends OpName>( args: TrioArgs<L, M, R>, ) { const { left, right, middle } = args function makePair(leftOp: "left" | "middle", rightOp: "middle" | "right") { // Choose which side is the "middle" in order to short-circuit getting the intermediate const middleArg = leftOp === "middle" ? "left" : rightOp === "middle" ? "right" : null return makeOpPair({ graph: Classical.query .where((s) => s.data.operation === middle.operation) .map((entry) => { return { left: entry.withData({ operation: args[leftOp].operation }), right: entry.withData({ operation: args[rightOp].operation }), options: { left: args[leftOp].options?.(entry), right: args[rightOp].options?.(entry), }, } }), // If this is the left-right operation, then the intermediate // is going to be the middle operation middle: middleArg ?? ((entry) => entry.left.withData({ operation: middle.operation })), getPose: ($, solid, options) => { // Use the pose function for the side that matches the op name of the solid const side = Object.values(args).find( (arg) => arg.operation === solid.specs.data.operation, ) return side.pose(solid, options) }, toLeft: leftOp === "left" ? left.transformer : undefined, toRight: rightOp === "right" ? right.transformer : undefined, }) } return { truncate: makePair("left", "middle"), cotruncate: makePair("middle", "right"), rectify: makePair("left", "right"), } } function getRegularPose(geom: Polyhedron, face: Face, crossPoint: Vec3D): Pose { return { origin: geom.centroid(), // scale on the inradius of the truncated face scale: face.distanceToCenter(), orientation: [face.normal(), crossPoint.sub(face.centroid())], } } /** * Describes the truncation operations on a Platonic solid. */ const regs = makeTruncateTrio({ left: { operation: "regular", pose({ geom }) { const face = geom.getFace() return getRegularPose(geom, geom.getFace(), face.edges[0].midpoint()) }, transformer({ geom }) { return getTransformedVertices(getSharpenFaces(geom), (face) => getSharpenPointEdge(face, face.edges[0]), ) }, }, middle: { operation: "truncate", pose({ geom }) { const face = geom.largestFace() const n = face.numSides // pick an edge connected to another truncated face const edge = face.edges.find((e) => e.twinFace().numSides === n)! return getRegularPose(geom, face, edge.midpoint()) }, }, right: { operation: "rectify", // The rectified version is the only thing we need to choose an option for // when we move out of it options: (entry) => ({ facet: entry.data.facet }), pose({ specs, geom }, options) { // pick a face that *isn't* the sharpen face type const faceType = options.right.facet === "vertex" ? 3 : specs.data.family const face = geom.faceWithNumSides(faceType) return getRegularPose(geom, face, face.vertices[0].vec) }, transformer({ geom }) { // All edges that between two truncated faces const edges = geom.edges.filter( (e) => e.face.numSides > 5 && e.twinFace().numSides > 5, ) // Move each edge to its midpoint return getTransformedVertices(edges, (e) => e.midpoint()) }, }, }) function getAmboPose( specs: Classical, geom: Polyhedron, face: Face, point: Vec3D, ): Pose { return { origin: geom.centroid(), scale: getAvgInradius(specs, geom), orientation: [face.normal(), point.sub(face.centroid())], } } /** * A trio of operations that describe the truncation behavior on a quasi-regular polyhedron * (tetratetrahedron, cuboctahedron, and icosidodecahedron). * * A raw truncation on one of these doesn't yield a CRF solid. We need to do some fudging * in order to everything to align correctly. * * We calculate the average inradius between the face-facet faces and the vertex-facet faces * and use that as a scale. For both, we use a reference polyhedron and calculate the vertex * transformations based on them. */ const ambos = makeTruncateTrio({ left: { operation: "rectify", pose({ geom, specs }) { const face = geom.faceWithNumSides(specs.data.family) return getAmboPose(specs, geom, face, face.edges[0].midpoint()) }, transformer({ geom, specs }, $, resultSpec) { const ref = getGeometry(resultSpec) const refInradius = getAvgInradius(resultSpec, ref) const refCircumradius = ref.getVertex().distanceToCenter() const inradius = getAvgInradius(specs, geom) const scale = (refCircumradius / refInradius) * inradius const faces = geom.faces.filter((f) => f.numSides === 4) // Sharpen each of the faces to a point aligning with the vertices // of the rectified solid return getTransformedVertices(faces, (f) => geom.centroid().add(f.normal().scale(scale)), ) }, }, middle: { operation: "bevel", pose({ geom, specs }) { const face = geom.faceWithNumSides(specs.data.family * 2) const edge = face.edges.find((e) => e.twinFace().numSides !== 4)! return getAmboPose(specs, geom, face, edge.midpoint()) }, }, right: { operation: "cantellate", pose({ geom, specs }) { const face = getCantellatedFace(geom, specs.data.family) return getAmboPose(specs, geom, face, face.vertices[0].vec) }, transformer({ geom, specs }, $, resultSpec) { const ref = getGeometry(resultSpec) const refInradius = getAvgInradius(resultSpec, ref) const refFace = getCantellatedEdgeFace(ref) const refMidradius = refFace.distanceToCenter() const refFaceRadius = refFace.radius() const inradius = getAvgInradius(specs, geom) const scale = inradius / refInradius const faces = geom.faces.filter((f) => f.numSides === 4) return getTransformedVertices(faces, (f) => { const faceCentroid = geom .centroid() .add(f.normal().scale(refMidradius * scale)) return (v) => faceCentroid.add( v .sub(f.centroid()) .getNormalized() .scale(refFaceRadius * scale), ) }) }, }, }) const augTruncate = makeOpPair({ graph: Composite.query .where((s) => { const source = s.data.source return ( s.isAugmented() && !s.isDiminished() && source.isClassical() && source.isRegular() ) }) .map((entry) => ({ left: entry, right: entry.withData({ source: entry.data.source.withData({ operation: "truncate" }), }), })), middle: "right", getPose($, { geom, specs }) { const source = specs.data.source const isTetrahedron = source.isClassical() && source.isTetrahedral() && source.isRegular() // If source is a tetrahedron, take only the first cap (the other is the base) let caps = Cap.getAll(geom) if (isTetrahedron) { caps = [caps[0]] } const capVertIndices = caps.flatMap((cap) => cap.innerVertices().map((v) => v.index), ) const sourceVerts = geom.vertices.filter( (v) => !capVertIndices.includes(v.index), ) // Calculate the centroid *only* for the source polyhedra const centroid = getCentroid(sourceVerts.map((v) => v.vec)) function isSourceFace(face: Face) { return face.vertices.every((v) => !capVertIndices.includes(v.index)) } function isBaseFace(face: Face) { return isTetrahedron || face.numSides > 3 } const scaleFace = geom.faces.find((f) => isSourceFace(f) && isBaseFace(f))! const cap = caps[0] const mainAxis = cap.normal() const boundary = cap.boundary() let crossAxis if (specs.isTri()) { // Use the midpoin of the normals of the two other caps crossAxis = getCentroid([caps[1].normal(), caps[2].normal()]) } else if (specs.isBi() && specs.isMeta()) { // If metabiaugmented, use the normal of the other cap crossAxis = caps[1].normal() } else { crossAxis = boundary.edges .find((e) => isBaseFace(e.twinFace()))! .midpoint() .sub(boundary.centroid()) } return { origin: centroid, scale: scaleFace.centroid().distanceTo(centroid), orientation: [mainAxis, crossAxis], } }, toLeft({ geom }) { const capVertIndices = Cap.getAll(geom).flatMap((cap) => cap.innerVertices().map((v) => v.index), ) const sourceFaces = geom.faces.filter((f) => f.vertices.every((v) => !capVertIndices.includes(v.index)), ) const truncatedFaces = sourceFaces.filter((f) => f.numSides === 3) const cupolaFaces = geom.faces.filter((f) => f.vertices.every((v) => capVertIndices.includes(v.index)), ) return getTransformedVertices( [...truncatedFaces, ...cupolaFaces], (face) => { if (cupolaFaces.some((f) => f.equals(face))) { // Sharpen the cupola faces const v = face.vertices[0] // Find a triangular cupola face const otherFace = v .adjacentFaces() .find((f) => f.numSides === 3 && !f.equals(face))! return getSharpenPoint(face, v.vec, otherFace.centroid()) } else { const edge = face.edges.find((e) => e.twinFace().numSides > 5)! return getSharpenPointEdge(face, edge) } }, ) }, }) // Exported operations export const truncate = new Operation( "truncate", combineOps<Classical | Composite, any>([ regs.truncate.left, ambos.truncate.left, augTruncate.left, ]), ) export const cotruncate = new Operation( "cotruncate", combineOps([regs.cotruncate.left, ambos.cotruncate.left]), ) export const rectify = new Operation( "rectify", combineOps([regs.rectify.left, ambos.rectify.left]), ) const hitOptArgs: Partial<OpArgs<FacetOpts, Classical>> = { hitOption: "facet", getHitOption({ geom }, hitPoint) { const n = geom.hitFace(hitPoint).numSides return n <= 5 ? { facet: n === 3 ? "face" : "vertex" } : {} }, faceSelectionStates({ specs, geom }, { facet }) { const faceType = !facet ? null : facet === "face" ? 3 : specs.data.family return geom.faces.map((face) => { if (face.numSides === faceType) return "selected" return "selectable" }) }, } export const sharpen = new Operation("sharpen", { ...combineOps<Classical | Composite, FacetOpts>([ regs.truncate.right, ambos.truncate.right, augTruncate.right, regs.rectify.right, ambos.rectify.right, ]), // TODO split up sharpening rectified and sharpening truncated ...hitOptArgs, }) // TODO the following operators are unused right now // and need to be integrated into the app export const cosharpen = new Operation("cosharpen", { ...combineOps<Classical, FacetOpts>([ regs.cotruncate.right, ambos.cotruncate.right, ]), ...hitOptArgs, }) export const unrectify = new Operation("unrectify", { ...combineOps<Classical, FacetOpts>([ regs.rectify.right, ambos.rectify.right, ]), ...hitOptArgs, })
the_stack
import { rApply } from "ranges-apply"; import { Ranges } from "ranges-push"; import { right } from "string-left-right"; import { version as v } from "../package.json"; const version: string = v; import { Range, Ranges as RangesType } from "../../../scripts/common"; interface Extras { whiteSpaceStartsAt: null | number; whiteSpaceEndsAt: null | number; str: string; } interface CbObj extends Extras { suggested: Range; } type Callback = (cbObj: CbObj) => any; interface Opts { trimStart: boolean; trimEnd: boolean; trimLines: boolean; trimnbsp: boolean; removeEmptyLines: boolean; limitConsecutiveEmptyLinesTo: number; enforceSpacesOnly: boolean; cb: Callback; } // default set of options const defaults: Opts = { trimStart: true, trimEnd: true, trimLines: false, trimnbsp: false, removeEmptyLines: false, limitConsecutiveEmptyLinesTo: 0, enforceSpacesOnly: false, cb: ({ suggested }) => { // console.log(`default CB called`); // console.log( // `${`\u001b[${33}m${`suggested`}\u001b[${39}m`} = ${JSON.stringify( // suggested, // null, // 4 // )}` // ); return suggested; }, }; interface Res { result: string; ranges: RangesType; } const cbSchema = ["suggested", "whiteSpaceStartsAt", "whiteSpaceEndsAt", "str"]; function collapse(str: string, originalOpts?: Partial<Opts>): Res { console.log( `064 ██ string-collapse-whitespace called: str = ${JSON.stringify( str, null, 4 )}; originalOpts = ${JSON.stringify(originalOpts, null, 4)}` ); // f's if (typeof str !== "string") { throw new Error( `string-collapse-white-space/collapse(): [THROW_ID_01] The input is not string but ${typeof str}, equal to: ${JSON.stringify( str, null, 4 )}` ); } if (originalOpts && typeof originalOpts !== "object") { throw new Error( `string-collapse-white-space/collapse(): [THROW_ID_02] The opts is not a plain object but ${typeof originalOpts}, equal to:\n${JSON.stringify( originalOpts, null, 4 )}` ); } if (!str.length) { return { result: "", ranges: null, }; } const finalIndexesToDelete = new Ranges(); const NBSP = `\xa0`; // fill any settings with defaults if missing: const opts: Opts = { ...defaults, ...originalOpts }; console.log(` `); console.log( `105 ${`\u001b[${32}m${`FINAL`}\u001b[${39}m`} ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify( opts, null, 4 )}` ); function push(something?: any, extras?: Extras) { console.log(`---- push() ----`); console.log( `115 ${`\u001b[${35}m${`push()`}\u001b[${39}m`} ${`\u001b[${32}m${`extras`}\u001b[${39}m`} = ${JSON.stringify( extras, null, 4 )}` ); if (typeof opts.cb === "function") { const final: Range | null = opts.cb({ suggested: something as any, ...(extras as any), }); console.log( `128 ${`\u001b[${35}m${`push():`}\u001b[${39}m`} ${`\u001b[${33}m${`final`}\u001b[${39}m`} = ${JSON.stringify( final, null, 4 )}` ); if (Array.isArray(final)) { console.log( `136 ${`\u001b[${35}m${`push():`}\u001b[${39}m`} ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}` ); (finalIndexesToDelete as any).push(...final); } } else if (something) { (finalIndexesToDelete as any).push(...something); } } // ----------------------------------------------------------------------------- let spacesStartAt = null; let whiteSpaceStartsAt = null; let lineWhiteSpaceStartsAt = null; let linebreaksStartAt = null; let linebreaksEndAt = null; let nbspPresent = false; // Logic clauses for spaces, per-line whitespace and general whitespace // overlap somewhat and are not aware of each other. For example, mixed chunk // "\xa0 a \xa0" // ^line whitespace ends here - caught by per-line clauses // // "\xa0 a \xa0" // ^non-breaking space ends here, 1 character further // that's caught by general whitespace clauses // // as a solution, we stage all whitespace pushing ranges into this array, // then general whitespace clauses release all what's gathered and can // adjust the logic depending what's in staging. // Alternatively we could dig in already staged ranges, but that's slower. type Staged = [Range, Extras]; const staging: Staged[] = []; let consecutiveLineBreakCount = 0; for (let i = 0, len = str.length; i <= len; i++) { // // // // // // // // // // // LOOP STARTS - THE TOP PART // // // // // // // // // // console.log( `${`\u001b[${36}m${`-----------------------------------------------`}\u001b[${39}m`} str[${`\u001b[${35}m${i}\u001b[${39}m`}] = ${JSON.stringify( str[i], null, 4 )}` ); // line break counting if (str[i] === "\r" || (str[i] === "\n" && str[i - 1] !== "\r")) { consecutiveLineBreakCount += 1; console.log( `206 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} consecutiveLineBreakCount = ${consecutiveLineBreakCount}` ); if (linebreaksStartAt === null) { linebreaksStartAt = i; console.log( `211 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} linebreaksStartAt = ${linebreaksStartAt}` ); } linebreaksEndAt = str[i] === "\r" && str[i + 1] === "\n" ? i + 2 : i + 1; console.log( `217 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} linebreaksEndAt = ${linebreaksEndAt}` ); } // catch raw non-breaking spaces if (!opts.trimnbsp && str[i] === NBSP && !nbspPresent) { nbspPresent = true; console.log( `225 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} nbspPresent = ${nbspPresent}` ); } // // // // // // // // // // // LOOP'S MIDDLE // // // // // // // // // // // catch the end of space character (" ") sequences if ( // spaces sequence hasn't started yet spacesStartAt !== null && // it's a space str[i] !== " " ) { console.log(`.`); console.log(`259 space sequence`); const a1 = // it's not a beginning of the string (more general whitespace clauses // will take care of trimming, taking into account opts.trimStart etc) // either it's not leading whitespace (spacesStartAt && whiteSpaceStartsAt) || // it is within frontal whitespace and (!whiteSpaceStartsAt && (!opts.trimStart || (!opts.trimnbsp && // we can't trim NBSP // and there's NBSP on one side (str[i] === NBSP || str[spacesStartAt - 1] === NBSP)))); const a2 = // it is not a trailing whitespace str[i] || !opts.trimEnd || (!opts.trimnbsp && // we can't trim NBSP // and there's NBSP on one side (str[i] === NBSP || str[spacesStartAt - 1] === NBSP)); const a3 = // beware that there might be whitespace characters (like tabs, \t) // before or after this chunk of spaces - if opts.enforceSpacesOnly // is enabled, we need to skip this clause because wider, general // whitespace chunk clauses will take care of the whole chunk, larger // than this [spacesStartAt, i - 1], it will be // [whiteSpaceStartsAt, ..., " "] // // either spaces-only setting is off, !opts.enforceSpacesOnly || // neither of surrounding characters (if present) is not whitespace ((!str[spacesStartAt - 1] || // or it's not whitespace str[spacesStartAt - 1].trim()) && // either it's end of string (!str[i] || // it's not a whitespace str[i].trim())); console.log( `297 space char seq. clause: a1=${`\u001b[${ a1 ? 32 : 31 }m${!!a1}\u001b[${39}m`} && a2=${`\u001b[${ a2 ? 32 : 31 }m${!!a2}\u001b[${39}m`} && a3=${`\u001b[${ a3 ? 32 : 31 }m${!!a3}\u001b[${39}m`} ===> ${`\u001b[${ spacesStartAt < i - 1 && a1 && a2 && a3 ? 32 : 31 }m${!!(spacesStartAt < i - 1 && a1 && a2 && a3)}\u001b[${39}m`}` ); if ( // length of spaces sequence is more than 1 spacesStartAt < i - 1 && a1 && a2 && a3 ) { console.log(`315 inside space seq. removal clauses`); const startIdx = spacesStartAt; let endIdx = i; let whatToAdd: string | null = " "; if ( opts.trimLines && // touches the start (!spacesStartAt || // touches the end !str[i] || // linebreak before (str[spacesStartAt - 1] && `\r\n`.includes(str[spacesStartAt - 1])) || // linebreak after (str[i] && `\r\n`.includes(str[i]))) ) { whatToAdd = null; } console.log( `336 initial range: [${startIdx}, ${endIdx}, ${JSON.stringify( whatToAdd, null, 0 )}]` ); // the plan is to reuse existing spaces - for example, imagine: // "a b" - three space gap. // Instead of overwriting all three spaces with single space, range: // [1, 4, " "], we leave the last space, only deleting other two: // range [1, 3] (notice the third element, "what to add" missing). if (whatToAdd && str[spacesStartAt] === " ") { console.log(`348 contract ending index`); endIdx -= 1; whatToAdd = null; console.log(`351 new range: [${startIdx}, ${endIdx}, " "]`); } // if nbsp trimming is disabled and we have a situation like: // " \xa0 a" // ^ // we're here // // we need to still trim the spaces chunk, in whole if (!spacesStartAt && opts.trimStart) { console.log(`361 - frontal chunk`); endIdx = i; console.log(`363 new range: [${startIdx}, ${endIdx}, " "]`); } else if (!str[i] && opts.trimEnd) { console.log(`365 - trailing chunk`); endIdx = i; console.log(`367 new range: [${startIdx}, ${endIdx}, " "]`); } console.log( `371 suggested range: ${`\u001b[${35}m${JSON.stringify( whatToAdd ? [startIdx, endIdx, whatToAdd] : [startIdx, endIdx], null, 0 )}\u001b[${39}m`}` ); // Notice we could push ranges to final, using standalone push() // but here we stage because general whitespace clauses need to be // aware what was "booked" so far. staging.push([ /* istanbul ignore next */ whatToAdd ? [startIdx, endIdx, whatToAdd] : [startIdx, endIdx], { whiteSpaceStartsAt, whiteSpaceEndsAt: right(str, i - 1) || i, str, }, ]); } // resets are at the bottom } // catch the start of space character (" ") sequences if ( // spaces sequence hasn't started yet spacesStartAt === null && // it's a space str[i] === " " ) { spacesStartAt = i; console.log( `404 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`spacesStartAt`}\u001b[${39}m`} = ${JSON.stringify( spacesStartAt, null, 4 )}` ); } // catch the start of whitespace chunks if ( // chunk hasn't been recording whiteSpaceStartsAt === null && // it's whitespace str[i] && !str[i].trim() ) { whiteSpaceStartsAt = i; console.log( `422 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`whiteSpaceStartsAt`}\u001b[${39}m`} = ${JSON.stringify( whiteSpaceStartsAt, null, 4 )}` ); } // catch the end of line whitespace (chunk of whitespace characters execept LF / CR) if ( // chunk has been recording lineWhiteSpaceStartsAt !== null && // and end has been met: // // either line break has been reached (`\n\r`.includes(str[i]) || // or // it's not whitespace !str[i] || str[i].trim() || // either we don't care about non-breaking spaces and trim/replace them (!(opts.trimnbsp || opts.enforceSpacesOnly) && // and we do care and it's not a non-breaking space str[i] === NBSP)) && // also, mind the trim-able whitespace at the edges... // // it's not beginning of the string (more general whitespace clauses // will take care of trimming, taking into account opts.trimStart etc) (lineWhiteSpaceStartsAt || !opts.trimStart || (opts.enforceSpacesOnly && nbspPresent)) && // it's not the ending of the string - we traverse upto and including // str.length, which means last str[i] is undefined (str[i] || !opts.trimEnd || (opts.enforceSpacesOnly && nbspPresent)) ) { console.log(`.`); console.log(`458 line whitespace clauses`); // tend opts.enforceSpacesOnly // --------------------------- if ( // setting is on opts.enforceSpacesOnly && // either chunk's longer than 1 (i > lineWhiteSpaceStartsAt + 1 || // or it's single character but not a space (yet still whitespace) str[lineWhiteSpaceStartsAt] !== " ") ) { console.log(`470 opts.enforceSpacesOnly clauses`); // also whole whitespace chunk goes, only we replace with a single space // but maybe we can reuse existing characters to reduce the footprint let startIdx = lineWhiteSpaceStartsAt; let endIdx = i; let whatToAdd: string | null = " "; if (str[endIdx - 1] === " ") { endIdx -= 1; whatToAdd = null; } else if (str[lineWhiteSpaceStartsAt] === " ") { startIdx += 1; whatToAdd = null; } // make sure it's not on the edge of string with trim options enabled, // in that case don't add the space! if ( ((opts.trimStart || opts.trimLines) && !lineWhiteSpaceStartsAt) || ((opts.trimEnd || opts.trimLines) && !str[i]) ) { whatToAdd = null; console.log( `493 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`whatToAdd`}\u001b[${39}m`} = ${JSON.stringify( whatToAdd, null, 4 )}` ); } console.log( `502 suggested range: ${`\u001b[${35}m${`[${lineWhiteSpaceStartsAt}, ${i}, " "]`}\u001b[${39}m`}` ); push(whatToAdd ? [startIdx, endIdx, whatToAdd] : [startIdx, endIdx], { whiteSpaceStartsAt: whiteSpaceStartsAt as number, whiteSpaceEndsAt: i, str, }); } // tend opts.trimLines // ------------------- if ( // setting is on opts.trimLines && // it is on the edge of a line (!lineWhiteSpaceStartsAt || `\r\n`.includes(str[lineWhiteSpaceStartsAt - 1]) || !str[i] || `\r\n`.includes(str[i])) && // and we don't care about non-breaking spaces (opts.trimnbsp || // this chunk doesn't contain any !nbspPresent) ) { console.log( `527 suggested range: ${`\u001b[${35}m${`[${lineWhiteSpaceStartsAt}, ${i}, " "]`}\u001b[${39}m`}` ); push([lineWhiteSpaceStartsAt, i], { whiteSpaceStartsAt: whiteSpaceStartsAt as number, whiteSpaceEndsAt: right(str, i - 1) || i, str, }); } lineWhiteSpaceStartsAt = null; console.log( `538 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} ${`\u001b[${33}m${`lineWhiteSpaceStartsAt`}\u001b[${39}m`} = ${JSON.stringify( lineWhiteSpaceStartsAt, null, 4 )}` ); } // Catch the start of a sequence of line whitespace (chunk of whitespace characters execept LF / CR) if ( // chunk hasn't been recording lineWhiteSpaceStartsAt === null && // we're currently not on CR or LF !`\r\n`.includes(str[i]) && // and it's whitespace str[i] && !str[i].trim() && // mind the raw non-breaking spaces (opts.trimnbsp || str[i] !== NBSP || opts.enforceSpacesOnly) ) { lineWhiteSpaceStartsAt = i; console.log( `560 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`lineWhiteSpaceStartsAt`}\u001b[${39}m`} = ${JSON.stringify( lineWhiteSpaceStartsAt, null, 4 )}` ); } // // // // // // // // // // // LOOP'S BOTTOM // // // // // // // // // // // Catch the end of whitespace chunks // This clause is deliberately under the catch clauses of the end of line // whitespace chunks because the empty, null ranges are the last thing to // be pinged to the callback. "pushed" flag must not be triggered too early. if ( // whitespace chunk has been recording whiteSpaceStartsAt !== null && // it's EOL (!str[i] || // or non-whitespace character str[i].trim()) ) { console.log(`.`); console.log(`604 general whitespace clauses`); // If there's anything staged, that must be string-only or per-line // whitespace chunks (possibly even multiple) gathered while we've been // traversing this (one) whitespace chunk. if ( // whitespace is frontal ((!whiteSpaceStartsAt && // frontal trimming is enabled (opts.trimStart || // or per-line trimming is enabled (opts.trimLines && // and we're on the same line (we don't want to remove linebreaks) linebreaksStartAt === null))) || // whitespace is trailing (!str[i] && // trailing part's trimming is enabled (opts.trimEnd || // or per-line trimming is enabled (opts.trimLines && // and we're on the same line (we don't want to remove linebreaks) linebreaksStartAt === null)))) && // either we don't care about non-breaking spaces (opts.trimnbsp || // or there are no raw non-breaking spaces in this trim-suitable chunk !nbspPresent || // or there are non-breaking spaces but they don't matter because // we want spaces-only everywhere opts.enforceSpacesOnly) ) { console.log( `635 suggested range: ${`\u001b[${35}m${`[${whiteSpaceStartsAt}, ${i}]`}\u001b[${39}m`}` ); push([whiteSpaceStartsAt, i], { whiteSpaceStartsAt, whiteSpaceEndsAt: i, str, }); } else { console.log(`643 - neither frontal nor rear`); let somethingPushed = false; // tackle the line breaks // ---------------------- if ( opts.removeEmptyLines && // there were some linebreaks recorded linebreaksStartAt !== null && // there are too many consecutiveLineBreakCount > (opts.limitConsecutiveEmptyLinesTo || 0) + 1 ) { somethingPushed = true; console.log(`657 remove the linebreak sequence`); // try to salvage some of the existing linebreaks - don't replace the // same with the same let startIdx = linebreaksStartAt; let endIdx = linebreaksEndAt || str.length; let whatToAdd: string | null = `${ str[linebreaksStartAt] === "\r" && str[linebreaksStartAt + 1] === "\n" ? "\r\n" : str[linebreaksStartAt] }`.repeat((opts.limitConsecutiveEmptyLinesTo || 0) + 1); console.log( `671 FIY, ${`\u001b[${33}m${`whatToAdd`}\u001b[${39}m`} = ${JSON.stringify( whatToAdd, null, 4 )}` ); /* istanbul ignore else */ if (str.endsWith(whatToAdd, linebreaksEndAt as number)) { console.log(`680 reuse the ending`); endIdx -= whatToAdd.length || 0; whatToAdd = null; } else if (str.startsWith(whatToAdd, linebreaksStartAt)) { console.log(`684 reuse the beginning`); startIdx += whatToAdd.length; whatToAdd = null; } console.log( `690 suggested range: ${`\u001b[${35}m${`[${startIdx}, ${endIdx}, ${JSON.stringify( whatToAdd, null, 0 )}]`}\u001b[${39}m`}` ); /* istanbul ignore next */ push(whatToAdd ? [startIdx, endIdx, whatToAdd] : [startIdx, endIdx], { whiteSpaceStartsAt, whiteSpaceEndsAt: i, str, }); } // push the staging if it exists // ----------------------------- if (staging.length) { console.log(`707 push all staged ranges into final`); while (staging.length) { // FIFO - first in, first out // @tsx-ignore push(...(staging.shift() as Staged)); } somethingPushed = true; } // if nothing has been pushed so far, push nothing to cb() // ------------------------------------------------------- if (!somethingPushed) { console.log( `720 suggested range: ${`\u001b[${35}m${`null`}\u001b[${39}m`}` ); push(null, { whiteSpaceStartsAt, whiteSpaceEndsAt: i, str, }); } } whiteSpaceStartsAt = null; lineWhiteSpaceStartsAt = null; console.log( `733 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} ${`\u001b[${33}m${`whiteSpaceStartsAt`}\u001b[${39}m`} = ${JSON.stringify( whiteSpaceStartsAt, null, 4 )}; ${`\u001b[${33}m${`lineWhiteSpaceStartsAt`}\u001b[${39}m`} = ${JSON.stringify( lineWhiteSpaceStartsAt, null, 4 )}` ); nbspPresent = false; console.log( `746 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`nbspPresent`}\u001b[${39}m`} = ${nbspPresent}` ); // reset line break counts if (consecutiveLineBreakCount) { consecutiveLineBreakCount = 0; console.log( `753 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`} consecutiveLineBreakCount = ${consecutiveLineBreakCount}` ); linebreaksStartAt = null; console.log( `757 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`} linebreaksStartAt = ${linebreaksStartAt}` ); linebreaksEndAt = null; console.log( `761 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`} linebreaksEndAt = ${linebreaksEndAt}` ); } } // rest spaces chunk starting record if (spacesStartAt !== null && str[i] !== " ") { spacesStartAt = null; console.log( `770 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} ${`\u001b[${33}m${`spacesStartAt`}\u001b[${39}m`} = ${JSON.stringify( spacesStartAt, null, 4 )}` ); } // ------------------------------------------------------------------------- console.log(`${`\u001b[${90}m${`.`}\u001b[${39}m`}`); console.log(`\u001b[${90}m${`██ ██ ██ ██ ██`}\u001b[${39}m`); console.log( `\u001b[${36}m${`spacesStartAt`}\u001b[${39}m = ${spacesStartAt}; \u001b[${36}m${`whiteSpaceStartsAt`}\u001b[${39}m = ${whiteSpaceStartsAt}; \u001b[${36}m${`lineWhiteSpaceStartsAt`}\u001b[${39}m = ${lineWhiteSpaceStartsAt}; \u001b[${36}m${`linebreaksStartAt`}\u001b[${39}m = ${linebreaksStartAt}; \u001b[${36}m${`linebreaksEndAt`}\u001b[${39}m = ${linebreaksEndAt}; \u001b[${36}m${`nbspPresent`}\u001b[${39}m = ${nbspPresent}; \u001b[${36}m${`consecutiveLineBreakCount`}\u001b[${39}m = ${consecutiveLineBreakCount}` ); console.log( `${`\u001b[${36}m${`staging`}\u001b[${39}m`} = ${JSON.stringify( staging, null, 4 )}` ); // // // // // // // // // // // LOOP ENDS // // // // // // // // // // } console.log(`822 ----------------------------`); console.log( `824 ${`\u001b[${32}m${`FINAL`}\u001b[${39}m`} ${`\u001b[${33}m${`finalIndexesToDelete`}\u001b[${39}m`} = ${JSON.stringify( finalIndexesToDelete.current(), null, 4 )}` ); return { result: rApply(str, finalIndexesToDelete.current()), ranges: finalIndexesToDelete.current(), }; } export { collapse, cbSchema, defaults, version };
the_stack
import { createLocalVue, shallowMount, Wrapper } from '@vue/test-utils'; import Vue from 'vue'; import Vuex from 'vuex'; import DataViewer from '../../src/components/DataViewer.vue'; import { buildStateWithOnePipeline, setupMockStore } from './utils'; const localVue = createLocalVue(); localVue.use(Vuex); describe('Data Viewer', () => { it('should instantiate', () => { const wrapper = shallowMount(DataViewer, { store: setupMockStore(), localVue }); expect(wrapper.exists()).toBeTruthy(); }); it('should display an empty state is no pipeline is selected', () => { const wrapper = shallowMount(DataViewer, { store: setupMockStore({}), localVue }); expect(wrapper.find('.data-viewer--no-pipeline').exists()).toBeTruthy(); expect(wrapper.find('ActionToolbar-stub').exists()).toBeFalsy(); }); it('should display a message when no data', () => { const wrapper = shallowMount(DataViewer, { store: setupMockStore(), localVue }); expect(wrapper.text()).toEqual('No data available'); }); it('should display a loader spinner when data is loading and hide data viewer container', () => { const wrapper = shallowMount(DataViewer, { store: setupMockStore( buildStateWithOnePipeline([], { isLoading: { dataset: true, uniqueValues: false }, }), ), localVue, }); const wrapperLoaderSpinner = wrapper.find('.data-viewer__loading-spinner'); const wrapperDataViewerContainer = wrapper.find('.data-viewer-container'); expect(wrapperLoaderSpinner.exists()).toBeTruthy(); expect(wrapperDataViewerContainer.exists()).toBeFalsy(); }); describe('pagination', () => { it('should display pagination if Dataset is not complete', () => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { // I let headers and data empty because I only want to test the pagination headers: [{ name: 'A' }], data: [['a']], // WARNING: the pagination context does not correspond to the headers and data above paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); expect(wrapper.find('Pagination-stub').exists()).toBeTruthy(); }); }); describe('header', () => { it('should have one row', () => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); const headerWrapper = wrapper.find('.data-viewer__header'); expect(headerWrapper.findAll('tr').length).toEqual(1); }); it('should have three cells', () => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); const headerCellsWrapper = wrapper.findAll('.data-viewer__header-cell'); expect(headerCellsWrapper.length).toEqual(3); }); describe('column names', () => { let wrapper: Wrapper<DataViewer>; const vTooltipStub = jest.fn(); beforeEach(() => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); wrapper = shallowMount(DataViewer, { store, localVue, directives: { tooltip: { bind: vTooltipStub, }, }, }); }); afterEach(() => { vTooltipStub.mockReset(); }); it("should contains column's names", () => { const headerCellsWrapper = wrapper.findAll('.data-viewer__header-cell'); expect(headerCellsWrapper.at(0).text()).toContain('columnA'); expect(headerCellsWrapper.at(1).text()).toContain('columnB'); expect(headerCellsWrapper.at(2).text()).toContain('columnC'); }); it('should have a tooltip for each column', () => { expect(vTooltipStub).toHaveBeenCalledTimes(3); }); }); it("should contains column's names even if not on every rows", () => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [ { name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }, { name: 'columnD' }, ], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15', 'value16'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); const headerCellsWrapper = wrapper.findAll('.data-viewer__header-cell'); expect(headerCellsWrapper.at(0).text()).toContain('columnA'); expect(headerCellsWrapper.at(1).text()).toContain('columnB'); expect(headerCellsWrapper.at(2).text()).toContain('columnC'); expect(headerCellsWrapper.at(3).text()).toContain('columnD'); }); it('should display the right icon and component for each types', () => { const date = new Date(); const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [ { name: 'columnA', type: 'string' }, { name: 'columnB', type: 'integer' }, { name: 'columnC', type: 'long' }, { name: 'columnD', type: 'float' }, { name: 'columnE', type: 'date' }, { name: 'columnF', type: 'object' }, { name: 'columnG', type: 'boolean' }, { name: 'columnH', type: undefined }, ], data: [['value1', 42, 3.14, date, { obj: 'value' }, true]], paginationContext: { totalCount: 10, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); const headerIconsWrapper = wrapper.findAll('.data-viewer__header-icon'); expect(headerIconsWrapper.at(0).text()).toEqual('ABC'); expect(headerIconsWrapper.at(1).text()).toEqual('123'); expect(headerIconsWrapper.at(2).text()).toEqual('123'); expect(headerIconsWrapper.at(3).text()).toEqual('1.2'); expect( headerIconsWrapper .at(4) .find('FAIcon-stub') .props().icon, ).toEqual('calendar-alt'); expect(headerIconsWrapper.at(5).text()).toEqual('{ }'); expect( headerIconsWrapper .at(6) .find('FAIcon-stub') .props().icon, ).toEqual('check'); expect(headerIconsWrapper.at(7).text()).toEqual('???'); }); it('should have a action menu for each column', async () => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); const actionMenuWrapperArray = wrapper.findAll('.data-viewer__header-action'); expect(actionMenuWrapperArray.length).toEqual(3); const oneActionMenuIcon = actionMenuWrapperArray.at(0); // there is no ActionMenu visible yet: expect(oneActionMenuIcon.find('ActionMenu-stub').exists()).toBeFalsy; // on click on icon: await oneActionMenuIcon.trigger('click'); // it should display ActionMenu: const actionMenuOpened = wrapper.findAll('ActionMenu-stub').at(0); expect(actionMenuOpened.vm.$props.visible).toBeTruthy(); expect(wrapper.findAll('ActionMenu-stub').at(1).vm.$props.visible).toBeFalsy(); expect(wrapper.findAll('ActionMenu-stub').at(2).vm.$props.visible).toBeFalsy(); // when emit close: actionMenuOpened.vm.$emit('closed'); // the Action menu disappear: expect(actionMenuOpened.vm.$props.visible).toBeFalsy(); }); it('should have a data type menu for supported backends', async () => { const store = setupMockStore( buildStateWithOnePipeline([], { translator: 'mongo40', dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [['value1', 'value2', 'value3']], paginationContext: { totalCount: 10, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); // Icons are here: expect(wrapper.findAll('.data-viewer__header-icon--active').length).toEqual(3); // DataTypesMenu is not open yet: expect(wrapper.findAll('DataTypesMenu-stub').at(0).vm.$props.visible).toBeFalsy(); // when click on icon: await wrapper .findAll('.data-viewer__header-icon--active') .at(0) .trigger('click'); // it should open the DataTypesMenu expect(wrapper.findAll('DataTypesMenu-stub').at(0).vm.$props.visible).toBeTruthy(); expect(wrapper.findAll('DataTypesMenu-stub').at(1).vm.$props.visible).toBeFalsy(); expect(wrapper.findAll('DataTypesMenu-stub').at(2).vm.$props.visible).toBeFalsy(); // when close: wrapper .findAll('DataTypesMenu-stub') .at(0) .vm.$emit('closed'); await wrapper.vm.$nextTick(); // DataTypesMenu is not open anymore: expect(wrapper.findAll('DataTypesMenu-stub').at(0).vm.$props.visible).toBeFalsy(); }); describe('changing columns', () => { let store: any, wrapper: any; const createWrapper = () => { store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); wrapper = shallowMount(DataViewer, { store, localVue }); }; it('should close the menu when the dataset is changed ...', async () => { createWrapper(); const actionMenuWrapperArray = wrapper.findAll('.data-viewer__header-action'); expect(actionMenuWrapperArray.length).toEqual(3); const oneActionMenuIcon = actionMenuWrapperArray.at(0); // there is no ActionMenu visible yet: expect(oneActionMenuIcon.find('ActionMenu-stub').exists()).toBeFalsy; // on click on icon: await oneActionMenuIcon.trigger('click'); // it should display ActionMenu: const actionMenuOpened = wrapper.findAll('ActionMenu-stub').at(0); expect(actionMenuOpened.vm.$props.visible).toBeTruthy(); // change the dataset store.commit('vqb/setDataset', { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [['value1', 'value2', 'value3']], }, }); // the Action menu disappear: expect(actionMenuOpened.vm.$props.visible).toBeFalsy(); }); it('... but not when headers are not modified', async () => { createWrapper(); await wrapper .findAll('.data-viewer__header-action') .at(0) .trigger('click'); const actionMenuOpened = wrapper.findAll('ActionMenu-stub').at(0); expect(actionMenuOpened.vm.$props.visible).toBeTruthy(); // load the values for columnA store.commit('vqb/setDataset', { dataset: { headers: [{ name: 'columnA', loaded: true }, { name: 'columnB' }, { name: 'columnC' }], data: [['value1', 'value2', 'value3']], }, }); // the action menu is still opened: expect(actionMenuOpened.vm.$props.visible).toBeTruthy(); }); }); it('should not have an icon "data type menu" for not supported backends', () => { const store = setupMockStore( buildStateWithOnePipeline([], { translator: 'mongo36', dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [['value1', 'value2', 'value3']], paginationContext: { totalCount: 10, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); expect(wrapper.find('.data-viewer__header-icon--active').exists()).toBeFalsy(); }); describe('selection', () => { it('should add an active class on the cell', async () => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); const firstHeaderCellWrapper = wrapper.find('.data-viewer__header-cell'); firstHeaderCellWrapper.trigger('click'); await localVue.nextTick(); expect(firstHeaderCellWrapper.classes()).toContain('data-viewer__header-cell--active'); }); }); }); describe('body', () => { it('should have 5 rows', () => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 100, pagesize: 50, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); const rowsWrapper = wrapper.findAll('.data-viewer__row'); expect(rowsWrapper.length).toEqual(5); }); it('should pass down the right value to DataViewerCell', () => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); const wrapper = shallowMount(DataViewer, { store, localVue }); const firstRowWrapper = wrapper.find('.data-viewer__row'); const firstCellWrapper = firstRowWrapper.find('dataviewercell-stub'); // Syntax specific to stubbed functional Vue Component expect(firstCellWrapper.attributes('value')).toEqual('value1'); }); }); describe('first column selection', () => { it('should select all first columns cells', async () => { const dataset = { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }; const store = setupMockStore(buildStateWithOnePipeline([], { dataset })); const wrapper = shallowMount(DataViewer, { store, localVue }); const firstHeadCellWrapper = wrapper.find('.data-viewer__header-cell'); firstHeadCellWrapper.trigger('click'); await localVue.nextTick(); const rowsWrapper = wrapper.findAll('.data-viewer__row'); dataset.data.forEach((_d, i) => { expect( rowsWrapper .at(i) .find('dataviewercell-stub') .classes(), ).toContain('data-viewer__cell--active'); }); }); }); describe('action clicked in ActionToolbar', () => { let wrapper: Wrapper<Vue>; const openStepFormStub = jest.fn(); beforeEach(() => { const store = setupMockStore( buildStateWithOnePipeline([], { dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [ ['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9'], ['value10', 'value11', 'value12'], ['value13', 'value14', 'value15'], ], paginationContext: { totalCount: 50, pagesize: 10, pageno: 1, }, }, }), ); wrapper = shallowMount(DataViewer, { store, localVue }); wrapper.setMethods({ openStepForm: openStepFormStub }); }); afterEach(() => { wrapper.destroy(); }); it('should open step form when click in one of toolbar button', () => { const actionToolbarWrapper = wrapper.findAll('actiontoolbar-stub').at(0); actionToolbarWrapper.vm.$emit('actionClicked', { stepName: 'rename' }); expect(openStepFormStub).toBeCalledWith({ stepName: 'rename' }); }); }); describe('without supported actions (empty supported steps)', () => { let wrapper: Wrapper<DataViewer>; beforeEach(() => { const store = setupMockStore( buildStateWithOnePipeline([], { translator: 'empty', // there is no supported actions in empty translator dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [['value1', 'value2', 'value3']], paginationContext: { totalCount: 10, pagesize: 10, pageno: 1, }, }, }), ); wrapper = shallowMount(DataViewer, { store, localVue }); }); afterEach(() => { if (wrapper) wrapper.destroy(); }); it('should remove data viewer header actions', () => { expect(wrapper.findAll('.data-viewer__header-action')).toHaveLength(0); }); it('should add a specific class to disable data viewer header', () => { const dataViewerHeaderCells = wrapper.findAll('.data-viewer__header-cell'); dataViewerHeaderCells.wrappers.forEach(wrapper => { expect(wrapper.classes()).toContain('data-viewer__header-cell--disabled'); }); }); }); });
the_stack
import { hasValue, isNotEmpty, isNotUndefined, isNull } from '../../shared/empty.util'; import { FlushPatchOperationsAction, PatchOperationsActions, JsonPatchOperationsActionTypes, NewPatchAddOperationAction, NewPatchCopyOperationAction, NewPatchMoveOperationAction, NewPatchRemoveOperationAction, NewPatchReplaceOperationAction, CommitPatchOperationsAction, StartTransactionPatchOperationsAction, RollbacktPatchOperationsAction, DeletePendingJsonPatchOperationsAction } from './json-patch-operations.actions'; import { JsonPatchOperationModel, JsonPatchOperationType } from './json-patch.model'; /** * An interface to represent JSON-PATCH Operation objects to execute */ export interface JsonPatchOperationObject { operation: JsonPatchOperationModel; timeCompleted: number; } /** * An interface to represent the body containing a list of JsonPatchOperationObject */ export interface JsonPatchOperationsEntry { body: JsonPatchOperationObject[]; } /** * Interface used to represent a JSON-PATCH path member * in JsonPatchOperationsState */ export interface JsonPatchOperationsResourceEntry { children: { [resourceId: string]: JsonPatchOperationsEntry }; transactionStartTime: number; commitPending: boolean; } /** * The JSON patch operations State * * Consists of a map with a namespace as key, * and an array of JsonPatchOperationModel as values */ export interface JsonPatchOperationsState { [resourceType: string]: JsonPatchOperationsResourceEntry; } const initialState: JsonPatchOperationsState = Object.create(null); /** * The JSON-PATCH operations Reducer * * @param state * the current state * @param action * the action to perform on the state * @return JsonPatchOperationsState * the new state */ export function jsonPatchOperationsReducer(state = initialState, action: PatchOperationsActions): JsonPatchOperationsState { switch (action.type) { case JsonPatchOperationsActionTypes.COMMIT_JSON_PATCH_OPERATIONS: { return commitOperations(state, action as CommitPatchOperationsAction); } case JsonPatchOperationsActionTypes.FLUSH_JSON_PATCH_OPERATIONS: { return flushOperation(state, action as FlushPatchOperationsAction); } case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_ADD_OPERATION: { return newOperation(state, action as NewPatchAddOperationAction); } case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_COPY_OPERATION: { return newOperation(state, action as NewPatchCopyOperationAction); } case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_MOVE_OPERATION: { return newOperation(state, action as NewPatchMoveOperationAction); } case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_REMOVE_OPERATION: { return newOperation(state, action as NewPatchRemoveOperationAction); } case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_REPLACE_OPERATION: { return newOperation(state, action as NewPatchReplaceOperationAction); } case JsonPatchOperationsActionTypes.ROLLBACK_JSON_PATCH_OPERATIONS: { return rollbackOperations(state, action as RollbacktPatchOperationsAction); } case JsonPatchOperationsActionTypes.START_TRANSACTION_JSON_PATCH_OPERATIONS: { return startTransactionPatchOperations(state, action as StartTransactionPatchOperationsAction); } case JsonPatchOperationsActionTypes.DELETE_PENDING_JSON_PATCH_OPERATIONS: { return deletePendingOperations(state, action as DeletePendingJsonPatchOperationsAction); } default: { return state; } } } /** * Set the transaction start time. * * @param state * the current state * @param action * an StartTransactionPatchOperationsAction * @return JsonPatchOperationsState * the new state. */ function startTransactionPatchOperations(state: JsonPatchOperationsState, action: StartTransactionPatchOperationsAction): JsonPatchOperationsState { if (hasValue(state[ action.payload.resourceType ]) && isNull(state[ action.payload.resourceType ].transactionStartTime)) { return Object.assign({}, state, { [action.payload.resourceType]: Object.assign({}, state[ action.payload.resourceType ], { transactionStartTime: action.payload.startTime, commitPending: true }) }); } else { return state; } } /** * Set commit pending state. * * @param state * the current state * @param action * an CommitPatchOperationsAction * @return JsonPatchOperationsState * the new state, with the section new validity status. */ function commitOperations(state: JsonPatchOperationsState, action: CommitPatchOperationsAction): JsonPatchOperationsState { if (hasValue(state[ action.payload.resourceType ]) && state[ action.payload.resourceType ].commitPending) { return Object.assign({}, state, { [action.payload.resourceType]: Object.assign({}, state[ action.payload.resourceType ], { commitPending: false }) }); } else { return state; } } /** * Set commit pending state. * * @param state * the current state * @param action * an RollbacktPatchOperationsAction * @return JsonPatchOperationsState * the new state. */ function rollbackOperations(state: JsonPatchOperationsState, action: RollbacktPatchOperationsAction): JsonPatchOperationsState { if (hasValue(state[ action.payload.resourceType ]) && state[ action.payload.resourceType ].commitPending) { return Object.assign({}, state, { [action.payload.resourceType]: Object.assign({}, state[ action.payload.resourceType ], { transactionStartTime: null, commitPending: false }) }); } else { return state; } } /** * Set the JsonPatchOperationsState to its initial value. * * @param state * the current state * @param action * an DeletePendingJsonPatchOperationsAction * @return JsonPatchOperationsState * the new state. */ function deletePendingOperations(state: JsonPatchOperationsState, action: DeletePendingJsonPatchOperationsAction): JsonPatchOperationsState { return null; } /** * Add new JSON patch operation list. * * @param state * the current state * @param action * an NewPatchAddOperationAction * @return JsonPatchOperationsState * the new state, with the section new validity status. */ function newOperation(state: JsonPatchOperationsState, action): JsonPatchOperationsState { const newState = Object.assign({}, state); const body: any[] = hasValidBody(newState, action.payload.resourceType, action.payload.resourceId) ? newState[ action.payload.resourceType ].children[ action.payload.resourceId ].body : Array.of(); const newBody = addOperationToList( body, action.type, action.payload.path, hasValue(action.payload.value) ? action.payload.value : null, hasValue(action.payload.from) ? action.payload.from : null); if (hasValue(newState[ action.payload.resourceType ]) && hasValue(newState[ action.payload.resourceType ].children)) { return Object.assign({}, state, { [action.payload.resourceType]: Object.assign({}, state[ action.payload.resourceType ], { children: Object.assign({}, state[ action.payload.resourceType ].children, { [action.payload.resourceId]: { body: newBody, } }), commitPending: isNotUndefined(state[ action.payload.resourceType ].commitPending) ? state[ action.payload.resourceType ].commitPending : false }) }); } else { return Object.assign({}, state, { [action.payload.resourceType]: Object.assign({}, { children: { [action.payload.resourceId]: { body: newBody, } }, transactionStartTime: null, commitPending: false }) }); } } /** * Check if state has a valid body. * * @param state * the current state * @param resourceType * an resource type * @param resourceId * an resource ID * @return boolean */ function hasValidBody(state: JsonPatchOperationsState, resourceType: any, resourceId: any): boolean { return (hasValue(state[ resourceType ]) && hasValue(state[ resourceType ].children) && hasValue(state[ resourceType ].children[ resourceId ]) && isNotEmpty(state[ resourceType ].children[ resourceId ].body)); } /** * Set the section validity. * * @param state * the current state * @param action * an FlushPatchOperationsAction * @return SubmissionObjectState * the new state, with the section new validity status. */ function flushOperation(state: JsonPatchOperationsState, action: FlushPatchOperationsAction): JsonPatchOperationsState { if (hasValue(state[ action.payload.resourceType ])) { let newChildren; if (isNotUndefined(action.payload.resourceId)) { // flush only specified child's operations if (hasValue(state[ action.payload.resourceType ].children) && hasValue(state[ action.payload.resourceType ].children[ action.payload.resourceId ])) { newChildren = Object.assign({}, state[ action.payload.resourceType ].children, { [action.payload.resourceId]: { body: state[ action.payload.resourceType ].children[ action.payload.resourceId ].body .filter((entry) => entry.timeCompleted > state[ action.payload.resourceType ].transactionStartTime) } }); } else { newChildren = state[ action.payload.resourceType ].children; } } else { // flush all children's operations newChildren = state[ action.payload.resourceType ].children; Object.keys(newChildren) .forEach((resourceId) => { newChildren = Object.assign({}, newChildren, { [resourceId]: { body: newChildren[ resourceId ].body .filter((entry) => entry.timeCompleted > state[ action.payload.resourceType ].transactionStartTime) } }); }); } return Object.assign({}, state, { [action.payload.resourceType]: Object.assign({}, state[ action.payload.resourceType ], { children: newChildren, transactionStartTime: null, }) }); } else { return state; } } /** * Add a new operation to a patch * * @param body * The current patch * @param actionType * The type of operation to add * @param targetPath * The path for the operation * @param value * The new value * @param fromPath * The previous path (in case of a move operation) */ function addOperationToList(body: JsonPatchOperationObject[], actionType, targetPath, value?, fromPath?) { const newBody = Array.from(body); switch (actionType) { case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_ADD_OPERATION: newBody.push(makeOperationEntry({ op: JsonPatchOperationType.add, path: targetPath, value: value })); break; case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_REPLACE_OPERATION: newBody.push(makeOperationEntry({ op: JsonPatchOperationType.replace, path: targetPath, value: value })); break; case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_REMOVE_OPERATION: newBody.push(makeOperationEntry({ op: JsonPatchOperationType.remove, path: targetPath })); break; case JsonPatchOperationsActionTypes.NEW_JSON_PATCH_MOVE_OPERATION: newBody.push(makeOperationEntry({ op: JsonPatchOperationType.move, from: fromPath, path: targetPath })); break; } return newBody; } function makeOperationEntry(operation) { return { operation: operation, timeCompleted: new Date().getTime() }; }
the_stack
import { Contracts } from "@arkecosystem/platform-sdk"; import { BIP39 } from "@arkecosystem/platform-sdk-crypto"; import { Contracts as ProfilesContracts } from "@arkecosystem/platform-sdk-profiles"; import { within } from "@testing-library/react"; import { renderHook } from "@testing-library/react-hooks"; import { Form } from "app/components/Form"; import { toasts } from "app/services"; import React from "react"; import { useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { act } from "react-test-renderer"; import secondSignatureFixture from "tests/fixtures/coins/ark/devnet/transactions/second-signature-registration.json"; import { TransactionFees } from "types"; import * as utils from "utils/electron-utils"; import { env, fireEvent, getDefaultProfileId, MNEMONICS, render, screen, waitFor } from "utils/testing-library"; import { translations as transactionTranslations } from "../../i18n"; import { SecondSignatureRegistrationForm } from "./SecondSignatureRegistrationForm"; describe("SecondSignatureRegistrationForm", () => { const passphrase = "power return attend drink piece found tragic fire liar page disease combine"; let profile: ProfilesContracts.IProfile; let wallet: ProfilesContracts.IReadWriteWallet; let fees: TransactionFees; beforeEach(() => { profile = env.profiles().findById(getDefaultProfileId()); wallet = profile.wallets().first(); fees = { avg: "1.354", max: "10", min: "0", }; }); const createTransactionMock = (wallet: ProfilesContracts.IReadWriteWallet) => // @ts-ignore jest.spyOn(wallet.transaction(), "transaction").mockReturnValue({ amount: () => secondSignatureFixture.data.amount / 1e8, data: () => ({ data: () => secondSignatureFixture.data }), explorerLink: () => `https://dexplorer.ark.io/transaction/${secondSignatureFixture.data.id}`, fee: () => secondSignatureFixture.data.fee / 1e8, id: () => secondSignatureFixture.data.id, recipient: () => secondSignatureFixture.data.recipient, sender: () => secondSignatureFixture.data.sender, }); const Component = ({ form, onSubmit, activeTab = 1, }: { form: ReturnType<typeof useForm>; onSubmit: () => void; activeTab?: number; }) => ( <Form context={form} onSubmit={onSubmit}> <SecondSignatureRegistrationForm.component profile={profile} activeTab={activeTab} fees={fees} wallet={wallet} /> </Form> ); it("should render generation step", async () => { const { result } = renderHook(() => useForm()); const passphrase = "mock bip39 passphrase"; const bip39GenerateMock = jest.spyOn(BIP39, "generate").mockReturnValue(passphrase); act(() => { const { asFragment } = render(<Component form={result.current} onSubmit={() => void 0} activeTab={1} />); expect(asFragment()).toMatchSnapshot(); }); await waitFor(() => expect(result.current.getValues("secondMnemonic")).toEqual(passphrase)); await waitFor(() => expect(screen.getByTestId("SecondSignatureRegistrationForm__generation-step"))); bip39GenerateMock.mockRestore(); }); it("should set fee", async () => { const { result } = renderHook(() => useForm()); result.current.register("fee"); result.current.register("inputFeeSettings"); const { rerender } = render(<Component form={result.current} onSubmit={() => void 0} />); // simple expect(screen.getAllByRole("radio")[1]).toBeChecked(); act(() => { fireEvent.click(within(screen.getByTestId("InputFee")).getAllByRole("radio")[2]); }); rerender(<Component form={result.current} onSubmit={() => void 0} />); expect(screen.getAllByRole("radio")[2]).toBeChecked(); // advanced act(() => { fireEvent.click(screen.getByText(transactionTranslations.INPUT_FEE_VIEW_TYPE.ADVANCED)); }); rerender(<Component form={result.current} onSubmit={() => void 0} />); expect(screen.getByTestId("InputCurrency")).toBeVisible(); act(() => { fireEvent.change(screen.getByTestId("InputCurrency"), { target: { value: "9", }, }); }); expect(screen.getByTestId("InputCurrency")).toHaveValue("9"); }); describe("backup step", () => { it("should render", async () => { const { result } = renderHook(() => useForm({ defaultValues: { secondMnemonic: "test mnemonic", wallet: { address: () => "address", }, }, }), ); const { asFragment } = render(<Component form={result.current} onSubmit={() => void 0} activeTab={2} />); await waitFor(() => expect(screen.getByTestId("SecondSignatureRegistrationForm__backup-step")).toBeTruthy(), ); const writeTextMock = jest.fn(); const clipboardOriginal = navigator.clipboard; // @ts-ignore navigator.clipboard = { writeText: writeTextMock }; act(() => { fireEvent.click(screen.getByTestId("SecondSignature__copy")); }); await waitFor(() => expect(writeTextMock).toHaveBeenCalledWith("test mnemonic")); // @ts-ignore navigator.clipboard = clipboardOriginal; expect(asFragment()).toMatchSnapshot(); }); it("should show success toast on succesfull download", async () => { const { result } = renderHook(() => useForm({ defaultValues: { secondMnemonic: "test mnemonic", wallet: { address: () => "address", }, }, }), ); render(<Component form={result.current} onSubmit={() => void 0} activeTab={2} />); jest.spyOn(utils, "saveFile").mockResolvedValueOnce("filePath"); const toastSpy = jest.spyOn(toasts, "success"); await act(async () => { fireEvent.click(screen.getByTestId("SecondSignature__download")); }); expect(toastSpy).toHaveBeenCalled(); toastSpy.mockRestore(); }); it("should not show success toast on cancelled download", async () => { const { result } = renderHook(() => useForm({ defaultValues: { secondMnemonic: "test mnemonic", wallet: { address: () => "address", }, }, }), ); render(<Component form={result.current} onSubmit={() => void 0} activeTab={2} />); jest.spyOn(utils, "saveFile").mockResolvedValueOnce(undefined); const toastSpy = jest.spyOn(toasts, "success"); await act(async () => { fireEvent.click(screen.getByTestId("SecondSignature__download")); }); expect(toastSpy).not.toHaveBeenCalled(); toastSpy.mockRestore(); }); it("should show error toast on error", async () => { const { result } = renderHook(() => useForm({ defaultValues: { secondMnemonic: "test mnemonic", wallet: { address: () => "address", }, }, }), ); render(<Component form={result.current} onSubmit={() => void 0} activeTab={2} />); jest.spyOn(utils, "saveFile").mockRejectedValueOnce(new Error("Error")); const toastSpy = jest.spyOn(toasts, "error"); await act(async () => { fireEvent.click(screen.getByTestId("SecondSignature__download")); }); expect(toastSpy).toHaveBeenCalled(); toastSpy.mockRestore(); }); }); it("should render verification step", async () => { const { result, waitForNextUpdate } = renderHook(() => useForm({ defaultValues: { secondMnemonic: passphrase, }, }), ); render(<Component form={result.current} onSubmit={() => void 0} activeTab={3} />); await waitFor(() => expect(screen.getByTestId("SecondSignatureRegistrationForm__verification-step")).toBeTruthy(), ); expect(result.current.getValues("verification")).toBeUndefined(); const walletMnemonic = passphrase.split(" "); for (let index = 0; index < 3; index++) { const wordNumber = Number.parseInt(screen.getByText(/Select the/).innerHTML.replace(/Select the/, "")); act(() => { fireEvent.click(screen.getByText(walletMnemonic[wordNumber - 1])); }); if (index < 2) { await waitFor(() => expect(screen.queryAllByText(/The (\d+)/).length === 2 - index)); } } await waitForNextUpdate(); await waitFor(() => expect(result.current.getValues("verification")).toBe(true)); }); it("should render review step", async () => { const { result } = renderHook(() => useForm({ defaultValues: { fee: 0, }, }), ); result.current.register("fee"); render(<Component form={result.current} onSubmit={() => void 0} activeTab={4} />); await waitFor(() => expect(screen.getByTestId("SecondSignatureRegistrationForm__review-step")).toBeTruthy()); }); it("should render transaction details", async () => { const DetailsComponent = () => { const { t } = useTranslation(); return ( <SecondSignatureRegistrationForm.transactionDetails translations={t} transaction={transaction} wallet={wallet} /> ); }; const transaction = { amount: () => secondSignatureFixture.data.amount / 1e8, data: () => ({ data: () => secondSignatureFixture.data }), fee: () => secondSignatureFixture.data.fee / 1e8, id: () => secondSignatureFixture.data.id, recipient: () => secondSignatureFixture.data.recipient, sender: () => secondSignatureFixture.data.sender, } as Contracts.SignedTransactionData; const { asFragment } = render(<DetailsComponent />); await waitFor(() => expect(screen.getByTestId("TransactionFee")).toBeTruthy()); expect(asFragment()).toMatchSnapshot(); }); it("should sign transaction", async () => { const form = { clearErrors: jest.fn(), getValues: () => ({ fee: "1", mnemonic: MNEMONICS[0], secondMnemonic: MNEMONICS[1], senderAddress: wallet.address(), }), setError: jest.fn(), setValue: jest.fn(), }; const signMock = jest .spyOn(wallet.transaction(), "signSecondSignature") .mockReturnValue(Promise.resolve(secondSignatureFixture.data.id)); const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({ accepted: [secondSignatureFixture.data.id], errors: {}, rejected: [], }); const transactionMock = createTransactionMock(wallet); await SecondSignatureRegistrationForm.signTransaction({ env, form, profile, }); expect(signMock).toHaveBeenCalled(); expect(broadcastMock).toHaveBeenCalled(); expect(transactionMock).toHaveBeenCalled(); signMock.mockRestore(); broadcastMock.mockRestore(); transactionMock.mockRestore(); }); it("should sign transaction using encryption password", async () => { const walletUsesWIFMock = jest.spyOn(wallet.wif(), "exists").mockReturnValue(true); const walletWifMock = jest.spyOn(wallet.wif(), "get").mockImplementation(() => { const wif = "S9rDfiJ2ar4DpWAQuaXECPTJHfTZ3XjCPv15gjxu4cHJZKzABPyV"; return Promise.resolve(wif); }); const form = { clearErrors: jest.fn(), getValues: () => ({ encryptionPassword: "password", fee: "1", senderAddress: wallet.address(), }), setError: jest.fn(), setValue: jest.fn(), }; const signMock = jest .spyOn(wallet.transaction(), "signSecondSignature") .mockReturnValue(Promise.resolve(secondSignatureFixture.data.id)); const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({ accepted: [secondSignatureFixture.data.id], errors: {}, rejected: [], }); const transactionMock = createTransactionMock(wallet); await SecondSignatureRegistrationForm.signTransaction({ env, form, profile, }); expect(signMock).toHaveBeenCalled(); expect(broadcastMock).toHaveBeenCalled(); expect(transactionMock).toHaveBeenCalled(); signMock.mockRestore(); broadcastMock.mockRestore(); transactionMock.mockRestore(); walletUsesWIFMock.mockRestore(); walletWifMock.mockRestore(); }); });
the_stack
import dotenv from "dotenv"; dotenv.config(); import ArbitrageSchema, { Arbitrage, ArbitrageState } from "./schemas/arbitrage.schema"; import { Logger } from "tslog"; import isAfter from "date-fns/isAfter"; import sub from "date-fns/sub"; import { LeanDocument } from "mongoose"; import { binance } from "ccxt.pro"; import { Order, Params } from "ccxt"; const log: Logger = new Logger(); export const getArbitrageOpportunitiesByState = async (state: ArbitrageState): Promise<LeanDocument<Arbitrage>[]> => { return ArbitrageSchema.find({ state: state }).lean().exec(); }; export const setArbitrageOpportunityState = async ( id: string, state: ArbitrageState ): Promise<LeanDocument<Arbitrage>> => { return ArbitrageSchema.findByIdAndUpdate(id, { state: state }, { new: true }).lean().exec(); }; export const isArbitrageOpportunityApproachingTradingStart = ( arbitrageOpportunity: LeanDocument<Arbitrage> ): boolean => { const triggerDate = sub(new Date(arbitrageOpportunity.tradingStartDate), { minutes: 1, }); if (isAfter(new Date(), triggerDate)) { log.info( "Arbitrage opportunity trading start is approaching in 1 minutes or less. Marking as ready for trading" ); return true; } log.info("Waiting for trading date to approach...."); return false; }; // export interface BaseOfPair { // usd: string; // busd: string; // eth: string; // btc: string; // bnb: string; // } export type PairBases = "usdt" | "busd" | "bnb" | "eth" | "btc"; export type TradingPairs = Record<Partial<PairBases>, string>; export const extractTradingPairs = (arbitrageOpportunity: LeanDocument<Arbitrage>): TradingPairs => { const tradingPairs = {} as TradingPairs; const busdPair = arbitrageOpportunity.tokenPairs.filter((tokenPair) => { return tokenPair.toLowerCase().includes("busd"); }); if (busdPair && busdPair[0]) { tradingPairs.busd = busdPair[0]; } const usdtPair = arbitrageOpportunity.tokenPairs.filter((tokenPair) => { return tokenPair.toLowerCase().includes("usdt"); }); if (usdtPair && usdtPair[0]) { tradingPairs.usdt = usdtPair[0]; } const bnbPair = arbitrageOpportunity.tokenPairs.filter((tokenPair) => { return tokenPair.toLowerCase().includes("bnb"); }); if (bnbPair && bnbPair[0]) { tradingPairs.bnb = bnbPair[0]; } const ethPair = arbitrageOpportunity.tokenPairs.filter((tokenPair) => { return tokenPair.toLowerCase().includes("eth"); }); if (ethPair && ethPair[0]) { tradingPairs.eth = ethPair[0]; } const btcPair = arbitrageOpportunity.tokenPairs.filter((tokenPair) => { return tokenPair.toLowerCase().includes("btc"); }); if (btcPair && btcPair[0]) { tradingPairs.btc = btcPair[0]; } return tradingPairs; }; export const tryToCreateOrder = async ( exchange: binance, symbol: string, type: string, side: "buy" | "sell", amount?: number, price?: number, params?: Params ): Promise<Order | boolean> => { try { const order = await exchange.createOrder(symbol, type, side, amount, price, params); return order; } catch (e) { log.error(e.constructor.name, e.message); return false; } }; export const buy = async (tradingPair: string, amountToBuy: number, exchange: binance): Promise<Order> => { let order: boolean | Order = false; while (true) { log.debug(`Attempting to buy ${amountToBuy} ${tradingPair}`); order = await tryToCreateOrder(exchange, tradingPair, "market", "buy", null, null, { quoteOrderQty: amountToBuy, }); if (order !== false) { break; } } if (order) { return order as Order; } }; export const sell = async (tradingPair: string, amountToSell: number, exchange: binance): Promise<Order> => { let order: boolean | Order = false; while (true) { log.debug(`Attempting to sell ${amountToSell} ${tradingPair}`); order = await tryToCreateOrder( exchange, tradingPair, "market", "sell", exchange.amount_to_precision(tradingPair, amountToSell) ); if (order !== false) { break; } } if (order) { return order as Order; } }; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const checkMinimumAmount = (usdAmount: number, _exchange: binance, _market: string): boolean => { if (usdAmount >= 10) { return true; } return false; }; export const convertBaseToBusd = async ( from: PairBases, availableBaseAmount: number, exchange: binance ): Promise<number> => { let busdPrice: number; switch (from) { case "usdt": busdPrice = (await exchange.fetchTicker("BUSD/USDT")).ask; return availableBaseAmount * busdPrice; case "busd": return availableBaseAmount; case "bnb": busdPrice = (await exchange.fetchTicker("BNB/BUSD")).bid; return availableBaseAmount * busdPrice; case "eth": busdPrice = (await exchange.fetchTicker("ETH/BUSD")).bid; return availableBaseAmount * busdPrice; case "btc": busdPrice = (await exchange.fetchTicker("BTC/BUSD")).bid; return availableBaseAmount * busdPrice; default: throw new Error("unknown base in conversion: " + from); } }; export const swapCurrency = async ( from: PairBases, to: PairBases, amount: number, exchange: binance ): Promise<Order | void> => { log.debug(`swapping ${amount} ${from}/${to}`); let orderQty: number; let calculatedAmount: number; let availableAmount: number; let sellableAmount: number; const balances = await exchange.fetchBalance(); switch (from) { case "usdt": switch (to) { case "busd": orderQty = exchange.amount_to_precision("BUSD/USDT", amount); log.debug(`orderQty: ${orderQty}; amount: ${amount};`); if (checkMinimumAmount(amount, exchange, "BUSD/USDT")) { log.debug("proceeding with BUSD/USDT order"); return exchange.createOrder("BUSD/USDT", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "bnb": orderQty = exchange.amount_to_precision("BNB/USDT", amount); if (checkMinimumAmount(amount, exchange, "BNB/USDT")) { return exchange.createOrder("BNB/USDT", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "eth": orderQty = exchange.amount_to_precision("ETH/USDT", amount); if (checkMinimumAmount(amount, exchange, "ETH/USDT")) { return exchange.createOrder("ETH/USDT", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "btc": orderQty = exchange.amount_to_precision("BTC/USDT", amount); if (checkMinimumAmount(amount, exchange, "BTC/USDT")) { return exchange.createOrder("BTC/USDT", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); } break; case "busd": switch (to) { case "usdt": const BusdUsdtSellPrice = (await exchange.fetchTicker("BUSD/USDT")).bid; calculatedAmount = amount * BusdUsdtSellPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("BUSD/USDT", sellableAmount); if (checkMinimumAmount(amount, exchange, "BUSD/USDT")) { return exchange.createOrder("BUSD/USDT", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "bnb": orderQty = exchange.amount_to_precision("BNB/BUSD", amount); if (checkMinimumAmount(amount, exchange, "BNB/BUSD")) { return exchange.createOrder("BNB/BUSD", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "eth": orderQty = exchange.amount_to_precision("ETH/BUSD", amount); if (checkMinimumAmount(amount, exchange, "ETH/BUSD")) { return exchange.createOrder("ETH/BUSD", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "btc": orderQty = exchange.amount_to_precision("BTC/BUSD", amount); if (checkMinimumAmount(amount, exchange, "BTC/BUSD")) { log.warn(`Creating BUSD/BTC Order for: ${orderQty}`); return exchange.createOrder("BTC/BUSD", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); } break; case "bnb": const BnbBusdPrice = (await exchange.fetchTicker("BNB/BUSD")).bid; const BnbUsdtPrice = (await exchange.fetchTicker("BNB/USDT")).bid; switch (to) { case "usdt": calculatedAmount = amount * BnbUsdtPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("BNB/USDT", sellableAmount); if (checkMinimumAmount(amount, exchange, "BNB/USDT")) { return exchange.createOrder("BNB/USDT", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "busd": calculatedAmount = amount * BnbBusdPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("BNB/BUSD", sellableAmount); log.debug(`orderQty: ${orderQty}; amount: ${amount};`); if (checkMinimumAmount(amount, exchange, "BNB/BUSD")) { log.debug("proceeding with BNB/BUSD order"); return exchange.createOrder("BNB/BUSD", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "eth": calculatedAmount = amount * BnbBusdPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("BNB/ETH", sellableAmount); if (checkMinimumAmount(amount, exchange, "BNB/ETH")) { return exchange.createOrder("BNB/ETH", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "btc": calculatedAmount = amount * BnbBusdPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("BNB/BTC", sellableAmount); if (checkMinimumAmount(amount, exchange, "BNB/BTC")) { return exchange.createOrder("BNB/BTC", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); } break; case "eth": const EthUsdtPrice = (await exchange.fetchTicker("ETH/USDT")).bid; const EthBusdPrice = (await exchange.fetchTicker("ETH/USDT")).bid; switch (to) { case "usdt": calculatedAmount = amount * EthUsdtPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("ETH/USDT", sellableAmount); if (checkMinimumAmount(amount, exchange, "ETH/USDT")) { return exchange.createOrder("ETH/USDT", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "busd": calculatedAmount = amount * EthBusdPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("ETH/BUSD", sellableAmount); if (checkMinimumAmount(amount, exchange, "ETH/BUSD")) { return exchange.createOrder("ETH/BUSD", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "bnb": const EthBusdBuyPrice = (await exchange.fetchTicker("ETH/BUSD")).bid; orderQty = exchange.amount_to_precision("BNB/ETH", amount / EthBusdBuyPrice); if (checkMinimumAmount(amount, exchange, "BNB/ETH")) { return exchange.createOrder("BNB/ETH", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "btc": calculatedAmount = amount / EthBusdPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("ETH/BTC", sellableAmount); if (checkMinimumAmount(amount, exchange, "ETH/BTC")) { return exchange.createOrder("ETH/BTC", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); } break; case "btc": const BtcBusdSellPrice = (await exchange.fetchTicker("BTC/BUSD")).bid; const BtcBusdBuyPrice = (await exchange.fetchTicker("BTC/BUSD")).ask; switch (to) { case "usdt": calculatedAmount = amount / BtcBusdSellPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("BTC/USDT", sellableAmount); if (checkMinimumAmount(amount, exchange, "BTC/USDT")) { return exchange.createOrder("BTC/USDT", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "busd": calculatedAmount = amount * BtcBusdSellPrice; availableAmount = balances[from.toUpperCase()].free; sellableAmount = calculatedAmount > availableAmount ? availableAmount : calculatedAmount; orderQty = exchange.amount_to_precision("BTC/BUSD", sellableAmount); log.debug(`orderQty: ${orderQty}; amount: ${amount}; BtcBusdSellPrice: ${BtcBusdSellPrice}`); if (checkMinimumAmount(amount, exchange, "BTC/BUSD")) { log.debug("proceeding with BTC/BUSD order"); return exchange.createOrder("BTC/BUSD", "market", "sell", orderQty); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "bnb": orderQty = exchange.amount_to_precision("BNB/BTC", amount / BtcBusdBuyPrice); if (checkMinimumAmount(amount, exchange, "BNB/BTC")) { return exchange.createOrder("BNB/BTC", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); case "eth": orderQty = exchange.amount_to_precision("ETH/BTC", amount / BtcBusdBuyPrice); if (checkMinimumAmount(amount, exchange, "ETH/BTC")) { return exchange.createOrder("ETH/BTC", "market", "buy", null, null, { quoteOrderQty: orderQty, }); } log.warn(`Minimum amount not met: ${amount}`); return Promise.resolve(); } break; default: break; } };
the_stack
import type { SFCBlock, SFCDescriptor, SFCScriptBlock, SFCStyleBlock, SFCTemplateBlock, } from '@vuedx/compiler-sfc' import { CompilerError, parse } from '@vuedx/compiler-sfc' import { getComponentName, isNotNull } from '@vuedx/shared' import { isPlainElementNode, RootNode } from '@vuedx/template-ast-types' import * as Path from 'path' import { parse as parseQueryString } from 'querystring' import { TextDocument, TextDocumentContentChangeEvent, } from 'vscode-languageserver-textdocument' import { BlockTransformer, builtins } from './BlockTransformer' import { ProxyDocument } from './ProxyDocument' import { VueBlockDocument } from './VueBlockDocument' export interface VueSFCDocumentOptions { transformers?: Record<string, BlockTransformer> } export class VueSFCDocument extends ProxyDocument { private readonly _tsFileName: string private constructor( private readonly _fileName: string, private readonly _options: Required<VueSFCDocumentOptions>, source: TextDocument, ) { super(source) this._tsFileName = `${this.fileName}.ts` } public get fileName(): string { return this._fileName } public get tsFileName(): string { return this._tsFileName } public get options(): Readonly<Required<VueSFCDocumentOptions>> { return this._options } private _isDirty = true private _descriptor: SFCDescriptor | null = null private _errors: Array<CompilerError | SyntaxError> = [] private _mainText: string = '' private readonly blockDocs = new Map<string, VueBlockDocument>() public templateAST: RootNode | null = null // Used by tsserver for caching line map public lineMap: any public get text(): string { return this.getText() } public readonly fallbackScript: SFCScriptBlock = { loc: { source: '', start: { offset: 0, line: 0, column: 0 }, end: { offset: 0, line: 0, column: 0 }, }, type: 'script', attrs: { fallback: true }, content: `import { defineComponent } from 'vue'\nexport default defineComponent({})\n`, } public declarations = { identifiers: new Set<string>(), } public get descriptor(): SFCDescriptor { return this._parse() } public get errors(): Array<CompilerError | SyntaxError> { this._parse() return this._errors } public get blocks(): SFCBlock[] { const descriptor = this.descriptor return [ descriptor.scriptSetup, descriptor.script, descriptor.template, ...descriptor.styles, ...descriptor.customBlocks, ].filter(isNotNull) } private _activeTSDocIDs = new Set<string>() public getActiveTSDocIDs(): Set<string> { this._parse() return this._activeTSDocIDs } public getTypeScriptText(): string { this._parse() return this._mainText } public getDocById(id: string): VueBlockDocument | null { this._parse() const block = this._getBlockFromId(id) if (block == null) { console.debug(`[VueDX] No block for "${id}"`) return null } return this.getDoc(block) } public getDoc(block: SFCBlock): VueBlockDocument | null { this._parse() return this._getBlockDocument(block) } public getBlockId(block: SFCBlock): string { this._parse() return this._getBlockFileName(block) } public getBlockAt(offset: number): SFCBlock | null { this._parse() const block = this.blocks.find( (block) => block.loc.start.offset <= offset && offset <= block.loc.end.offset, ) return block ?? null } public getDocAt(offset: number): VueBlockDocument | null { this._parse() const block = this.getBlockAt(offset) if (block != null) return this.getDoc(block) return null } private _getBlockDocument(block: SFCBlock, index?: number): VueBlockDocument { const id = this._getBlockFileName(block, index) const existing = this.blockDocs.get(id) if (existing != null) return existing const transformer = this.options.transformers[block.type] const doc = new VueBlockDocument( id, this, this._createBlockGetter(block, index), () => this.descriptor, transformer, ) this.blockDocs.set(id, doc) return doc } private _createBlockGetter( block: SFCBlock | SFCTemplateBlock | SFCScriptBlock | SFCStyleBlock, index: number = 0, ): () => SFCBlock { switch (block.type) { case 'template': return () => this._descriptor?.template ?? block case 'script': return 'setup' in block && block.setup != null && block.setup !== false ? () => this._descriptor?.scriptSetup ?? block : () => this._descriptor?.script ?? block case 'style': return () => this._descriptor?.styles[index] ?? block default: return () => this._descriptor?.customBlocks[index] ?? block } } private _parse(): SFCDescriptor { if (this._descriptor == null || this._isDirty) { if (this._descriptor == null) { console.debug(`[VueDX] (SFC) Parse: ${this.fileName}`) } else { console.debug(`[VueDX] (SFC) Re-parse: ${this.fileName}`) } // TODO: Incremental SFC Parser using const result = parse(this.source.getText(), { sourceMap: false, filename: this.fileName, pad: false, }) if (this._descriptor != null) { // Delete stale documents. const prev = this._descriptor const next = result.descriptor const hasTemplateChanged = hasBlockChanged(prev.template, next.template) const hasScriptChanged = hasBlockChanged(prev.script, next.script) const hasScriptSetupChanged = hasBlockChanged( prev.scriptSetup, next.scriptSetup, ) if (hasTemplateChanged || hasScriptChanged || hasScriptSetupChanged) { if (prev.template != null) { const fileName = this._getBlockFileName(prev.template) this.blockDocs.delete(fileName) console.debug(`[VueDX] (SFC) Stale: ${fileName}`) } } if (hasScriptSetupChanged || hasTemplateChanged) { if (prev.scriptSetup != null) { const fileName = this._getBlockFileName(prev.scriptSetup) this.blockDocs.delete(fileName) console.debug(`[VueDX] (SFC) Stale: ${fileName}`) } } if (hasScriptChanged) { if (prev.script != null) { const fileName = this._getBlockFileName(prev.script) this.blockDocs.delete(fileName) console.debug(`[VueDX] (SFC) Stale: ${fileName}`) } } prev.styles.forEach((block, i) => { if ( hasBlockChanged(prev.styles[i], next.styles[i]) && block != null ) { this.blockDocs.delete(this._getBlockFileName(block, i)) } }) prev.customBlocks.forEach((block, i) => { if ( hasBlockChanged(prev.customBlocks[i], next.customBlocks[i]) && block != null ) { this.blockDocs.delete(this._getBlockFileName(block, i)) } }) } if ( result.descriptor.script == null && result.descriptor.scriptSetup == null ) { result.descriptor.script = this.fallbackScript } const code = this._generateMainModuleText(result.descriptor) this._descriptor = result.descriptor this._errors = result.errors this._mainText = code.content this._activeTSDocIDs = code.files this._isDirty = false console.debug( `[VueDX] (SFC) New Files: ${JSON.stringify( Array.from(code.files), null, 2, )}`, ) } return this._descriptor } private _generateMainModuleText( descriptor: SFCDescriptor, ): { content: string; files: Set<string> } { const { template, script, scriptSetup, styles, customBlocks } = descriptor const code: string[] = [`import 'vuedx~runtime'`] const props: string[] = [] // TODO: Detect inner element to forward attrs. const files = new Set<string>() const createImportSource = (id: string): string => JSON.stringify(`./${Path.posix.basename(id.replace(/\.[tj]sx?$/, ''))}`) if (template != null) { const id = this._getBlockTSId(template) if (id != null) { files.add(id) const node = this.templateAST?.children[0] if (isPlainElementNode(node)) { props.push(`JSX.IntrinsicElements['${node.tag}']`) } code.push(`import ${createImportSource(id)}`) } } styles.forEach((block, index) => { const id = this._getBlockTSId(block, index) if (id != null) { files.add(id) code.push(`import ${createImportSource(id)}`) } }) customBlocks.forEach((block, index) => { const id = this._getBlockTSId(block, index) if (id != null) { files.add(id) code.push(`import ${createImportSource(id)}`) } }) const name = getComponentName(this.fileName) if (scriptSetup != null) { const id = this._getBlockTSId(scriptSetup) if (id != null) { files.add(id) const idPath = createImportSource(id) props.push(`InstanceType<typeof _Self>['$props']`) code.push(`import _Self from ${idPath}`) code.push(`export * from ${idPath}`) // TODO: Only type exports are supported. if (script != null) { const id = this._getBlockTSId(script) if (id != null) { files.add(id) code.push(`export * from ${createImportSource(id)}`) } } } } else if (script != null) { const id = this._getBlockTSId(script) if (id != null) { files.add(id) const idPath = createImportSource(id) props.push(`InstanceType<typeof _Self>['$props']`) code.push(`import _Self from ${idPath}`) code.push(`export * from ${idPath}`) } } if (props.length === 0) props.push('{}') code.push(`const ${name} = _Self`) code.push(`export default ${name}`) return { content: code.join('\n'), files, } } private _getBlockFileName( block: SFCBlock | SFCScriptBlock | SFCStyleBlock | SFCTemplateBlock, index?: number, lang: string = this._getBlockLanguage(block), ): string { if (index == null && block.type !== 'script' && block.type !== 'template') { if (block.type === 'style') { index = this._descriptor?.styles.indexOf(block as any) } else { index = this._descriptor?.customBlocks.indexOf(block) } } const query = 'setup' in block && block.setup != null && block.setup !== false ? `setup=true` : undefined return createVirtualFileName(this.fileName, block, lang, query, index) } private _getBlockTSId( block: SFCBlock | SFCScriptBlock | SFCStyleBlock | SFCTemplateBlock, index?: number, ): string | null { const transformer = this.options.transformers[block.type] if (transformer == null) return null return this._getBlockFileName(block, index, transformer.output(block)) } private _getBlockLanguage(block: SFCBlock): string { if (block.lang != null) return block.lang switch (block.type) { case 'script': return 'js' case 'template': return 'vue-html' case 'style': return 'css' default: return block.type // TODO: Support extending block default language } } private _getBlockFromId( id: string, ): SFCBlock | SFCStyleBlock | SFCTemplateBlock | SFCScriptBlock | null { const offset = id.indexOf('.vue?vue') if (offset < 0) return null const query = id.substr(offset + 5) const { type, index, setup } = parseQueryString(query) as Record< string, string > if (type == null) return null if (this._descriptor == null) return null switch (type) { case 'template': return this._descriptor.template case 'script': return setup != null ? this._descriptor.scriptSetup : this._descriptor.script case 'style': if (index == null) return null return this._descriptor.styles[Number(index)] ?? null default: if (index == null) return null return this._descriptor.customBlocks[Number(index)] ?? null } } static create( fileName: string, content: string, options: VueSFCDocumentOptions = {}, version: number = 0, ): VueSFCDocument { return new VueSFCDocument( fileName, { ...options, transformers: { ...options.transformers, ...builtins, }, }, TextDocument.create(`file://${fileName}`, 'vue', version, content), ) } public update( changes: TextDocumentContentChangeEvent[], version: number, ): void { this.source = TextDocument.update(this.source, changes, version) this._isDirty = true this.lineMap = undefined console.debug( `[VueDX] (SFC) ${this.version} ${this.fileName} is marked dirty`, ) } } function createVirtualFileName( fileName: string, block: SFCBlock, lang: string, query?: string, index?: number, ): string { return `${fileName}?vue&type=${block.type}${ index != null ? `&index=${index}` : '' }${query != null ? `&${query}` : ''}&lang.${lang}` } function hasBlockChanged( a: SFCBlock | null | undefined, b: SFCBlock | null | undefined, ): boolean { if (a === b) return false if (a == null || b == null) return true if ( a.content !== b.content || a.lang !== b.lang || a.loc.start.offset !== b.loc.start.offset || a.loc.end.offset !== b.loc.end.offset ) { return true } const aKeys = Array.from(Object.keys(a.attrs)) const bKeys = new Set(Object.keys(b.attrs)) if (aKeys.length !== bKeys.size) return true if ( aKeys.some((key) => { try { return !bKeys.has(key) || a.attrs[key] !== b.attrs[key] } finally { bKeys.delete(key) } }) ) { return true } return bKeys.size > 0 }
the_stack
'use-strict'; import yaml = require('js-yaml'); import { existsSync, readFileSync } from 'fs'; import { sync } from 'glob'; import { platform } from 'os'; import { extname, join, parse, sep, resolve } from 'path'; import { DocumentLink, Extension, extensions, Position, Range, Selection, TextDocument, TextEditor, Uri, window, workspace } from 'vscode'; import { output } from './output'; export const ignoreFiles = ['.git', '.github', '.vscode', '.vs', 'node_module']; export function tryFindFile(rootPath: string, fileName: string) { let result: { path?: string; error?: any | unknown; }; try { const fullPath = resolve(rootPath, fileName); const exists = existsSync(fullPath); if (exists) { result = { path: fullPath }; } else { const files = sync(`**/${fileName}`, { cwd: rootPath }); if (files && files.length === 1) { result = { path: join(rootPath, files[0]) }; } } } catch (error) { result = { error }; } if (!result?.path) { result = traverseDirectoryToFile(rootPath, fileName); } if (result?.error) { postWarning( `Unable to find a file named "${fileName}", recursively at root "${rootPath}".\n${result?.error}` ); } return result?.path; } function traverseDirectoryToFile( rootPath: string, fileName: string ): { path?: string; error?: any | unknown; } { let error: any | unknown; try { const getParent = (dir: string) => { if (dir) { const segments = dir.split(sep); if (segments.length > 1) { segments.pop(); return segments.join(sep); } } return dir; }; const isRoot = (dir: string) => parse(dir).root === dir; let currentDirectory = rootPath; let filePath: string; while (!filePath) { const fullPath = resolve(currentDirectory, fileName); const exists = existsSync(fullPath); if (exists) { filePath = fullPath; } else { currentDirectory = getParent(currentDirectory); if (isRoot(currentDirectory)) { break; } } } return { path: filePath }; } catch (e) { error = e; } return { error }; } /** * Provide current os platform */ export function getOSPlatform(this: any) { if (this.osPlatform == null) { this.osPlatform = platform(); this.osPlatform = this.osPlatform; } return this.osPlatform; } /** * Create a posted warning message and applies the message to the log * @param {string} message - the message to post to the editor as an warning. */ export function postWarning(message: string) { window.showWarningMessage(message); } /** * Create a posted information message and applies the message to the log * @param {string} message - the message to post to the editor as an information. */ export function postInformation(message: string) { window.showInformationMessage(message); } /** * Create a posted information message and applies the message to the log * @param {string} message - the message to post to the editor as an information. */ export function postError(message: string) { window.showErrorMessage(message); } /** * Checks that there is a document open, and the document has selected text. * Displays warning to users if error is caught. * @param {vscode.TextEditor} editor - the activeTextEditor in the vscode window * @param {boolean} testSelection - test to see if the selection includes text in addition to testing a editor is open. * @param {string} senderName - the name of the command running the test. */ export function isValidEditor(editor: TextEditor, testSelection: boolean, senderName: string) { if (editor === undefined) { output.appendLine('Please open a document to apply ' + senderName + ' to.'); return false; } if (testSelection && editor.selection.isEmpty) { if ( senderName === 'format bold' || senderName === 'format italic' || senderName === 'format code' ) { output.appendLine( 'VS Code active editor has valid configuration to apply ' + senderName + ' to.' ); return true; } output.appendLine('No text selected, cannot apply ' + senderName + '.'); return false; } output.appendLine( 'VS Code active editor has valid configuration to apply ' + senderName + ' to.' ); return true; } export function noActiveEditorMessage() { postWarning('No active editor. Abandoning command.'); } export function unsupportedFileMessage(languageId: string) { postWarning(`Command is not support for "${languageId}". Abandoning command.`); } export function hasValidWorkSpaceRootPath(senderName: string) { let folderPath: string = ''; if (folderPath == null) { postWarning( 'The ' + senderName + ' command requires an active workspace. Please open VS Code from the root of your clone to continue.' ); return false; } if (workspace.workspaceFolders) { folderPath = workspace.workspaceFolders[0].uri.fsPath; } return true; } /** * Inserts or Replaces text at the current selection in the editor. * If overwrite is set the content will replace current selection. * @param {vscode.TextEditor} editor - the active editor in vs code. * @param {string} senderName - the name of the function that is calling this function * which is used to provide traceability in logging. * @param {string} string - the content to insert. * @param {boolean} overwrite - if true replaces current selection. * @param {vscode.Range} selection - if null uses the current selection for the insert or update. * If provided will insert or update at the given range. */ export async function insertContentToEditor( editor: TextEditor, content: string, overwrite: boolean = false, selection: Range = null! ) { if (selection == null) { selection = editor.selection; } try { if (overwrite) { await editor.edit(update => { update.replace(selection, content); }); } else { // Gets the cursor position const position = editor.selection.active; await editor.edit(selected => { selected.insert(position, content); }); } } catch (error) { output.appendLine('Could not write content to active editor window: ' + error); } } /** * Set the cursor to a new position, based on X and Y coordinates. * @param {vscode.TextEditor} editor - * @param {number} line - * @param {number} character - */ export function setCursorPosition(editor: TextEditor, line: number, character: number) { const cursorPosition = editor.selection.active; const newPosition = cursorPosition.with(line, character); const newSelection = new Selection(newPosition, newPosition); editor.selection = newSelection; } export function setSelectorPosition( editor: TextEditor, fromLine: number, fromCharacter: number, toLine: number, toCharacter: number ) { const fromPosition = new Position(fromLine, fromCharacter); const toPosition = new Position(toLine, toCharacter); editor.selection = new Selection(fromPosition, toPosition); } /** * Function does trim from the right on the the string. It removes specified characters. * @param {string} str - string to trim. * @param {string} chr - searched characters to trim. */ export function rtrim(str: string, chr: string) { const rgxtrim = !chr ? new RegExp('\\s+$') : new RegExp(chr + '+$'); return str.replace(rgxtrim, ''); } /** * Checks to see if the active file is markdown. * Commands should only run on markdown files. * @param {vscode.TextEditor} editor - the active editor in vs code. */ export function isMarkdownFileCheck(editor: TextEditor, languageId: boolean) { if (editor.document.languageId !== 'markdown') { if (editor.document.languageId !== 'yaml') { postInformation('The docs-markdown extension only works on Markdown files.'); } return false; } else { return true; } } export function isMarkdownFileCheckWithoutNotification(editor: TextEditor) { if (editor.document.languageId !== 'markdown') { return false; } else { return true; } } export function isMarkdownYamlFileCheckWithoutNotification(editor: TextEditor) { if (editor.document.languageId === 'markdown' || editor.document.languageId === 'yaml') { return true; } else { return false; } } export function isValidFileCheck(editor: TextEditor, languageIds: string[]) { return languageIds.some(id => editor.document.languageId === id); } /** * Telemetry or Trace Log Type */ export enum LogType { Telemetry, Trace } /** * Create timestamp */ export function generateTimestamp() { const date = new Date(Date.now()); return { msDateValue: date.toLocaleDateString('en-us'), msTimeValue: date.toLocaleTimeString([], { hour12: false }) }; } /** * Check for install extensions */ export function checkExtensionInstalled(extensionName: string, notInstalledMessage?: string) { const extension = getInstalledExtension(extensionName, notInstalledMessage); return !!extension; } /** * Check for active extensions */ export function checkExtension(extensionName: string, notInstalledMessage?: string) { const extension = getInstalledExtension(extensionName, notInstalledMessage); return !!extension && extension.isActive; } function getInstalledExtension( extensionName: string, notInstalledMessage?: string ): Extension<any> { const extensionValue = extensions.getExtension(extensionName); if (!extensionValue) { if (notInstalledMessage) { output.appendLine(notInstalledMessage); } return undefined; } return extensionValue; } /** * Output message with timestamp * @param message */ export function showStatusMessage(message: string) { const { msTimeValue } = generateTimestamp(); output.appendLine(`[${msTimeValue}] - ${message}`); } export function detectFileExtension(filePath: string) { const fileExtension = extname(filePath); return fileExtension; } /** * Create a posted error message and applies the message to the log * @param {string} message - the message to post to the editor as an error. */ export async function showWarningMessage(message: string) { await window.showWarningMessage(message); } export function matchAll(pattern: RegExp, text: string): RegExpMatchArray[] { const out: RegExpMatchArray[] = []; pattern.lastIndex = 0; let match: RegExpMatchArray | null = pattern.exec(text); while (match) { if (match) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === pattern.lastIndex) { pattern.lastIndex++; } out.push(match); } match = pattern.exec(text); } return out; } export function extractDocumentLink( document: TextDocument, link: string, matchIndex: number | undefined ): DocumentLink | undefined { const offset = (matchIndex || 0) + 8; const linkStart = document.positionAt(offset); const linkEnd = document.positionAt(offset + link.length); const text = document.getText(new Range(linkStart, linkEnd)); try { const httpMatch = text.match(/^(http|https):\/\//); if (httpMatch) { const documentLink = new DocumentLink(new Range(linkStart, linkEnd), Uri.parse(link)); return documentLink; } else { const filePath = document.fileName.split('\\').slice(0, -1).join('\\'); const documentLink = new DocumentLink( new Range(linkStart, linkEnd), Uri.file(resolve(filePath, link)) ); return documentLink; } } catch (e) { return undefined; } } export const naturalLanguageCompare = (a: string, b: string) => { return !!a && !!b ? a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) : 0; }; export function escapeRegExp(content: string) { return content.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } export function splice(insertAsPosition: number, content: string, insertStr: string) { return content.slice(0, insertAsPosition) + insertStr + content.slice(insertAsPosition); } export function toShortDate(date: Date) { const year = date.getFullYear(); const month = (1 + date.getMonth()).toString(); const monthStr = month.length > 1 ? month : `0${month}`; const day = date.getDate().toString(); const dayStr = day.length > 1 ? day : `0${day}`; return `${monthStr}/${dayStr}/${year}`; } export function findLineNumberOfPattern(editor: TextEditor, pattern: string) { const article = editor.document; let found = -1; for (let line = 0; line < article.lineCount; line++) { const text = article.lineAt(line).text; const match = text.match(pattern); if (match !== null && match.index !== undefined) { found = line; return found; } } return found; } export function isNullOrWhiteSpace(str: string) { return !str || str.length === 0 || /^\s*$/.test(str); } export function getYmlTitle(filePath: string) { try { const doc = yaml.load(readFileSync(filePath, 'utf8')); return doc.title; } catch (error) { output.appendLine(error); } }
the_stack
import { VssueAPI } from 'vssue'; import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'; import { buildURL, concatURL, getCleanURL, parseQuery } from '@vssue/utils'; import { normalizeUser, normalizeIssue, normalizeComment, normalizeReactions, mapReactionName, } from './utils'; import { ResponseAccessToken, ResponseUser, ResponseIssue, ResponseComment, ResponseLabel, ResponseMarkdown, ResponseReaction, } from './types'; /** * Gitea API V1 * * @see https://docs.gitea.io/en-us/oauth2-provider/ * @see https://docs.gitea.io/en-us/api-usage * @see https://gitea.com/api/swagger */ export default class GiteaV1 implements VssueAPI.Instance { baseURL: string; owner: string; repo: string; labels: Array<string>; clientId: string; clientSecret: string; state: string; proxy: string | ((url: string) => string); $http: AxiosInstance; constructor({ baseURL = 'https://gitea.com', owner, repo, labels, clientId, clientSecret, state, proxy, }: VssueAPI.Options) { /* istanbul ignore if */ if (typeof clientSecret === 'undefined' || typeof proxy === 'undefined') { throw new Error('clientSecret and proxy is required for Gitea V1'); } this.baseURL = baseURL; this.owner = owner; this.repo = repo; this.labels = labels; this.clientId = clientId; this.clientSecret = clientSecret; this.state = state; this.proxy = proxy; this.$http = axios.create({ baseURL: concatURL(baseURL, 'api/v1'), headers: { Accept: 'application/json', }, }); } /** * The platform api info */ get platform(): VssueAPI.Platform { return { name: 'Gitea', link: this.baseURL, version: 'v1', meta: { reactable: true, sortable: false, }, }; } /** * Redirect to the authorization page of platform. * * @see https://docs.gitea.io/en-us/oauth2-provider/ */ redirectAuth(): void { window.location.href = buildURL( concatURL(this.baseURL, 'login/oauth/authorize'), { client_id: this.clientId, redirect_uri: window.location.href, response_type: 'code', state: this.state, } ); } /** * Handle authorization. * * @see https://docs.gitea.io/en-us/oauth2-provider/ * * @remarks * If the `code` and `state` exist in the query, and the `state` matches, remove them from query, and try to get the access token. */ async handleAuth(): Promise<VssueAPI.AccessToken> { const query = parseQuery(window.location.search); if (query.code) { if (query.state !== this.state) { return null; } // the `code` from gitea is uri encoded // typically includes an encoded `=` -> `%3D` const code = decodeURIComponent(query.code); delete query.code; delete query.state; const replaceURL = buildURL(getCleanURL(window.location.href), query) + window.location.hash; window.history.replaceState(null, '', replaceURL); const accessToken = await this.getAccessToken({ code }); return accessToken; } return null; } /** * Get user access token via `code` * * @see https://docs.gitea.io/en-us/oauth2-provider/ */ async getAccessToken({ code }: { code: string }): Promise<string> { const originalURL = concatURL(this.baseURL, 'login/oauth/access_token'); const proxyURL = typeof this.proxy === 'function' ? this.proxy(originalURL) : this.proxy; const { data } = await this.$http.post<ResponseAccessToken>(proxyURL, { client_id: this.clientId, client_secret: this.clientSecret, code: code, grant_type: 'authorization_code', redirect_uri: window.location.href, }); return data.access_token; } /** * Get the logged-in user with access token. * * @see https://gitea.com/api/swagger#/user/userGetCurrent */ async getUser({ accessToken, }: { accessToken: VssueAPI.AccessToken; }): Promise<VssueAPI.User> { const { data } = await this.$http.get<ResponseUser>('user', { headers: { Authorization: `bearer ${accessToken}` }, }); return normalizeUser(data, this.baseURL); } /** * Get issue of this page according to the issue id or the issue title * * @see https://gitea.com/api/swagger#/issue/issueListIssues * @see https://gitea.com/api/swagger#/issue/issueGetIssue */ async getIssue({ accessToken, issueId, issueTitle, }: { accessToken: VssueAPI.AccessToken; issueId?: string | number; issueTitle?: string; }): Promise<VssueAPI.Issue | null> { const options: AxiosRequestConfig = {}; if (accessToken) { options.headers = { Authorization: `bearer ${accessToken}`, }; } if (issueId) { try { options.params = { // to avoid caching timestamp: Date.now(), }; const { data } = await this.$http.get<ResponseIssue>( `repos/${this.owner}/${this.repo}/issues/${issueId}`, options ); return normalizeIssue(data, this.baseURL, this.owner, this.repo); } catch (e) { if (e.response && e.response.status === 404) { return null; } else { throw e; } } } else { /** * Gitea only supports using label ids to get issues */ const allLabels = await this.getLabels({ accessToken }); const labels = this.labels .filter(label => allLabels.find(item => item.name === label)) .map(label => allLabels.find(item => item.name === label)!.id); options.params = { labels, q: issueTitle, // to avoid caching timestamp: Date.now(), }; const { data } = await this.$http.get<ResponseIssue[]>( `repos/${this.owner}/${this.repo}/issues`, options ); const issue = data .map(item => normalizeIssue(item, this.baseURL, this.owner, this.repo)) .find(item => item.title === issueTitle); return issue || null; } } /** * Create a new issue * * @see https://gitea.com/api/swagger#/issue/issueCreateIssue */ async postIssue({ accessToken, title, content, }: { accessToken: VssueAPI.AccessToken; title: string; content: string; }): Promise<VssueAPI.Issue> { /** * Gitea only supports using label ids to create issue */ const labels = await Promise.all( this.labels.map(label => this.postLabel({ accessToken, label, }) ) ); const { data } = await this.$http.post<ResponseIssue>( `repos/${this.owner}/${this.repo}/issues`, { title, body: content, labels, }, { headers: { Authorization: `bearer ${accessToken}` }, } ); return normalizeIssue(data, this.baseURL, this.owner, this.repo); } /** * Get comments of this page according to the issue id * * @see https://gitea.com/api/swagger#/issue/issueGetComments */ async getComments({ accessToken, issueId, // eslint-disable-next-line @typescript-eslint/no-unused-vars query: { page = 1, perPage = 10, sort = 'desc' } = {}, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; query?: Partial<VssueAPI.Query>; }): Promise<VssueAPI.Comments> { const options: AxiosRequestConfig = { params: { // to avoid caching timestamp: Date.now(), }, }; if (accessToken) { options.headers = { Authorization: `bearer ${accessToken}`, }; } const response = await this.$http.get<ResponseComment[]>( `repos/${this.owner}/${this.repo}/issues/${issueId}/comments`, options ); const commentsRaw = response.data; // gitea api v1 should get html content and reactions by other api const getCommentsMeta: Array<Promise<void>> = []; for (const comment of commentsRaw) { getCommentsMeta.push( (async (): Promise<void> => { comment.body_html = await this.getMarkdownContent({ accessToken: accessToken, contentRaw: comment.body, }); })() ); getCommentsMeta.push( (async (): Promise<void> => { comment.reactions = await this.getCommentReactions({ accessToken: accessToken, issueId: issueId, commentId: comment.id, }); })() ); } await Promise.all(getCommentsMeta); return { count: commentsRaw.length, // gitea api v1 does not support pagination for now // so the `page` and `perPage` are fake data page: 1, perPage: 50, data: commentsRaw.map(item => normalizeComment(item, this.baseURL)), }; } /** * Create a new comment * * @see https://gitea.com/api/swagger#/issue/issueCreateComment */ async postComment({ accessToken, issueId, content, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; content: string; }): Promise<VssueAPI.Comment> { const { data } = await this.$http.post<ResponseComment>( `repos/${this.owner}/${this.repo}/issues/${issueId}/comments`, { body: content, }, { headers: { Authorization: `bearer ${accessToken}` }, } ); return normalizeComment(data, this.baseURL); } /** * Edit a comment * * @see https://gitea.com/api/swagger#/issue/issueEditCommentDeprecated */ async putComment({ accessToken, issueId, commentId, content, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; commentId: string | number; content: string; }): Promise<VssueAPI.Comment> { const { data } = await this.$http.patch<ResponseComment>( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}`, { body: content, }, { headers: { Authorization: `bearer ${accessToken}` }, } ); const [contentHTML, reactions] = await Promise.all([ this.getMarkdownContent({ accessToken: accessToken, contentRaw: data.body, }), this.getCommentReactions({ accessToken: accessToken, issueId: issueId, commentId: data.id, }), ]); data.body_html = contentHTML; data.reactions = reactions; return normalizeComment(data, this.baseURL); } /** * Delete a comment * * @see https://gitea.com/api/swagger#/issue/issueDeleteCommentDeprecated */ async deleteComment({ accessToken, commentId, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; commentId: string | number; }): Promise<boolean> { const { status } = await this.$http.delete( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}`, { headers: { Authorization: `bearer ${accessToken}` }, } ); return status === 204; } /** * Get reactions of a comment * * @see https://gitea.com/api/swagger#/issue/issueGetCommentReactions */ async getCommentReactions({ accessToken, commentId, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; commentId: string | number; }): Promise<VssueAPI.Reactions> { const options: AxiosRequestConfig = { params: { // to avoid caching timestamp: Date.now(), }, }; if (accessToken) { options.headers = { Authorization: `bearer ${accessToken}`, }; } const { data } = await this.$http.get<ResponseReaction[]>( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}/reactions`, options ); // data is possibly be `null` return normalizeReactions(data || []); } /** * Create a new reaction of a comment * * @see https://gitea.com/api/swagger#/issue/issuePostCommentReaction */ async postCommentReaction({ commentId, reaction, accessToken, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; commentId: string | number; reaction: keyof VssueAPI.Reactions; }): Promise<boolean> { const response = await this.$http.post( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}/reactions`, { content: mapReactionName(reaction), }, { headers: { Authorization: `bearer ${accessToken}` }, } ); // 200 OK if the reaction is already token if (response.status === 200) { return this.deleteCommentReaction({ accessToken, commentId, reaction, }); } // 201 CREATED return response.status === 201; } /** * Create a new reaction of a comment * * @see https://gitea.com/api/swagger#/issue/issueDeleteCommentReaction */ async deleteCommentReaction({ commentId, reaction, accessToken, }: { accessToken: VssueAPI.AccessToken; commentId: string | number; reaction: keyof VssueAPI.Reactions; }): Promise<boolean> { const response = await this.$http.request({ url: `repos/${this.owner}/${this.repo}/issues/comments/${commentId}/reactions`, method: 'delete', data: { content: mapReactionName(reaction) }, headers: { Authorization: `bearer ${accessToken}` }, }); return response.status === 200; } /** * Get labels * * @see https://gitea.com/api/swagger#/issue/issueListLabels */ async getLabels({ accessToken, }: { accessToken: VssueAPI.AccessToken; }): Promise<ResponseLabel[]> { const options: AxiosRequestConfig = { params: { // to avoid caching timestamp: Date.now(), }, }; if (accessToken) { options.headers = { Authorization: `bearer ${accessToken}`, }; } const { data } = await this.$http.get<ResponseLabel[]>( `repos/${this.owner}/${this.repo}/labels`, options ); return data || []; } /** * Create label * * @see https://gitea.com/api/swagger#/issue/issueCreateLabel */ async postLabel({ accessToken, label, color = '#3eaf7c', description, }: { accessToken: VssueAPI.AccessToken; label: string; color?: string; description?: string; }): Promise<number> { const { data } = await this.$http.post<ResponseLabel>( `repos/${this.owner}/${this.repo}/labels`, { name: label, color, description, }, { headers: { Authorization: `bearer ${accessToken}` }, } ); return data.id; } /** * Get the parse HTML of markdown content * * @see https://gitea.com/api/swagger#/miscellaneous/renderMarkdown */ async getMarkdownContent({ accessToken, contentRaw, }: { accessToken?: VssueAPI.AccessToken; contentRaw: string; }): Promise<string> { const options: AxiosRequestConfig = {}; if (accessToken) { options.headers = { Authorization: `bearer ${accessToken}`, }; } const { data } = await this.$http.post<ResponseMarkdown>( `markdown`, { Context: `${this.owner}/${this.repo}`, Mode: 'gfm', Text: contentRaw, Wiki: false, }, options ); return data; } }
the_stack
import * as lsp from 'vscode-languageserver'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { isInteresting, parallel, StopWatch } from '../common'; import { DocumentStore } from '../documentStore'; import { Trees } from '../trees'; import { Trie } from '../util/trie'; import { getDocumentSymbols } from './documentSymbols'; import { getDocumentUsages, IUsage } from './references'; class Queue { private readonly _queue = new Set<string>(); enqueue(uri: string): void { if (isInteresting(uri) && !this._queue.has(uri)) { this._queue.add(uri); } } dequeue(uri: string): void { this._queue.delete(uri); } consume(n?: number): string[] { if (n === undefined) { const result = Array.from(this._queue.values()); this._queue.clear(); return result; } const result: string[] = []; const iter = this._queue.values(); for (; n > 0; n--) { const r = iter.next(); if (r.done) { break; } const uri = r.value; result.push(uri); this._queue.delete(uri); } return result; } } export class DBPersistedIndex implements IPersistedIndex { private readonly _version = 1; private readonly _store = 'fileSymbols'; private _db?: IDBDatabase; constructor(private readonly _name: string) { } async open() { if (this._db) { return; } await new Promise((resolve, reject) => { const request = indexedDB.open(this._name, this._version); request.onerror = () => reject(request.error); request.onsuccess = () => { const db = request.result; if (!db.objectStoreNames.contains(this._store)) { console.error(`Error while opening IndexedDB. Could not find '${this._store}' object store`); return resolve(this._delete(db).then(() => this.open())); } else { resolve(undefined); this._db = db; } }; request.onupgradeneeded = () => { const db = request.result; if (db.objectStoreNames.contains(this._store)) { db.deleteObjectStore(this._store); } db.createObjectStore(this._store); }; }); } async close(): Promise<void> { if (this._db) { await this._bulkInsert(); this._db.close(); } } private _delete(db: IDBDatabase): Promise<void> { return new Promise((resolve, reject) => { // Close any opened connections db.close(); // Delete the db const deleteRequest = indexedDB.deleteDatabase(this._name); deleteRequest.onerror = () => reject(deleteRequest.error); deleteRequest.onsuccess = () => resolve(); }); } private _insertQueue = new Map<string, Array<string | number>>(); private _insertHandle: number | undefined; insert(uri: string, info: Map<string, SymbolInfo>) { const flatInfo: Array<string | number> = []; for (let [word, i] of info) { flatInfo.push(word); flatInfo.push(i.definitions.size); flatInfo.push(...i.definitions); flatInfo.push(...i.usages); } this._insertQueue.set(uri, flatInfo); clearTimeout(this._insertHandle); this._insertHandle = setTimeout(() => { this._bulkInsert().catch(err => { console.error(err); }); }, 50); } private async _bulkInsert(): Promise<void> { if (this._insertQueue.size === 0) { return; } return new Promise((resolve, reject) => { if (!this._db) { return reject(new Error('invalid state')); } const t = this._db.transaction(this._store, 'readwrite'); const toInsert = new Map(this._insertQueue); this._insertQueue.clear(); for (let [uri, data] of toInsert) { t.objectStore(this._store).put(data, uri); } t.oncomplete = () => resolve(undefined); t.onerror = (err) => reject(err); }); } getAll(): Promise<Map<string, Map<string, SymbolInfo>>> { return new Promise((resolve, reject) => { if (!this._db) { return reject(new Error('invalid state')); } const entries = new Map<string, Map<string, SymbolInfo>>(); const t = this._db.transaction(this._store, 'readonly'); const store = t.objectStore(this._store); const cursor = store.openCursor(); cursor.onsuccess = () => { if (!cursor.result) { resolve(entries); return; } const info = new Map<string, SymbolInfo>(); const flatInfo = (<Array<string | number>>cursor.result.value); for (let i = 0; i < flatInfo.length;) { let word = (<string>flatInfo[i]); let defLen = (<number>flatInfo[++i]); let kindStart = ++i; for (; i < flatInfo.length && typeof flatInfo[i] === 'number'; i++) { ; } info.set(word, { definitions: new Set(<lsp.SymbolKind[]>flatInfo.slice(kindStart, kindStart + defLen)), usages: new Set(<lsp.SymbolKind[]>flatInfo.slice(kindStart + defLen, i)) }); } entries.set(String(cursor.result.key), info); cursor.result.continue(); }; cursor.onerror = () => reject(cursor.error); t.onerror = () => reject(t.error); }); } delete(uris: Set<string>): Promise<void> { return new Promise((resolve, reject) => { if (!this._db) { return reject(new Error('invalid state')); } const t = this._db.transaction(this._store, 'readwrite'); const store = t.objectStore(this._store); for (const uri of uris) { const request = store.delete(uri); request.onerror = e => console.error(e); } t.oncomplete = () => resolve(undefined); t.onerror = (err) => reject(err); }); } } export class FilePersistedIndex implements IPersistedIndex { private readonly _data = new Map<string, Array<string | number>>(); constructor(private readonly _connection: lsp.Connection) { } insert(uri: string, info: Map<string, SymbolInfo>): void { const flatInfo: Array<string | number> = []; for (let [word, i] of info) { flatInfo.push(word); flatInfo.push(i.definitions.size); flatInfo.push(...i.definitions); flatInfo.push(...i.usages); } this._data.set(uri, flatInfo); this._saveSoon(); } async delete(uris: Set<string>): Promise<void> { for (const uri of uris) { this._data.delete(uri); } this._saveSoon(); } private _saveTimer: number | undefined; private _saveSoon() { clearTimeout(this._saveTimer); this._saveTimer = setTimeout(() => { const raw = JSON.stringify(Array.from(this._data.entries())); const bytes = new TextEncoder().encode(raw); this._connection.sendRequest('persisted/write', bytes).catch(err => console.error(err)); }, 50); } async getAll(): Promise<Map<string, Map<string, SymbolInfo>>> { this._data.clear(); const result = new Map<string, Map<string, SymbolInfo>>(); try { const bytes = await this._connection.sendRequest<Uint8Array>('persisted/read'); const raw = new TextDecoder().decode(bytes); const data = <[string, Array<string | number>][]>JSON.parse(raw); for (let [uri, flatInfo] of data) { this._data.set(uri, flatInfo); const info = new Map<string, SymbolInfo>(); result.set(uri, info); for (let i = 0; i < flatInfo.length;) { let word = (<string>flatInfo[i]); let defLen = (<number>flatInfo[++i]); let kindStart = ++i; for (; i < flatInfo.length && typeof flatInfo[i] === 'number'; i++) { ; } info.set(word, { definitions: new Set(<lsp.SymbolKind[]>flatInfo.slice(kindStart, kindStart + defLen)), usages: new Set(<lsp.SymbolKind[]>flatInfo.slice(kindStart + defLen, i)) }); } } } catch (err) { console.error(err); } return result; } } export interface IPersistedIndex { insert(uri: string, info: Map<string, SymbolInfo>): void; getAll(): Promise<Map<string, Map<string, SymbolInfo>>>; delete(uris: Set<string>): Promise<void>; } interface SymbolInfo { definitions: Set<lsp.SymbolKind> usages: Set<lsp.SymbolKind> } class Index { private readonly _index = Trie.create<Map<lsp.DocumentUri, SymbolInfo>>(); private readonly _cleanup = new Map<lsp.DocumentUri, Function>(); get(text: string) { return this._index.get(text); } query(query: string): IterableIterator<[string, Map<lsp.DocumentUri, SymbolInfo>]> { return this._index.query(Array.from(query)); } [Symbol.iterator](): IterableIterator<[string, Map<lsp.DocumentUri, SymbolInfo>]> { return this._index[Symbol.iterator](); } update(uri: lsp.DocumentUri, value: Map<string, SymbolInfo>) { // (1) remove old symbol information this._cleanup.get(uri)?.(); // (2) insert new symbol information for (const [name, kinds] of value) { const all = this._index.get(name); if (all) { all.set(uri, kinds); } else { this._index.set(name, new Map([[uri, kinds]])); } } // (3) register clean-up by uri this._cleanup.set(uri, () => { for (const name of value.keys()) { const all = this._index.get(name); if (all) { if (all.delete(uri) && all.size === 0) { this._index.delete(name); } } } }); } delete(uri: lsp.DocumentUri): boolean { const cleanupFn = this._cleanup.get(uri); if (cleanupFn) { cleanupFn(); this._cleanup.delete(uri); return true; } return false; } } export class SymbolIndex { readonly index = new Index(); private readonly _syncQueue = new Queue(); private readonly _asyncQueue = new Queue(); constructor( private readonly _trees: Trees, private readonly _documents: DocumentStore, private readonly _persistedIndex: IPersistedIndex ) { } addFile(uri: string): void { this._syncQueue.enqueue(uri); this._asyncQueue.dequeue(uri); } removeFile(uri: string): void { this._syncQueue.dequeue(uri); this._asyncQueue.dequeue(uri); this.index.delete(uri); } private _currentUpdate: Promise<void> | undefined; async update(): Promise<void> { await this._currentUpdate; this._currentUpdate = this._doUpdate(this._syncQueue.consume()); return this._currentUpdate; } private async _doUpdate(uris: string[], silent?: boolean): Promise<void> { if (uris.length !== 0) { // schedule a new task to update the cache for changed uris const sw = new StopWatch(); const tasks = uris.map(this._createIndexTask, this); const stats = await parallel(tasks, 50, new lsp.CancellationTokenSource().token); let totalRetrieve = 0; let totalIndex = 0; for (let stat of stats) { totalRetrieve += stat.durationRetrieve; totalIndex += stat.durationIndex; } if (!silent) { console.log(`[index] added ${uris.length} files ${sw.elapsed()}ms\n\tretrieval: ${Math.round(totalRetrieve)}ms\n\tindexing: ${Math.round(totalIndex)}ms`); } } } private _createIndexTask(uri: string): () => Promise<{ durationRetrieve: number, durationIndex: number }> { return async () => { // fetch document const _t1Retrieve = performance.now(); const document = await this._documents.retrieve(uri); const durationRetrieve = performance.now() - _t1Retrieve; // remove current data this.index.delete(uri); // update index const _t1Index = performance.now(); try { this._doIndex(document); } catch (e) { console.log(`FAILED to index ${uri}`, e); } const durationIndex = performance.now() - _t1Index; return { durationRetrieve, durationIndex }; }; } private _doIndex(document: TextDocument, symbols?: lsp.DocumentSymbol[], usages?: IUsage[]): void { const symbolInfo = new Map<string, SymbolInfo>(); // definitions if (!symbols) { symbols = getDocumentSymbols(document, this._trees, true); } for (const symbol of symbols) { const all = symbolInfo.get(symbol.name); if (all) { all.definitions.add(symbol.kind); } else { symbolInfo.set(symbol.name, { definitions: new Set([symbol.kind]), usages: new Set() }); } } // usages if (!usages) { usages = getDocumentUsages(document, this._trees); } for (const usage of usages) { const all = symbolInfo.get(usage.name); if (all) { all.usages.add(usage.kind); } else { symbolInfo.set(usage.name, { definitions: new Set(), usages: new Set([usage.kind]) }); } } // update in-memory index and persisted index this.index.update(document.uri, symbolInfo); this._persistedIndex.insert(document.uri, symbolInfo); } async initFiles(_uris: string[]) { const uris = new Set(_uris); const sw = new StopWatch(); console.log(`[index] building index for ${uris.size} files.`); const persisted = await this._persistedIndex.getAll(); const obsolete = new Set<string>(); for (const [uri, data] of persisted) { if (!uris.delete(uri)) { // this file isn't requested anymore, remove later obsolete.add(uri); } else { // restore definitions and usages and schedule async // update for this file this.index.update(uri, data); this._asyncQueue.enqueue(uri); } } console.log(`[index] added FROM CACHE ${persisted.size} files ${sw.elapsed()}ms\n\t${uris.size} files still need to be fetched\n\t${obsolete.size} files are obsolete in cache`); // sync update all files that were not cached uris.forEach(this.addFile, this); await this.update(); // remove from persisted cache files that aren't interesting anymore await this._persistedIndex.delete(obsolete); // async update all files that were taken from cache const asyncUpdate = async () => { const uris = this._asyncQueue.consume(70); if (uris.length === 0) { console.log('[index] ASYNC update is done'); return; } const t1 = performance.now(); await this._doUpdate(uris, true); setTimeout(() => asyncUpdate(), (performance.now() - t1) * 4); }; asyncUpdate(); } // --- async getDefinitions(ident: string, source: TextDocument) { await this.update(); const result: lsp.SymbolInformation[] = []; let sameLanguageOffset = 0; const all = this.index.get(ident) ?? []; const work: Promise<any>[] = []; for (const [uri, value] of all) { if (value.definitions.size === 0) { // only usages continue; } work.push(this._documents.retrieve(uri).then(document => { const isSameLanguage = source.languageId === document.languageId; const symbols = getDocumentSymbols(document, this._trees, true); for (const item of symbols) { if (item.name === ident) { const info = lsp.SymbolInformation.create(item.name, item.kind, item.selectionRange, uri); if (isSameLanguage) { result.unshift(info); sameLanguageOffset++; } else { result.push(info); } } } // update index setTimeout(() => { this._asyncQueue.dequeue(document.uri); this._doIndex(document, symbols); }); }).catch(err => { console.log(err); })); } await Promise.allSettled(work); // only return results that are of the same language unless there are only // results from other languages return result.slice(0, sameLanguageOffset || undefined); } async getUsages(ident: string, source: TextDocument) { await this.update(); const result: lsp.Location[] = []; const all = this.index.get(ident) ?? []; const work: Promise<any>[] = []; let sameLanguageOffset = 0; for (const [uri, value] of all) { if (value.usages.size === 0) { // only definitions continue; } work.push(this._documents.retrieve(uri).then(document => { const isSameLanguage = source.languageId === document.languageId; const usages = getDocumentUsages(document, this._trees); for (const item of usages) { if (item.name === ident) { const location = lsp.Location.create(uri, item.range); if (isSameLanguage) { result.unshift(location); sameLanguageOffset++; } else { result.push(location); } } } // update index setTimeout(() => { this._asyncQueue.dequeue(document.uri); this._doIndex(document, undefined, usages); }); }).catch(err => { console.log(err); })); } await Promise.allSettled(work); // only return results that are of the same language unless there are only // results from other languages return result.slice(0, sameLanguageOffset || undefined); } }
the_stack
import EventDispatcher from "./../../starling/events/EventDispatcher"; import Vector from "openfl/Vector"; import ArrayUtil from "./../../starling/utils/ArrayUtil"; import URLRequest from "openfl/net/URLRequest"; import ArgumentError from "openfl/errors/ArgumentError"; import Starling from "./../../starling/core/Starling"; import Error from "openfl/errors/Error"; import TextureAtlas from "./../../starling/textures/TextureAtlas"; import TextField from "./../../starling/text/TextField"; import BitmapFont from "./../../starling/text/BitmapFont"; import Sound from "openfl/media/Sound"; import Bitmap from "openfl/display/Bitmap"; import Texture from "./../../starling/textures/Texture"; import ByteArray from "openfl/utils/ByteArray"; import AtfData from "./../../starling/textures/AtfData"; import LoaderContext from "openfl/system/LoaderContext"; import Loader from "openfl/display/Loader"; import URLLoader from "openfl/net/URLLoader"; import TextureOptions from "./../../starling/textures/TextureOptions"; import SoundTransform from "openfl/media/SoundTransform"; import SoundChannel from "openfl/media/SoundChannel"; import Context3DTextureFormat from "openfl/display3D/Context3DTextureFormat"; declare namespace starling.utils { /** Dispatched when all textures have been restored after a context loss. */ // @:meta(Event(name="texturesRestored", type="starling.events.Event")) /** Dispatched when an URLLoader fails with an IO_ERROR while processing the queue. * The 'data' property of the Event contains the URL-String that could not be loaded. */ // @:meta(Event(name="ioError", type="starling.events.Event")) /** Dispatched when an URLLoader fails with a SECURITY_ERROR while processing the queue. * The 'data' property of the Event contains the URL-String that could not be loaded. */ // @:meta(Event(name="securityError", type="starling.events.Event")) /** Dispatched when an XML or JSON file couldn't be parsed. * The 'data' property of the Event contains the name of the asset that could not be parsed. */ // @:meta(Event(name="parseError", type="starling.events.Event")) /** The AssetManager handles loading and accessing a variety of asset types. You can * add assets directly (via the 'add...' methods) or asynchronously via a queue. This allows * you to deal with assets in a unified way, no matter if they are loaded from a file, * directory, URL, or from an embedded object. * * <p>The class can deal with the following media types: * <ul> * <li>Textures, either from Bitmaps or ATF data</li> * <li>Texture atlases</li> * <li>Bitmap Fonts</li> * <li>Sounds</li> * <li>XML data</li> * <li>JSON data</li> * <li>ByteArrays</li> * </ul> * </p> * * <p>For more information on how to add assets from different sources, read the documentation * of the "enqueue()" method.</p> * * <strong>Context Loss</strong> * * <p>When the stage3D context is lost (and you have enabled 'Starling.handleLostContext'), * the AssetManager will automatically restore all loaded textures. To save memory, it will * get them from their original sources. Since this is done asynchronously, your images might * not reappear all at once, but during a timeframe of several seconds. If you want, you can * pause your game during that time; the AssetManager dispatches an "Event.TEXTURES_RESTORED" * event when all textures have been restored.</p> * * <strong>Error handling</strong> * * <p>Loading of some assets may fail while the queue is being processed. In that case, the * AssetManager will dispatch events of type "IO_ERROR", "SECURITY_ERROR" or "PARSE_ERROR". * You can listen to those events and handle the errors manually (e.g., you could enqueue * them once again and retry, or provide placeholder textures). Queue processing will * continue even when those events are dispatched.</p> * * <strong>Using variable texture formats</strong> * * <p>When you enqueue a texture, its properties for "format", "scale", "mipMapping", and * "repeat" will reflect the settings of the AssetManager at the time they were enqueued. * This means that you can enqueue a bunch of textures, then change the settings and enqueue * some more. Like this:</p> * * <listing> * appDir:File = File.applicationDirectory; * assets:AssetManager = new AssetManager(); * * assets.textureFormat = Context3DTextureFormat.BGRA; * assets.enqueue(appDir.resolvePath("textures/32bit")); * * assets.textureFormat = Context3DTextureFormat.BGRA_PACKED; * assets.enqueue(appDir.resolvePath("textures/16bit")); * * assets.loadQueue(...);</listing> */ export class AssetManager extends EventDispatcher { /** Create a new AssetManager. The 'scaleFactor' and 'useMipmaps' parameters define * how enqueued bitmaps will be converted to textures. */ public constructor(scaleFactor?:number, useMipmaps?:boolean); /** Disposes all contained textures, XMLs and ByteArrays. * * <p>Beware that all references to the assets will remain intact, even though the assets * are no longer valid. Call 'purge' if you want to remove all resources and reuse * the AssetManager later.</p> */ public dispose():void; // retrieving /** Returns a texture with a certain name. The method first looks through the directly * added textures; if no texture with that name is found, it scans through all * texture atlases. */ public getTexture(name:string):Texture; /** Returns all textures that start with a certain string, sorted alphabetically * (especially useful for "MovieClip"). */ public getTextures(prefix?:string, out?:Vector<Texture>):Vector<Texture>; /** Returns all texture names that start with a certain string, sorted alphabetically. */ public getTextureNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns a texture atlas with a certain name, or null if it's not found. */ public getTextureAtlas(name:string):TextureAtlas; /** Returns all texture atlas names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getTextureAtlasNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns a sound with a certain name, or null if it's not found. */ public getSound(name:string):Sound; /** Returns all sound names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getSoundNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Generates a new SoundChannel object to play back the sound. This method returns a * SoundChannel object, which you can access to stop the sound and to control volume. */ public playSound(name:string, startTime?:number, loops?:number, transform?:SoundTransform):SoundChannel; /** Returns an XML with a certain name, or null if it's not found. */ public getXml(name:string):any /*Xml*/; /** Returns all XML names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getXmlNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns an object with a certain name, or null if it's not found. Enqueued JSON * data is parsed and can be accessed with this method. */ public getObject(name:string):any; /** Returns all object names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getObjectNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns a byte array with a certain name, or null if it's not found. */ public getByteArray(name:string):ByteArray; /** Returns all byte array names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getByteArrayNames(prefix?:string, out?:Vector<string>):Vector<string>; /** Returns a bitmaps font with a certain name, or null if it's not found. */ public getBitmapFont(name:string):BitmapFont; /** Returns all bitmap fonts names that start with a certain string, sorted alphabetically. * If you pass an <code>out</code>-vector, the names will be added to that vector. */ public getBitmapFontNames(prefix?:string, out?:Vector<string>):Vector<string>; // direct adding /** Register a texture under a certain name. It will be available right away. * If the name was already taken, the existing texture will be disposed and replaced * by the new one. */ public addTexture(name:string, texture:Texture):void; /** Register a texture atlas under a certain name. It will be available right away. * If the name was already taken, the existing atlas will be disposed and replaced * by the new one. */ public addTextureAtlas(name:string, atlas:TextureAtlas):void; /** Register a sound under a certain name. It will be available right away. * If the name was already taken, the existing sound will be replaced by the new one. */ public addSound(name:string, sound:Sound):void; /** Register an XML object under a certain name. It will be available right away. * If the name was already taken, the existing XML will be disposed and replaced * by the new one. */ public addXml(name:string, xml:any):void; /** Register an arbitrary object under a certain name. It will be available right away. * If the name was already taken, the existing object will be replaced by the new one. */ public addObject(name:string, object:any):void; /** Register a byte array under a certain name. It will be available right away. * If the name was already taken, the existing byte array will be cleared and replaced * by the new one. */ public addByteArray(name:string, byteArray:ByteArray):void; /** Register a bitmap font under a certain name. It will be available right away. * If the name was already taken, the existing font will be disposed and replaced * by the new one. * * <p>Note that the font is <strong>not</strong> registered at the TextField class. * This only happens when a bitmap font is loaded via the asset queue.</p> */ public addBitmapFont(name:string, font:BitmapFont):void; // removing /** Removes a certain texture, optionally disposing it. */ public removeTexture(name:string, dispose?:boolean):void; /** Removes a certain texture atlas, optionally disposing it. */ public removeTextureAtlas(name:string, dispose?:boolean):void; /** Removes a certain sound. */ public removeSound(name:string):void; /** Removes a certain Xml object, optionally disposing it. */ public removeXml(name:string, dispose?:boolean):void; /** Removes a certain object. */ public removeObject(name:string):void; /** Removes a certain byte array, optionally disposing its memory right away. */ public removeByteArray(name:string, dispose?:boolean):void; /** Removes a certain bitmap font, optionally disposing it. */ public removeBitmapFont(name:string, dispose?:boolean):void; /** Empties the queue and aborts any pending load operations. */ public purgeQueue():void; /** Removes assets of all types (disposing them along the way), empties the queue and * aborts any pending load operations. */ public purge():void; // queued adding /** Enqueues one or more raw assets; they will only be available after successfully * executing the "loadQueue" method. This method accepts a variety of different objects: * * <ul> * <li>Strings or URLRequests containing an URL to a local or remote resource. Supported * types: <code>png, jpg, gif, atf, mp3, xml, fnt, json, binary</code>.</li> * <li>Instances of the File class (AIR only) pointing to a directory or a file. * Directories will be scanned recursively for all supported types.</li> * <li>Classes that contain <code>static</code> embedded assets.</li> * <li>If the file extension is not recognized, the data is analyzed to see if * contains XML or JSON data. If it's neither, it is stored as ByteArray.</li> * </ul> * * <p>Suitable object names are extracted automatically: A file named "image.png" will be * accessible under the name "image". When enqueuing embedded assets via a class, * the variable name of the embedded object will be used as its name. An exception * are texture atlases: they will have the same name as the actual texture they are * referencing.</p> * * <p>XMLs that contain texture atlases or bitmap fonts are processed directly: fonts are * registered at the TextField class, atlas textures can be acquired with the * "getTexture()" method. All other XMLs are available via "getXml()".</p> * * <p>If you pass in JSON data, it will be parsed into an object and will be available via * "getObject()".</p> */ public enqueue(rawAssets:Array<any>):void; /** Enqueues a single asset with a custom name that can be used to access it later. * If the asset is a texture, you can also add custom texture options. * * @param asset The asset that will be enqueued; accepts the same objects as the * 'enqueue' method. * @param name The name under which the asset will be found later. If you pass null or * omit the parameter, it's attempted to generate a name automatically. * @param options Custom options that will be used if 'asset' points to texture data. * @return the name with which the asset was registered. */ public enqueueWithName(asset:any, name?:string, options?:TextureOptions):string; /** Loads all enqueued assets asynchronously. The 'onProgress' will be called * with a 'ratio' between '0.0' and '1.0', with '1.0' meaning that it's complete. * * <p>When you call this method, the manager will save a reference to "Starling.current"; * all textures that are loaded will be accessible only from within this instance. Thus, * if you are working with more than one Starling instance, be sure to call * "makeCurrent()" on the appropriate instance before processing the queue.</p> * * @param onProgress <code>function(ratio:Number):void;</code> */ public loadQueue(onProgress:(number)=>void):void; // properties /** The queue contains one 'Object' for each enqueued asset. Each object has 'asset' * and 'name' properties, pointing to the raw asset and its name, respectively. */ protected readonly queue:Array<any>; protected get_queue():Array<any>; /** Returns the number of raw assets that have been enqueued, but not yet loaded. */ public readonly numQueuedAssets:number; protected get_numQueuedAssets():number; /** When activated, the class will trace information about added/enqueued assets. * @default true */ public verbose:boolean; protected get_verbose():boolean; protected set_verbose(value:boolean):boolean; /** Indicates if a queue is currently being loaded. */ public readonly isLoading:boolean; protected get_isLoading():boolean; /** For bitmap textures, this flag indicates if mip maps should be generated when they * are loaded; for ATF textures, it indicates if mip maps are valid and should be * used. @default false */ public useMipMaps:boolean; protected get_useMipMaps():boolean; protected set_useMipMaps(value:boolean):boolean; /** Textures that are created from Bitmaps or ATF files will have the scale factor * assigned here. @default 1 */ public scaleFactor:number; protected get_scaleFactor():number; protected set_scaleFactor(value:number):number; /** Textures that are created from Bitmaps will be uploaded to the GPU with the * <code>Context3DTextureFormat</code> assigned to this property. @default "bgra" */ public textureFormat:Context3DTextureFormat; protected get_textureFormat():Context3DTextureFormat; protected set_textureFormat(value:Context3DTextureFormat):Context3DTextureFormat; /** Indicates if the underlying Stage3D textures should be created as the power-of-two based * <code>Texture</code> class instead of the more memory efficient <code>RectangleTexture</code>. * @default false */ public forcePotTextures:boolean; protected get_forcePotTextures():boolean; protected set_forcePotTextures(value:boolean):boolean; /** Specifies whether a check should be made for the existence of a URL policy file before * loading an object from a remote server. More information about this topic can be found * in the 'flash.system.LoaderContext' documentation. @default false */ public checkPolicyFile:boolean; protected get_checkPolicyFile():boolean; protected set_checkPolicyFile(value:boolean):boolean; /** Indicates if atlas XML data should be stored for access via the 'getXml' method. * If true, you can access an XML under the same name as the atlas. * If false, XMLs will be disposed when the atlas was created. @default false. */ public keepAtlasXmls:boolean; protected get_keepAtlasXmls():boolean; protected set_keepAtlasXmls(value:boolean):boolean; /** Indicates if bitmap font XML data should be stored for access via the 'getXml' method. * If true, you can access an XML under the same name as the bitmap font. * If false, XMLs will be disposed when the font was created. @default false. */ public keepFontXmls:boolean; protected get_keepFontXmls():boolean; protected set_keepFontXmls(value:boolean):boolean; /** The maximum number of parallel connections that are spawned when loading the queue. * More connections can reduce loading times, but require more memory. @default 3. */ public numConnections:number; protected get_numConnections():number; protected set_numConnections(value:number):number; /** Indicates if bitmap fonts should be registered with their "face" attribute from the * font XML file. Per default, they are registered with the name of the texture file. * @default false */ public registerBitmapFontsWithFontFace:boolean; public get_registerBitmapFontsWithFontFace():boolean; public set_registerBitmapFontsWithFontFace(value:boolean):boolean; } } export default starling.utils.AssetManager;
the_stack
declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zza { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zza>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zza interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzaa<K, V> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzs<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaa<any,any>>; public get(param0: any): any; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzab<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzo<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzab<any>>; public size(): number; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzac extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzo<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzac>; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzad<K, V> extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzu<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzad<any,any>>; public contains(param0: any): boolean; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzae extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzo<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzae>; public size(): number; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzaf<K> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzu<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaf<any>>; public contains(param0: any): boolean; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzag { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzag>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzah<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzu<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzah<any>>; public contains(param0: any): boolean; public size(): number; public hashCode(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzai<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzai<any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzaj<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzu<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaj<any>>; public contains(param0: any): boolean; public size(): number; public hashCode(): number; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzak<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzal<any>*/ implements java.util.ListIterator<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzak<any>>; public constructor(); public set(param0: any): void; public add(param0: any): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzal<E> extends java.util.Iterator<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzal<any>>; public constructor(); public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzam { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzam>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzan<N> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzan<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzan<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzao extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzat { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzao>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzap { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzap>; public hashCode(): number; public toString(): string; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzaq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzar extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzat { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzar>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzas { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzas>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzat extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzam { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzat>; public hashCode(): number; public toString(): string; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzau extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzau>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzav extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzai<java.io.File> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzav>; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzaw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzax { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzax>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzay extends java.util.concurrent.Executor { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzay>; public execute(param0: java.lang.Runnable): void; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzay>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzaz { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzb>; public constructor(); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public dispatchMessage(param0: globalAndroid.os.Message): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzba { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzba>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbb<V> extends java.util.concurrent.Future<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbb<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbb<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzbc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbd>; } export module zzbd { export class zza extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbd.zza>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbe extends java.lang.ref.WeakReference<java.lang.Throwable> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbe>; public hashCode(): number; public equals(param0: any): boolean; public constructor(param0: java.lang.Throwable, param1: java.lang.ref.ReferenceQueue<java.lang.Throwable>); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbf { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbf>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbg extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh>; } export module zzbh { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zza,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zza>; public isInitialized(): boolean; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zza,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zza.zza>; public isInitialized(): boolean; } } export class zzaa extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zzc>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa>; public isInitialized(): boolean; } export module zzaa { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zzb>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zzb>*/; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zzc>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zzc>; public isInitialized(): boolean; } } export class zzab extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzab,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzab.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzab>; public isInitialized(): boolean; } export module zzab { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzab,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzab.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzab.zza>; public isInitialized(): boolean; } } export class zzac extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzac,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzac.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzac>; public isInitialized(): boolean; } export module zzac { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzac,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzac.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzac.zza>; public isInitialized(): boolean; } } export class zzad extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzad,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzad.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzad>; public isInitialized(): boolean; } export module zzad { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzad,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzad.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzad.zza>; public isInitialized(): boolean; } } export class zzae extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae>; public isInitialized(): boolean; } export module zzae { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzb>; public isInitialized(): boolean; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzb.zza>; public isInitialized(): boolean; } } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzc>; public isInitialized(): boolean; } export module zzc { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzc.zza>; public isInitialized(): boolean; } } export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzd,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzd>; public isInitialized(): boolean; } export module zzd { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzd,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzae.zzd.zza>; public isInitialized(): boolean; } } } export class zzaf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaf,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaf>; public isInitialized(): boolean; } export module zzaf { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaf,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaf.zza>; public isInitialized(): boolean; } } export class zzag extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag>; public isInitialized(): boolean; } export module zzag { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag.zzb>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag.zzb>*/; public toString(): string; } } export class zzah extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzah,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzah.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzah>; public isInitialized(): boolean; } export module zzah { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzah,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzah.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzah.zza>; public isInitialized(): boolean; } } export class zzai extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzai,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzai.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzai>; public isInitialized(): boolean; } export module zzai { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzai,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzai.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzai.zza>; public isInitialized(): boolean; } } export class zzaj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj>; public isInitialized(): boolean; } export module zzaj { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzb>; public isInitialized(): boolean; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzc>; public isInitialized(): boolean; } export module zzc { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zzc.zza>; public isInitialized(): boolean; } } } export class zzak extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzak,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzak.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzak>; public isInitialized(): boolean; } export module zzak { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzak,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzak.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzak.zza>; public isInitialized(): boolean; } } export class zzal extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal>; public isInitialized(): boolean; } export module zzal { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal.zzb>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal.zzb>*/; } } export class zzam extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzam,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzam.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzam>; public isInitialized(): boolean; } export module zzam { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzam,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzam.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzam.zza>; public isInitialized(): boolean; } } export class zzan extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzan,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzan.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzan>; public isInitialized(): boolean; } export module zzan { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzan,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzan.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzan.zza>; public isInitialized(): boolean; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzb>; public isInitialized(): boolean; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzb.zza>; public isInitialized(): boolean; } } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzc>; public isInitialized(): boolean; } export module zzc { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzc.zza>; public isInitialized(): boolean; } } export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzd,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzd>; public isInitialized(): boolean; } export module zzd { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzd,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzd.zza>; public isInitialized(): boolean; } } export class zze extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze>; public isInitialized(): boolean; } export module zze { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze.zzb>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze.zzb>*/; public toString(): string; } } export class zzf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzf,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzf>; public isInitialized(): boolean; } export module zzf { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzf,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzf.zza>; public isInitialized(): boolean; } } export class zzg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzg,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzg.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzg>; public isInitialized(): boolean; } export module zzg { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzg,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzg.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzg.zza>; public isInitialized(): boolean; } } export class zzh extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzh,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzh.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzh>; public isInitialized(): boolean; } export module zzh { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzh,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzh.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzh.zza>; public isInitialized(): boolean; } } export class zzi extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzi,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzi.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzi>; public isInitialized(): boolean; } export module zzi { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzi,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzi.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzi.zza>; public isInitialized(): boolean; } } export class zzj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzj,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzj.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzj>; public isInitialized(): boolean; } export module zzj { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzj,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzj.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzj.zza>; public isInitialized(): boolean; } } export class zzk extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzk,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzk.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzk>; public isInitialized(): boolean; } export module zzk { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzk,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzk.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzk.zza>; public isInitialized(): boolean; } } export class zzl extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzl,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzl.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzl>; public isInitialized(): boolean; } export module zzl { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzl,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzl.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzl.zza>; public isInitialized(): boolean; } } export class zzm extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzm,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzm.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzm>; public isInitialized(): boolean; } export module zzm { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzm,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzm.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzm.zza>; public isInitialized(): boolean; } } export class zzn extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzn,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzn.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzn>; public isInitialized(): boolean; } export module zzn { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzn,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzn.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzn.zza>; public isInitialized(): boolean; } } export class zzo extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzo,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzo.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzo>; public isInitialized(): boolean; } export module zzo { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzo,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzo.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzo.zza>; public isInitialized(): boolean; } } export class zzp extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp>; public isInitialized(): boolean; } export module zzp { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza>; public isInitialized(): boolean; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza.zzb>; public isInitialized(): boolean; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zzb>; public isInitialized(): boolean; } } export class zzq extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzq,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzq.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzq>; public isInitialized(): boolean; } export module zzq { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzq,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzq.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzq.zza>; public isInitialized(): boolean; } } export class zzr extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr>; public isInitialized(): boolean; } export module zzr { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zza>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zza>*/; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzb>; public isInitialized(): boolean; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzc>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzc>*/; } export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzd>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzd>*/; public toString(): string; } export class zze extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zze>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zze>*/; public toString(): string; } } export class zzs extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzs,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzs.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzs>; public isInitialized(): boolean; } export module zzs { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzs,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzs.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzs.zza>; public isInitialized(): boolean; } } export class zzt extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt>; public isInitialized(): boolean; } export module zzt { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt.zzb>; public isInitialized(): boolean; } } export class zzu extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzu,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzu.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzu>; public isInitialized(): boolean; } export module zzu { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzu,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzu.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzu.zza>; public isInitialized(): boolean; } } export class zzv extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzv,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzv.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzv>; public isInitialized(): boolean; } export module zzv { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzv,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzv.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzv.zza>; public isInitialized(): boolean; } } export class zzw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw>; public isInitialized(): boolean; } export module zzw { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw.zzb>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw.zzb>*/; public toString(): string; } } export class zzx extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx>; public isInitialized(): boolean; } export module zzx { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zza>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zza>*/; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zzb>; public isInitialized(): boolean; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zzc>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zzc>*/; public toString(): string; } } export class zzy extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy>; public isInitialized(): boolean; } export module zzy { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zza,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zza>; public isInitialized(): boolean; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zza,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zza.zza>; public isInitialized(): boolean; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzy.zzb>; public isInitialized(): boolean; } } export class zzz extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz>; public isInitialized(): boolean; } export module zzz { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz.zzb>; public isInitialized(): boolean; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbi extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbi>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbj { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbk extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbk>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbl extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zze.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbm extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbn extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbo extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzp.zza.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbo>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbp extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbq extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbq>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbq>*/; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbr extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbs extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbq>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbs>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbt extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbu>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbt>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbu extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbu>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbu>*/; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbv extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbw extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbx extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzby extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzby>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzbz extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzca extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzca>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zzd>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzr.zze>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcd extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzce extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzce>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzt.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcf>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzw.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzch extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzch>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzci extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzci>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzck extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzx.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzck>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcl extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcm extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcn extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzz.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzco extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzco>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcp extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcq extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcr extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcs extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaa.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcs>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzct extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzct>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcu extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzag.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcv extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcw extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcx extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzaj.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcy extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzal.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcy>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzcz extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzcz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzd>; public static UTF_8: java.nio.charset.Charset; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzda { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzda>; public getVersion(param0: string): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdc>; public run(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdd>; public getHandler(): globalAndroid.os.Handler; public handleMessage(param0: globalAndroid.os.Message): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzde extends java.util.concurrent.Callable<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzde>; public call(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdf { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdf>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdg { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdg>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdg interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzck(): void; release(): void; }); public constructor(); public release(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdi { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdi>; public onBackgroundStateChanged(param0: boolean): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdj { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdk>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdl extends java.util.concurrent.Callable<java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdl>; public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdm extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdn { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdn>; public onDeleted(param0: string, param1: com.google.firebase.FirebaseOptions): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdo { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdo>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdo interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zza(param0: java.io.BufferedWriter): void; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdp extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdo { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdr>; public constructor(param0: com.google.firebase.FirebaseApp); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzds { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzds>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzds>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdt>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdt interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zza(param0: java.io.File): java.io.File; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdu>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdu interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zza(param0: java.io.File, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdy*/): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdx*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdv { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdw>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdw>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdx>; public isValid(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdy { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdy>; public constructor(param0: com.google.firebase.FirebaseApp, param1: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzdz { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zze { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zze>; public static checkArgument(param0: boolean): void; public static checkNotNull(param0: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzea { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzea>; public constructor(param0: com.google.firebase.FirebaseApp, param1: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdu*/, param3: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzds*/); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzeb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeb>; public getModelHash(): string; public constructor(param0: string, param1: globalAndroid.net.Uri, param2: string, param3: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzds*/); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzec extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzec>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzed { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzed>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzee { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzee>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzef extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzef>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzeg { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg>; public constructor(); public toString(): string; public getAsBoolean(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzeh extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg*/ implements any /* java.lang.Iterable<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeh>; public constructor(); public hashCode(): number; public equals(param0: any): boolean; public iterator(): any /* java.util.Iterator<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg>*/; public getAsBoolean(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzei extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzei>; public constructor(); public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzej extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzek { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzej>; public constructor(param0: string); public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzek { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzek>; public constructor(param0: string); public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzel extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzel>; public constructor(); public has(param0: string): boolean; public entrySet(): any /* java.util.Set<java.util.Map.Entry<string,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg>>*/; public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzem extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzem>; public constructor(); public hashCode(): number; public constructor(param0: string); public constructor(param0: java.lang.Boolean); public constructor(param0: java.lang.Number); public equals(param0: any): boolean; public getAsBoolean(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzen { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzen>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzeo<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzep extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzek { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzep>; public constructor(param0: string); public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzeq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeq>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeq interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzer extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzer>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzes { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzes>; public longValue(): number; public hashCode(): number; public constructor(param0: string); public floatValue(): number; public intValue(): number; public toString(): string; public equals(param0: any): boolean; public doubleValue(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzet { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzet>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzeu extends java.util.Comparator<java.lang.Comparable> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzev<K, V> extends java.util.AbstractMap<any,any> implements java.io.Serializable { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzev<any,any>>; public constructor(); public get(param0: any): any; public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>; public size(): number; public remove(param0: any): any; public containsKey(param0: any): boolean; public clear(): void; public keySet(): java.util.Set<any>; public put(param0: any, param1: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzew extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfb<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzew>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzex extends java.util.AbstractSet<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzex>; public contains(param0: any): boolean; public size(): number; public remove(param0: any): boolean; public clear(): void; public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzey extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfb<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzey>; public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzez extends java.util.AbstractSet<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzez>; public contains(param0: any): boolean; public size(): number; public iterator(): java.util.Iterator<any>; public remove(param0: any): boolean; public clear(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzf extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzf>; public static equal(param0: any, param1: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfa<K, V> extends java.util.Map.Entry<any,any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfa<any,any>>; public getValue(): any; public hashCode(): number; public getKey(): any; public toString(): string; public setValue(param0: any): any; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzfb<T> extends java.util.Iterator<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfb<any>>; public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfe extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.util.concurrent.atomic.AtomicIntegerArray> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfe>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzff extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Class> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzff>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfg extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Number> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfh extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Number> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfi extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Number> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfi>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfj extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Number> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfk extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<string>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfk>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfl extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Character> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfm extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.math.BigInteger> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfn extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.math.BigDecimal> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfo extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.util.BitSet> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfo>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfp extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.StringBuilder> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfq extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.net.URL> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfr extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.StringBuffer> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfs extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.net.InetAddress> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfs>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzft extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.net.URI> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzft>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfu extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.util.Currency> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfv extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.util.UUID> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfw extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.util.Calendar> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfy extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeg>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfy>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzfz extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.util.Locale> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzg<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzak<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzg<any>>; public constructor(); public previousIndex(): number; public constructor(param0: number, param1: number); public previous(): any; public nextIndex(): number; public hasNext(): boolean; public get(param0: number): any; public hasPrevious(): boolean; public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzga { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzga>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgb extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Boolean> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgc>; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgd>; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzge { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzge>; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgf { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgf>; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgg extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Boolean> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgi extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Number> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgi>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgj extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Number> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgk extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.util.concurrent.atomic.AtomicInteger> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgk>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgl extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.lang.Number> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgm>; public nextBoolean(): boolean; public nextLong(): number; public close(): void; public endArray(): void; public nextNull(): void; public hasNext(): boolean; public nextName(): string; public nextString(): string; public beginArray(): void; public constructor(param0: java.io.Reader); public toString(): string; public beginObject(): void; public isLenient(): boolean; public nextDouble(): number; public nextInt(): number; public endObject(): void; public setLenient(param0: boolean): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgn extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo<java.util.concurrent.atomic.AtomicBoolean> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgo { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgo>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgo>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgp extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzet { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgq>; public constructor(param0: string); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgr>; public close(): void; public constructor(param0: java.io.Writer); public setLenient(param0: boolean): void; public flush(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgs>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt>; } export module zzgt { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zza,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zza>; public isInitialized(): boolean; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zza,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zza.zza>; public isInitialized(): boolean; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb>; public isInitialized(): boolean; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzb>; public isInitialized(): boolean; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzc>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzc>*/; public toString(): string; } export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzd>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzd>*/; public toString(): string; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgu extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgv extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgx extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgy extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgy>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzgz extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzha extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzgt.zzb.zzd>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzha>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhc>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhc>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzhd<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhd<any,any>>; public constructor(); public isInitialized(): boolean; public toByteArray(): native.Array<number>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhe extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhe>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhf<MessageType> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhf<any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzhg<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjy*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhg<any,any>>; public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzhi<E> extends java.util.AbstractList<any> implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziv<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhi<any>>; public addAll(param0: number, param1: java.util.Collection<any>): boolean; public remove(param0: number): any; public set(param0: number, param1: any): any; public add(param0: any): boolean; public hashCode(): number; public remove(param0: any): boolean; public removeAll(param0: java.util.Collection<any>): boolean; public add(param0: number, param1: any): void; public clear(): void; public equals(param0: any): boolean; public addAll(param0: java.util.Collection<any>): boolean; public retainAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzhj extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhj>; public size(): number; public hashCode(): number; public toString(): string; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzhk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhk>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhl extends java.lang.Object /* java.util.Comparator<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhj>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhm extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzho { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhm>; public nextByte(): number; public hasNext(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhn { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzho extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzho>; public nextByte(): number; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhp { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhp>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhq extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzht { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhq>; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhs extends java.util.Iterator<java.lang.Byte> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhs>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { nextByte(): number; }); public constructor(); public nextByte(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzht extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzht>; public bytes: native.Array<number>; public size(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzhu extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhj { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzhv { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhx extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhv { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhy { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhy>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzhz { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzi { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzi>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzia extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzia>; } export module zzia { export class zza { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzia.zza>; } export class zzb extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzia { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzia.zzb>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzib { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzib>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzic extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzic>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzid<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzid<any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzie { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzie>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzif { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzif>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzig extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzid<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzig>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzih { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzih>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzii<FieldDescriptorType> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzii<any>>; public iterator(): java.util.Iterator<java.util.Map.Entry<FieldDescriptorType,any>>; public hashCode(): number; public equals(param0: any): boolean; public isInitialized(): boolean; public isImmutable(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzij { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzij>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzij>*/; public id(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzik<T> extends java.lang.Comparable<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzik<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzik<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzab(): number; zzgf(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzls*/; zzgg(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlv*/; zzgh(): boolean; zzgi(): boolean; zza(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjy*/, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjy*/; zza(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkb*/, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkb*/): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkb*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzil { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzil>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzil>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzim { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzim>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzin<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhd<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<any,any>>; public constructor(); public hashCode(): number; public toString(): string; public equals(param0: any): boolean; public isInitialized(): boolean; } export module zzin { export class zza<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhf<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zza<any>>; public constructor(param0: any); public constructor(); } export class zzb<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhg<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb<any,any>>; public constructor(param0: any); public isInitialized(): boolean; public constructor(); } export class zzc extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzc>; public static values$50KLMJ33DTMIUPRFDTJMOP9FE1P6UT3FC9QMCBQ7CLN6ASJ1EHIM8JB5EDPM2PR59HKN8P949LIN8Q3FCHA6UIBEEPNMMP9R0(): native.Array<number>; } export abstract class zzd<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin<any,any>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzd<any,any>>; public isInitialized(): boolean; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzio extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzio>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzip { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzip>; public static hashCode(param0: native.Array<number>): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zziq extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhi<java.lang.Integer> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziq>; public addAll(param0: number, param1: java.util.Collection<any>): boolean; public remove(param0: number): any; public size(): number; public hashCode(): number; public remove(param0: any): boolean; public equals(param0: any): boolean; public removeRange(param0: number, param1: number): void; public getInt(param0: number): number; public addAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzir<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzis { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzis interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzab(): number; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzit extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziv<java.lang.Integer> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzit>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzit interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzfj(): void; zzfi(): boolean; zzas(param0: number): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziv<any>*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zziu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziu interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zziv<E> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziv<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziv<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzfj(): void; zzfi(): boolean; zzas(param0: number): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziv<E>*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zziw<F, T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziw<any,any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziw<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzix extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziy { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzix>; public constructor(param0: string); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zziy { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziy>; public constructor(param0: string); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zziz extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziz>; public hashCode(): number; public toString(): string; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzj { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzja { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzja>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzja>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjb<K> extends java.util.Map.Entry<any,any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjb<any>>; public getValue(): any; public getKey(): any; public setValue(param0: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjd>; public constructor(); public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzje<K> extends java.util.Iterator<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzje<any>>; public constructor(param0: java.util.Iterator<java.util.Map.Entry<any,any>>); public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjf { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjf>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getRaw(param0: number): any; zzc(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhj*/): void; zzha(): java.util.List<any>; zzhb(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjf*/; }); public constructor(); public getRaw(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhi<string>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjg>; public constructor(); public addAll(param0: number, param1: java.util.Collection<any>): boolean; public size(): number; public getRaw(param0: number): any; public clear(): void; public constructor(param0: number); public addAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzji { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzji>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjj extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzji { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjk extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzji { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjk>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjl extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkl { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjl>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjm extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhi<java.lang.Long> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjm>; public addAll(param0: number, param1: java.util.Collection<any>): boolean; public remove(param0: number): any; public size(): number; public hashCode(): number; public remove(param0: any): boolean; public equals(param0: any): boolean; public removeRange(param0: number, param1: number): void; public getLong(param0: number): number; public addAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjn extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjo extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjo>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjp<K, V> extends java.util.LinkedHashMap<any,any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjp<any,any>>; public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>; public hashCode(): number; public remove(param0: any): any; public clear(): void; public isMutable(): boolean; public put(param0: any, param1: any): any; public equals(param0: any): boolean; public putAll(param0: java.util.Map<any,any>): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjq<K, V> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjq<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjr extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjs>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzn(param0: any): java.util.Map<any,any>; zzo(param0: any): any; zzm(param0: any): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjq<any,any>*/; zze(param0: any, param1: any): any; zzb(param0: number, param1: any, param2: any): number; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjt>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjt interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzhh(): number; zzhi(): boolean; zzhj(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzju { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzju>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjv extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzb(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzia*/): void; zzgk(): number; zzfd(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhj*/; zzgn(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjy*/; zzgo(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/; isInitialized(): boolean; }); public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjw>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjw interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzb(param0: java.lang.Class<any>): boolean; zzc(param0: java.lang.Class<any>): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjt*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzgo(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/; isInitialized(): boolean; }); public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjy extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjy>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjy interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzgu(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/; zzgt(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/; zza(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjy*/; zzgo(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/; isInitialized(): boolean; }); public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzjz<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjz<any>>; public hashCode(param0: any): number; public equals(param0: any, param1: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzk<K, V> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzv<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzk<any,any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzka { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzka>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkb extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkb>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkb interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzhn(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkb*/; zzb(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzia*/): void; zzgk(): number; zzfd(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhj*/; zzgn(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjy*/; zzgo(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/; isInitialized(): boolean; }); public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkc<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkc<any>>; public hashCode(param0: any): number; public equals(param0: any, param1: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkd extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzke { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzke { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzke>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzke interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkf<MessageType> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkf<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkf<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkg { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzki { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzki>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzki interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkj extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkk<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhi<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkk<any>>; public remove(param0: number): any; public set(param0: number, param1: any): any; public add(param0: any): boolean; public size(): number; public remove(param0: any): boolean; public add(param0: number, param1: any): void; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkl { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkl>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkl interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzd(param0: java.lang.Class): any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any>*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkm<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zza(param0: T, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlx*/): void; zzi(param0: T): void; zzq(param0: T): boolean; equals(param0: T, param1: T): boolean; hashCode(param0: T): number; zzf(param0: T, param1: T): void; zzp(param0: T): number; }); public constructor(); public equals(param0: T, param1: T): boolean; public hashCode(param0: T): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkn<K, V> extends java.util.AbstractMap<any,any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkn<any,any>>; public get(param0: any): any; public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>; public size(): number; public hashCode(): number; public remove(param0: any): any; public containsKey(param0: any): boolean; public clear(): void; public equals(param0: any): boolean; public isImmutable(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzko { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzko>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkp extends java.util.Iterator<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkp>; public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkq extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkn<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzks extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzky*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzks>; public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkt extends java.lang.Iterable<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkt>; public iterator(): java.util.Iterator<any>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzku extends java.util.Iterator<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzku>; public hasNext(): boolean; public remove(): void; public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkv extends java.util.Iterator<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkv>; public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkw extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkw>; public getValue(): any; public hashCode(): number; public toString(): string; public setValue(param0: any): any; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkx extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzky extends java.util.AbstractSet<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzky>; public contains(param0: any): boolean; public size(): number; public remove(param0: any): boolean; public clear(): void; public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzkz extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkz>; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzl<K, V> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzs<any,any>*/ implements java.util.Map<any,any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzl<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzla { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzla>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlb>; public constructor(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjv*/); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlc>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlc interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { size(): number; zzx(param0: number): number; }); public constructor(); public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzld { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzld>; public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzle<T, B> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzle<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlf extends java.util.AbstractList<string> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlf>; public listIterator(param0: number): java.util.ListIterator<string>; public iterator(): java.util.Iterator<string>; public size(): number; public getRaw(param0: number): any; public constructor(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjf*/); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzle<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzld,com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzld>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlh extends java.util.Iterator<string> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlh>; public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzli extends java.util.ListIterator<string> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzli>; public previousIndex(): number; public nextIndex(): number; public hasNext(): boolean; public remove(): void; public hasPrevious(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlj extends java.security.PrivilegedExceptionAction<sun.misc.Unsafe> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlk>; } export module zzlk { export class zza extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlk.zzc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlk.zza>; } export class zzb extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlk.zzc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlk.zzb>; } export abstract class zzc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlk.zzc>; } export class zzd extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlk.zzc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlk.zzd>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzll { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzll>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzln { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzln>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlo extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzll { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlo>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlp { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlq extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzll { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlr extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzls { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzls { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzls>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzls>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlt extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzls { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlt>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlu extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzls { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlv { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlv>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlv>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlw extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzls { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzlx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlx>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzlx interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzfx(): number; zzr(param0: number, param1: number): void; zzi(param0: number, param1: number): void; zzj(param0: number, param1: number): void; zza(param0: number, param1: number): void; zza(param0: number, param1: number): void; zzs(param0: number, param1: number): void; zza(param0: number, param1: number): void; zzh(param0: number, param1: number): void; zzc(param0: number, param1: number): void; zzk(param0: number, param1: number): void; zza(param0: number, param1: boolean): void; zzc(param0: number, param1: string): void; zza(param0: number, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhj*/): void; zzi(param0: number, param1: number): void; zzj(param0: number, param1: number): void; zzb(param0: number, param1: number): void; zza(param0: number, param1: any, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any>*/): void; zzb(param0: number, param1: any, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any>*/): void; zzao(param0: number): void; zzap(param0: number): void; zza(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzb(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzc(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zzd(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zze(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zzf(param0: number, param1: java.util.List<java.lang.Float>, param2: boolean): void; zzg(param0: number, param1: java.util.List<java.lang.Double>, param2: boolean): void; zzh(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzi(param0: number, param1: java.util.List<java.lang.Boolean>, param2: boolean): void; zza(param0: number, param1: java.util.List<string>): void; zzb(param0: number, param1: any /* java.util.List<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhj>*/): void; zzj(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzk(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzl(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zzm(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzn(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zza(param0: number, param1: java.util.List<any>, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any>*/): void; zzb(param0: number, param1: java.util.List<any>, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm<any>*/): void; zza(param0: number, param1: any): void; zza(param0: number, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjq<any,any>*/, param2: java.util.Map): void; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzm<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzp<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzm<any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzn<E> extends java.util.AbstractCollection<any> implements java.io.Serializable { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzn<any>>; public contains(param0: any): boolean; public add(param0: any): boolean; public remove(param0: any): boolean; public removeAll(param0: java.util.Collection<any>): boolean; public toArray(param0: native.Array<any>): native.Array<any>; public clear(): void; public toArray(): native.Array<any>; public addAll(param0: java.util.Collection<any>): boolean; public retainAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzo<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzn<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzo<any>>; public addAll(param0: number, param1: java.util.Collection<any>): boolean; public contains(param0: any): boolean; public set(param0: number, param1: any): any; public remove(param0: number): any; public add(param0: any): boolean; public lastIndexOf(param0: any): number; public hashCode(): number; public remove(param0: any): boolean; public add(param0: number, param1: any): void; public indexOf(param0: any): number; public equals(param0: any): boolean; public addAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzp<E> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzp<any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzq<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzg<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzq<any>>; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzr<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzm<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzr<any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzs<K, V> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzs<any,any>>; public getOrDefault(param0: any, param1: V): V; public get(param0: any): V; public hashCode(): number; public containsKey(param0: any): boolean; public clear(): void; public put(param0: K, param1: V): V; public remove(param0: any): V; public toString(): string; public isEmpty(): boolean; public equals(param0: any): boolean; public containsValue(param0: any): boolean; public putAll(param0: java.util.Map<any,any>): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzt extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzo<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzt>; public size(): number; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export abstract class zzu<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzn<any>*/ implements java.util.Set<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzu<any>>; public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzv<K, V> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzv<any,any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzal<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzw>; public hasNext(): boolean; public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzx<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzm<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzx<any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzy<K, V> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzl<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzy<any,any>>; public get(param0: any): any; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage_translate { export class zzz { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzz>; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class FirebaseTranslateLanguage { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage>; public static AF: number; public static AR: number; public static BE: number; public static BG: number; public static BN: number; public static CA: number; public static CS: number; public static CY: number; public static DA: number; public static DE: number; public static EL: number; public static EN: number; public static EO: number; public static ES: number; public static ET: number; public static FA: number; public static FI: number; public static FR: number; public static GA: number; public static GL: number; public static GU: number; public static HE: number; public static HI: number; public static HR: number; public static HT: number; public static HU: number; public static ID: number; public static IS: number; public static IT: number; public static JA: number; public static KA: number; public static KN: number; public static KO: number; public static LT: number; public static LV: number; public static MK: number; public static MR: number; public static MS: number; public static MT: number; public static NL: number; public static NO: number; public static PL: number; public static PT: number; public static RO: number; public static RU: number; public static SK: number; public static SL: number; public static SQ: number; public static SV: number; public static SW: number; public static TA: number; public static TE: number; public static TH: number; public static TL: number; public static TR: number; public static UK: number; public static UR: number; public static VI: number; public static ZH: number; public static languageCodeForLanguage(param0: number): string; public static getAllLanguages(): java.util.Set<java.lang.Integer>; public static languageForLanguageCode(param0: string): java.lang.Integer; } export module FirebaseTranslateLanguage { export class TranslateLanguage { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage.TranslateLanguage>; /** * Constructs a new instance of the com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage$TranslateLanguage interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class FirebaseTranslateModelManager { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateModelManager>; public downloadRemoteModelIfNeeded(param0: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel): com.google.android.gms.tasks.Task<java.lang.Void>; public getLocalModel(param0: string): com.google.firebase.ml.common.modeldownload.FirebaseLocalModel; public static getInstance(): com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateModelManager; public getNonBaseRemoteModel(param0: string): com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel; public registerRemoteModel(param0: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel): boolean; public registerLocalModel(param0: com.google.firebase.ml.common.modeldownload.FirebaseLocalModel): boolean; public getAvailableModels(param0: com.google.firebase.FirebaseApp): com.google.android.gms.tasks.Task<java.util.Set<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateRemoteModel>>; public deleteDownloadedModel(param0: com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateRemoteModel): com.google.android.gms.tasks.Task<java.lang.Void>; } export module FirebaseTranslateModelManager { export class zza { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateModelManager.zza>; public downloadRemoteModelIfNeeded(param0: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel): com.google.android.gms.tasks.Task<java.lang.Void>; public registerRemoteModel(param0: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel): boolean; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class FirebaseTranslateRemoteModel { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateRemoteModel>; public getUniqueModelNameForPersist(): string; public getLanguage(): number; public getModelNameForBackend(): string; public hashCode(): number; public getPluginIdentifier(): any; public getLanguageCode(): string; public equals(param0: any): boolean; } export module FirebaseTranslateRemoteModel { export class Builder { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateRemoteModel.Builder>; public setDownloadConditions(param0: com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions): com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateRemoteModel.Builder; public constructor(param0: number); public setFirebaseApp(param0: com.google.firebase.FirebaseApp): com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateRemoteModel.Builder; public build(): com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateRemoteModel; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class FirebaseTranslator { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator>; public close(): void; public downloadModelIfNeeded(): com.google.android.gms.tasks.Task<java.lang.Void>; public translate(param0: string): com.google.android.gms.tasks.Task<string>; public static getInstance(param0: com.google.firebase.FirebaseApp, param1: com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions): com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator; public downloadModelIfNeeded(param0: com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions): com.google.android.gms.tasks.Task<java.lang.Void>; } export module FirebaseTranslator { export class zza extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdg { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator.zza>; public constructor(param0: com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdg*/); public release(): void; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class FirebaseTranslatorOptions { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions>; public getSourceLanguage(): number; public getSourceLanguageCode(): string; public hashCode(): number; public getTargetLanguage(): number; public getTargetLanguageCode(): string; public equals(param0: any): boolean; } export module FirebaseTranslatorOptions { export class Builder { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions.Builder>; public setSourceLanguage(param0: number): com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions.Builder; public constructor(); public build(): com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions; public setTargetLanguage(param0: number): com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions.Builder; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class TranslateJni extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdg { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.TranslateJni>; public constructor(param0: com.google.firebase.FirebaseApp, param1: string, param2: string); public release(): void; } export module TranslateJni { export class zza { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.TranslateJni.zza>; public getErrorCode(): number; public constructor(param0: number); } export class zzb { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.TranslateJni.zzb>; public getErrorCode(): number; public constructor(param0: number); } export class zzc { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.TranslateJni.zzc>; } } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zza { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zza>; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzb { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzb>; public accept(param0: java.io.File, param1: string): boolean; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzc { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzc>; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzd { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzd>; public run(): void; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zze { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zze>; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzf { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzf>; public run(): void; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzg { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzg>; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzh { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzh>; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzi { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzi>; public constructor(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdh*/, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbh.zzan*/); public constructor(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdh*/, param1: com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel); } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzj { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzj>; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzk { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzk>; public constructor(param0: any /* com.google.firebase.ml.naturallanguage.translate.internal.zzi*/); } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzl { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzl>; public then(param0: com.google.android.gms.tasks.Task): any; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzm extends com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzdu { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzm>; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzn { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzn>; public then(param0: com.google.android.gms.tasks.Task): any; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzo { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzo>; public then(param0: com.google.android.gms.tasks.Task): any; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzp { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzp>; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzq { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzq>; public call(): any; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzr { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzr>; public then(param0: com.google.android.gms.tasks.Task): any; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzs { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzs>; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzt extends com.google.firebase.ml.naturallanguage.translate.internal.zzu { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzt>; public get(param0: string): string; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export module internal { export class zzu { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.internal.zzu>; /** * Constructs a new instance of the com.google.firebase.ml.naturallanguage.translate.internal.zzu interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { get(param0: string): string; }); public constructor(); public get(param0: string): string; } } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zza { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zza>; public then(param0: com.google.android.gms.tasks.Task): any; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzb { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzb>; public call(): any; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzc { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzc>; public call(): any; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzd { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzd>; public then(param0: com.google.android.gms.tasks.Task): any; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zze { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zze>; public call(): any; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzf { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzf>; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzg { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzg>; public then(param0: com.google.android.gms.tasks.Task): any; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzh { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzh>; public call(): any; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzi { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzi>; public onComplete(param0: com.google.android.gms.tasks.Task): void; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzj { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzj>; public call(): any; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module naturallanguage { export module translate { export class zzk { public static class: java.lang.Class<com.google.firebase.ml.naturallanguage.translate.zzk>; } } } } } } } //Generics information: //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaa:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzab:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzad:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaf:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzah:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzai:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzaj:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzak:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzal:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzan:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzbb:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzeo:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzev:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfa:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzfb:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzg:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhd:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhf:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhg:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzhi:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzid:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzii:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzik:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zza:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzb:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzin.zzd:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzir:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziv:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zziw:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjb:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzje:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjp:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjq:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzjz:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzk:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkc:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkf:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkk:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkm:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzkn:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzl:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzle:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzm:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzn:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzo:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzp:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzq:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzr:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzs:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzu:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzv:2 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzx:1 //com.google.android.gms.internal.firebase_ml_naturallanguage_translate.zzy:2
the_stack
import { compareDates } from "./Util"; import fs = require("fs"); import { window, commands } from "vscode"; import path = require("path"); import { Summary } from "../models/Summary"; import { updateSummaryMilestones, incrementSummaryShare, updateSummaryLanguages } from "./SummaryUtil"; import { getLanguages } from "./LanguageUtil"; import { HOURS_THRESHOLD } from "./Constants"; import { Milestone } from "../models/Milestone"; import { getFile, getFileDataAsJson, fetchSummaryJsonFileData } from "../managers/FileManager"; export function getMilestonesJsonFilePath(): string { return getFile("milestones.json"); } export function checkMilestonesJson(): boolean { const filePath = getMilestonesJsonFilePath(); if (!fs.existsSync(filePath)) { try { const src = path.join(__dirname, "/assets/milestones.json"); fs.copyFileSync(src, filePath); } catch (e) { return false; } } return true; } export function deleteMilestoneJson() { const filepath = getMilestonesJsonFilePath(); const fileExists = fs.existsSync(filepath); if (fileExists) { fs.unlinkSync(filepath); } } export function getTodaysLocalMilestones(): Array<number> { const now = new Date(); // finds milestones achieved on date give and returns them const sendMilestones: Array<number> = []; const milestoneData = getAllMilestones(); if (milestoneData && milestoneData.milestones) { const milestones = milestoneData.milestones; for (let milestone of milestones) { if (milestone.achieved && milestone.date_achieved && compareDates(new Date(milestone.date_achieved), now)) { sendMilestones.push(milestone.id); } } } return sendMilestones; } export function compareWithLocalMilestones(serverMilestones: any) { // get the local copy of the milestones and update the attributes const localMilestoneData = getAllMilestones(); const milestones = localMilestoneData.milestones || []; const hasServerMilestones = (serverMilestones && serverMilestones.length); for (let milestone of milestones) { if (hasServerMilestones) { const serverMilestone = serverMilestones.find((n:any) => n.milestones.includes(milestone.id)); if (serverMilestone) { milestone.date_achieved = new Date(serverMilestone.unix_date * 1000); milestone.achieved = true; } } } writeToMilestoneJson(milestones); } export function checkCodeTimeMetricsMilestonesAchieved(): Array<number> { let achievedMilestones = []; const summary: Summary = fetchSummaryJsonFileData(); // check for aggregate codetime const aggHours = summary.hours + summary.currentHours; if (aggHours >= 200) { achievedMilestones.push(6, 5, 4, 3, 2, 1); } else if (aggHours >= 120) { achievedMilestones.push(5, 4, 3, 2, 1); } else if (aggHours >= 90) { achievedMilestones.push(4, 3, 2, 1); } else if (aggHours >= 60) { achievedMilestones.push(3, 2, 1); } else if (aggHours >= 30) { achievedMilestones.push(2, 1); } else if (aggHours >= 1) { achievedMilestones.push(1); } // check for daily codetime. These will be given out daily const dayHours = summary.currentHours; if (dayHours >= 10) { achievedMilestones.push(24, 23, 22, 21, 20, 19); } else if (dayHours >= 8) { achievedMilestones.push(23, 22, 21, 20, 19); } else if (dayHours >= 5) { achievedMilestones.push(22, 21, 20, 19); } else if (dayHours >= 3) { achievedMilestones.push(21, 20, 19); } else if (dayHours >= 2) { achievedMilestones.push(20, 19); } else if (dayHours >= 1) { achievedMilestones.push(19); } // check for lines added const lines = summary.lines_added + summary.currentLines; if (lines >= 10000) { achievedMilestones.push(30, 29, 28, 27, 26, 25); } else if (lines >= 1000) { achievedMilestones.push(29, 28, 27, 26, 25); } else if (lines >= 100) { achievedMilestones.push(28, 27, 26, 25); } else if (lines >= 50) { achievedMilestones.push(27, 26, 25); } else if (lines >= 16) { achievedMilestones.push(26, 25); } else if (lines >= 1) { achievedMilestones.push(25); } // check for keystrokes const keystrokes = summary.keystrokes + summary.currentKeystrokes; if (keystrokes >= 42195) { achievedMilestones.push(42, 41, 40, 39, 38, 37); } else if (keystrokes >= 21097) { achievedMilestones.push(41, 40, 39, 38, 37); } else if (keystrokes >= 10000) { achievedMilestones.push(40, 39, 38, 37); } else if (keystrokes >= 5000) { achievedMilestones.push(39, 38, 37); } else if (keystrokes >= 1000) { achievedMilestones.push(38, 37); } else if (keystrokes >= 100) { achievedMilestones.push(37); } if (achievedMilestones.length) { return achievedMilestonesJson(achievedMilestones); } return []; } export function checkLanguageMilestonesAchieved(): Array<number> { updateSummaryLanguages(); const summary: Summary = fetchSummaryJsonFileData(); const languages = getLanguages(); let milestones: Set<number> = new Set<number>(); // single language check let language: string; for (language of languages) { switch (language) { case "c": case "cpp": milestones.add(51); break; case "html": case "css": milestones.add(54); break; case "javascript": case "javascriptreact": milestones.add(52); break; case "json": case "jsonc": milestones.add(55); break; case "java": milestones.add(49); break; case "plaintext": milestones.add(53); break; case "python": milestones.add(50); break; case "typescript": case "typescriptreact": milestones.add(56); break; } } // multi language check switch (summary.languages.length) { default: case 6: milestones.add(48); case 5: milestones.add(47); case 4: milestones.add(46); case 3: milestones.add(45); case 2: milestones.add(44); case 1: milestones.add(43); case 0: break; } const milestonesAchieved = Array.from(milestones); if (milestonesAchieved.length > 0) { return achievedMilestonesJson(milestonesAchieved); } return []; } export function checkDaysMilestones(): Array<number> { const summary: Summary = fetchSummaryJsonFileData(); let days = summary.days; let streaks = summary.longest_streak; // curr day is completed only after a certain threshold hours are met // no checks for prev day if (summary.currentHours < HOURS_THRESHOLD) { days--; streaks--; } let achievedMilestones = []; // checking for days if (days >= 110) { achievedMilestones.push(12); } else if (days >= 100) { achievedMilestones.push(11); } else if (days >= 75) { achievedMilestones.push(10); } else if (days >= 50) { achievedMilestones.push(9); } else if (days >= 10) { achievedMilestones.push(8); } else if (days >= 1) { achievedMilestones.push(7); } // checking for streaks if (streaks >= 100) { achievedMilestones.push(18); } else if (streaks >= 60) { achievedMilestones.push(17); } else if (streaks >= 30) { achievedMilestones.push(16); } else if (streaks >= 14) { achievedMilestones.push(15); } else if (streaks >= 7) { achievedMilestones.push(14); } else if (streaks >= 2) { achievedMilestones.push(13); } if (achievedMilestones.length > 0) { return achievedMilestonesJson(achievedMilestones); } return []; } export function checkSharesMilestones(): void { const summary: Summary = fetchSummaryJsonFileData(); const shares = summary.shares; if (shares >= 100) { achievedMilestonesJson([36]); } else if (shares >= 50) { achievedMilestonesJson([35]); } else if (shares >= 21) { achievedMilestonesJson([34]); } else if (shares >= 10) { achievedMilestonesJson([33]); } else if (shares >= 5) { achievedMilestonesJson([32]); } else if (shares >= 1) { achievedMilestonesJson([31]); } } export function checkIfDaily(id: number): boolean { if ((id > 18 && id < 25) || (id > 48 && id < 57)) { return true; } return false; } function checkIdRange(id: number): boolean { const MIN_ID = 1; const MAX_ID = 56; if (id >= MIN_ID && id <= MAX_ID) { return true; } window.showErrorMessage("Incorrect Milestone Id! Please contact cody@software.com for help."); return false; } export function getMilestoneById(id: number): Milestone | any { if (!checkIdRange(id)) { return {}; } const milestoneData = getAllMilestones(); return milestoneData && milestoneData.milestones ? milestoneData.milestones.find((n: any) => n.id === id) : null; } function achievedMilestonesJson(ids: Array<number>): Array<number> { let updatedIds = []; const milestonesData = getAllMilestones(); const milestones = milestonesData.milestones || []; const dateNow = new Date(); let displayedPrompt = false; for (let id of ids) { const milestone = milestones.length > id - 1 ? milestones[id - 1] : null; // check if the milestone ID is valid and if the milestone has been marked as achieved or not if (!checkIdRange(id) || !milestone || (milestone.date_achieved && milestone.achieved)) { continue; } // this is the only place that sets "date_achieved" and "achieved" values milestone.achieved = true; milestone.date_achieved = dateNow.valueOf(); updatedIds.push(id); if (id === 11) { displayedPrompt = true; const title = "View Dashboard"; const msg = "Whoa! You just unlocked the #100DaysOfCode Certificate. Please view it on the 100 Days of Code Dashboard."; const commandCallback = "DoC.viewDashboard"; commands.executeCommand("DoC.showInfoMessage", title, msg, true /*isModal*/, commandCallback); } } if (updatedIds.length) { // updates summary let totalMilestonesAchieved = 0; for (let i = 0; i < milestones.length; i++) { if (milestones[i].achieved) { totalMilestonesAchieved++; } } updateSummaryMilestones(updatedIds, totalMilestonesAchieved); // write to milestones file writeToMilestoneJson(milestones); if (!displayedPrompt) { const title = "View Milestones"; const msg = "Hurray! You just achieved another milestone."; const commandCallback = "DoC.viewMilestones"; commands.executeCommand("DoC.showInfoMessage", title, msg, false /*isModal*/, commandCallback); } return updatedIds; } return []; } export function updateMilestoneShare(id: number): void { if (!checkIdRange(id)) { return; } let milestones = getAllMilestones(); // check and update milestones if not shared if (milestones && milestones.length && milestones[id - 1] && !milestones[id - 1].shared) { milestones[id - 1].shared = true; writeToMilestoneJson(milestones); incrementSummaryShare(); } } export function getTotalMilestonesAchieved(): number { const milestoneData = getAllMilestones(); const milestones = milestoneData.milestones || []; let totalMilestonesAchieved = 0; for (let milestone of milestones) { if (milestone.achieved) { totalMilestonesAchieved++; } } return totalMilestonesAchieved; } /** * This returns the milestones data * {milestones: []} */ export function getAllMilestones(): any { // Checks if the file exists and if not, creates a new file if (!checkMilestonesJson()) { window.showErrorMessage("Cannot access Milestone file! Please contact cody@software.com for help."); return { milestones: [] }; } const filepath = getMilestonesJsonFilePath(); const milestoneData = getFileDataAsJson(filepath); return milestoneData || { milestones: [] }; } export function getThreeMostRecentMilestones(): Array<number> { const milestoneData = getAllMilestones(); const milestones = milestoneData.milestones || []; milestones.sort((a: any, b: any) => { // sorting in descending order of date_achieved if (a.achieved && b.achieved) { return b.date_achieved - a.date_achieved; } else if (a.achieved) { return -1; } else if (b.achieved) { return 1; } else { return 0; } }); let sendMilestones: Array<number> = []; const rawSendMilestones = milestones.slice(0, 3); rawSendMilestones.forEach((milestone: any) => { if (milestone.achieved) { sendMilestones.push(milestone.id); } }); return sendMilestones; } function writeToMilestoneJson(milestones: Array<Milestone>) { const filepath = getMilestonesJsonFilePath(); let sendMilestones = { milestones }; try { fs.writeFileSync(filepath, JSON.stringify(sendMilestones, null, 2)); } catch (err) { console.log(err); } }
the_stack
import { BasicClient } from "../BasicClient"; import { ClientOptions } from "../ClientOptions"; import { Level3Point } from "../Level3Point"; import { Level3Snapshot } from "../Level3Snapshot"; import * as https from "../Https"; import { Trade } from "../Trade"; import { Level3Update } from "../Level3Update"; import { NotImplementedFn } from "../NotImplementedFn"; export type LedgerXClientOptions = ClientOptions & { apiKey?: string; }; /** * LedgerX is defined in https://docs.ledgerx.com/reference#connecting * This socket uses a unified stream for ALL market data. So we will leverage * subscription filtering to only reply with values that of are of interest. */ export class LedgerXClient extends BasicClient { public runId: number; public apiKey: string; constructor({ wssPath = "wss://api.ledgerx.com/ws?token=", apiKey, watcherMs, }: LedgerXClientOptions = {}) { super(wssPath + apiKey, "LedgerX", undefined, watcherMs); this.hasTrades = true; this.hasLevel3Updates = true; this.runId = 0; this.apiKey = apiKey; } protected _sendSubTrades() {} protected _sendUnsubTrades() {} protected _sendSubLevel3Updates(remote_id, market) { this._requestLevel3Snapshot(market); } protected _sendUnSubLevel3Updates() {} protected _sendSubTicker = NotImplementedFn; protected _sendSubCandles = NotImplementedFn; protected _sendUnsubCandles = NotImplementedFn; protected _sendUnsubTicker = NotImplementedFn; protected _sendSubLevel2Snapshots = NotImplementedFn; protected _sendUnsubLevel2Snapshots = NotImplementedFn; protected _sendSubLevel2Updates = NotImplementedFn; protected _sendUnsubLevel2Updates = NotImplementedFn; protected _sendSubLevel3Snapshots = NotImplementedFn; protected _sendUnsubLevel3Snapshots = NotImplementedFn; protected _sendUnsubLevel3Updates = NotImplementedFn; protected _onMessage(msg: string) { this.emit("raw", msg); const json = JSON.parse(msg); if (json.type === "auth_success") { return; } if (json.type === "book_top") { return; } if (json.positions !== undefined) { return; } if (json.collateral !== undefined) { return; } if (json.type === "exposure_reports") { return; } if (json.type === "heartbeat") { this._watcher.markAlive(); // update the run_id if it's changed if (this.runId !== json.run_id) { this.runId = json.run_id; } return; } if (json.type === "action_report") { // insert event if (json.status_type === 200) { const market = this._level3UpdateSubs.get(json.contract_id) || this._level3UpdateSubs.get(json.contract_id.toString()); if (!market) return; const update = this._constructL3Insert(json, market); this.emit("l3update", update, market, json); return; } // trade event, filled either partial or fully if (json.status_type === 201) { // check for trade subscription let market = this._tradeSubs.get(json.contract_id) || this._tradeSubs.get(json.contract_id.toString()); // prettier-ignore if (market) { const trade = this._constructTrade(json, market); this.emit("trade", trade, market, json); } // check for l3 subscription market = this._level3UpdateSubs.get(json.contract_id) || this._level3UpdateSubs.get(json.contract_id.toString()); if (market) { const update = this._constructL3Trade(json, market); this.emit("l3update", update, market, json); } return; } // cancel event if (json.status_type === 203) { const market = this._level3UpdateSubs.get(json.contract_id) || this._level3UpdateSubs.get(json.contract_id.toString()); if (!market) return; const update = this._constructL3Cancel(json, market); this.emit("l3update", update, market, json); return; } // cancelled and replaced event if (json.status_type === 204) { const market = this._level3UpdateSubs.get(json.contract_id) || this._level3UpdateSubs.get(json.contract_id.toString()); if (!market) return; const update = this._constructL3Replace(json, market); this.emit("l3update", update, market, json); return; } } } /** * Obtains the orderbook via REST */ protected async _requestLevel3Snapshot(market) { try { const uri = `https://trade.ledgerx.com/api/book-states/${market.id}?token=${this.apiKey}`; const { data } = await https.get(uri); const sequenceId = data.clock; const asks = []; const bids = []; for (const row of data.book_states) { const orderId = row.mid; const price = row.price.toFixed(2); const size = row.size.toFixed(); const point = new Level3Point(orderId, price, size); if (row.is_ask) asks.push(point); else bids.push(point); } const snapshot = new Level3Snapshot({ exchange: this.name, base: market.base, quote: market.quote, sequenceId, asks, bids, }); this.emit("l3snapshot", snapshot, market); } catch (ex) { // TODO handle this properly this.emit("error", ex); } } /** { mid: 'f4c34b09de0b4064a33b7b46f8180022', filled_size: 5, size: 0, inserted_price: 0, updated_time: 1597173352257155800, inserted_size: 0, timestamp: 1597173352257176800, ticks: 78678024531551, price: 0, original_price: 16000, status_type: 201, order_type: 'customer_limit_order', status_reason: 52, filled_price: 16000, is_volatile: false, clock: 24823, vwap: 16000, is_ask: false, inserted_time: 1597173352257155800, type: 'action_report', original_size: 5, contract_id: 22204639 } { mid: '885be81549974faf88e4430f6046513d', filled_size: 5, size: 0, inserted_price: 0, updated_time: 1597164994095326700, inserted_size: 0, timestamp: 1597173352258250800, ticks: 78678025605522, price: 0, original_price: 16000, status_type: 201, order_type: 'customer_limit_order', status_reason: 0, filled_price: 16000, is_volatile: false, clock: 24824, vwap: 16000, is_ask: true, inserted_time: 1597164994095326700, type: 'action_report', original_size: 10, contract_id: 22204639 } */ protected _constructTrade(msg, market) { let buyOrderId; let sellOrderId; if (msg.is_ask) sellOrderId = msg.mid; else buyOrderId = msg.mid; return new Trade({ exchange: this.name, base: market.base, quote: market.quote, tradeId: undefined, // doesn't emit or match REST API unix: Math.floor(msg.timestamp / 1e6), side: msg.is_ask ? "sell" : "buy", price: msg.filled_price.toFixed(8), amount: msg.filled_size.toFixed(8), buyOrderId, sellOrderId, open_interest: msg.open_interest, }); } /** * 200 - A resting limit order of size inserted_size @ price * inserted_price was inserted into book depth. { inserted_time: 1597176131501325800, timestamp: 1597176131501343700, filled_size: 0, ticks: 81457268698527, size: 1000, contract_id: 22202469, filled_price: 0, inserted_price: 165100, inserted_size: 1000, vwap: 0, is_volatile: true, mid: 'eecd8297c1dc42f1985f67c909540631', original_price: 165100, order_type: 'customer_limit_order', updated_time: 1597176131501325800, original_size: 1000, status_type: 200, status_reason: 0, type: 'action_report', price: 165100, clock: 260, is_ask: false } */ protected _constructL3Insert(msg, market) { const price = msg.price.toFixed(8); const size = msg.inserted_size.toFixed(8); const point = new Level3Point(msg.mid, price, size, { order_type: msg.order_type, status_type: msg.status_type, status_reason: msg.status_reason, is_volatile: msg.is_volatile, timestamp: msg.timestamp, ticks: msg.ticks, inserted_time: msg.inserted_time, updated_time: msg.updated_time, original_price: msg.original_price, original_size: msg.original_size, inserted_price: msg.inserted_price, inserted_size: msg.inserted_size, filled_price: msg.filled_price, filled_size: msg.filled_size, price: msg.price, size: msg.size, vwap: msg.vwap, }); const asks = []; const bids = []; if (msg.is_ask) asks.push(point); else bids.push(point); return new Level3Update({ exchange: this.name, base: market.base, quote: market.quote, sequenceId: msg.clock, timestampMs: Math.floor(msg.inserted_time / 1e6), runId: this.runId, asks, bids, }); } /** * 201 - A cross of size filled_size @ price filled_price occurred. * Subtract filled_size from the resting size for this order. { mid: '885be81549974faf88e4430f6046513d', filled_size: 5, size: 0, inserted_price: 0, updated_time: 1597164994095326700, inserted_size: 0, timestamp: 1597173352258250800, ticks: 78678025605522, price: 0, original_price: 16000, status_type: 201, order_type: 'customer_limit_order', status_reason: 0, filled_price: 16000, is_volatile: false, clock: 24824, vwap: 16000, is_ask: true, inserted_time: 1597164994095326700, type: 'action_report', original_size: 10, contract_id: 22204639 } */ protected _constructL3Trade(msg, market) { const price = msg.original_price.toFixed(8); const size = (msg.original_size - msg.filled_size).toFixed(8); const point = new Level3Point(msg.mid, price, size, { order_type: msg.order_type, status_type: msg.status_type, status_reason: msg.status_reason, is_volatile: msg.is_volatile, timestamp: msg.timestamp, ticks: msg.ticks, inserted_time: msg.inserted_time, updated_time: msg.updated_time, original_price: msg.original_price, original_size: msg.original_size, inserted_price: msg.inserted_price, inserted_size: msg.inserted_size, filled_price: msg.filled_price, filled_size: msg.filled_size, price: msg.price, size: msg.size, vwap: msg.vwap, open_interest: msg.open_interest, }); const asks = []; const bids = []; if (msg.is_ask) asks.push(point); else bids.push(point); return new Level3Update({ exchange: this.name, base: market.base, quote: market.quote, sequenceId: msg.clock, timestampMs: Math.floor(msg.inserted_time / 1e6), runId: this.runId, asks, bids, }); } /** * 203 - An order was cancelled. Remove this order from book depth. { inserted_time: 1597176853952381700, timestamp: 1597176857137740800, filled_size: 0, ticks: 82182905095242, size: 0, contract_id: 22204631, filled_price: 0, inserted_price: 0, inserted_size: 0, vwap: 0, is_volatile: true, mid: 'b623fdd6fae14fcbbcb9ab3b6b9b3771', original_price: 51300, order_type: 'customer_limit_order', updated_time: 1597176853952381700, original_size: 1, status_type: 203, status_reason: 0, type: 'action_report', price: 0, clock: 506, is_ask: false } */ protected _constructL3Cancel(msg, market) { const price = msg.original_price.toFixed(8); const size = (0).toFixed(8); const point = new Level3Point(msg.mid, price, size, { order_type: msg.order_type, status_type: msg.status_type, status_reason: msg.status_reason, is_volatile: msg.is_volatile, timestamp: msg.timestamp, ticks: msg.ticks, inserted_time: msg.inserted_time, updated_time: msg.updated_time, original_price: msg.original_price, original_size: msg.original_size, inserted_price: msg.inserted_price, inserted_size: msg.inserted_size, filled_price: msg.filled_price, filled_size: msg.filled_size, price: msg.price, size: msg.size, vwap: msg.vwap, open_interest: msg.open_interest, }); const asks = []; const bids = []; if (msg.is_ask) asks.push(point); else bids.push(point); return new Level3Update({ exchange: this.name, base: market.base, quote: market.quote, sequenceId: msg.clock, timestampMs: Math.floor(msg.inserted_time / 1e6), runId: this.runId, asks, bids, }); } /** * 204 - An order was cancelled and replaced. The new order retains the * existing mid, and can only reflect an update in size and not price. * Overwrite the resting order size with inserted_size. * { "status_type": 204, "inserted_size": 12, "original_price": 59000, "open_interest": 121, "filled_size": 0, "updated_time": 1623074768372895949, "clock": 40011, "size": 12, "timestamp": 1623074768372897897, "status_reason": 0, "vwap": 0, "inserted_time": 1623074764668677182, "price": 59000, "type": "action_report", "is_ask": true, "original_size": 12, "order_type": "customer_limit_order", "is_volatile": true, "ticks": 25980094140252686, "filled_price": 0, "mid": "c071baaa458a411db184cb6874e86d69", "inserted_price": 59000, "contract_id": 22216779 } */ protected _constructL3Replace(msg, market) { const price = msg.original_price.toFixed(8); const size = msg.inserted_size.toFixed(8); const point = new Level3Point(msg.mid, price, size, { order_type: msg.order_type, status_type: msg.status_type, status_reason: msg.status_reason, is_volatile: msg.is_volatile, timestamp: msg.timestamp, ticks: msg.ticks, inserted_time: msg.inserted_time, updated_time: msg.updated_time, original_price: msg.original_price, original_size: msg.original_size, inserted_price: msg.inserted_price, inserted_size: msg.inserted_size, filled_price: msg.filled_price, filled_size: msg.filled_size, price: msg.price, size: msg.size, vwap: msg.vwap, open_interest: msg.open_interest, }); const asks = []; const bids = []; if (msg.is_ask) asks.push(point); else bids.push(point); return new Level3Update({ exchange: this.name, base: market.base, quote: market.quote, sequenceId: msg.clock, timestampMs: Math.floor(msg.inserted_time / 1e6), runId: this.runId, asks, bids, }); } }
the_stack
import { AppendCommand, BitCountCommand, BitOpCommand, BitPosCommand, DBSizeCommand, DecrByCommand, DecrCommand, DelCommand, EchoCommand, EvalCommand, EvalshaCommand, ExistsCommand, ExpireAtCommand, ExpireCommand, FlushAllCommand, FlushDBCommand, GetBitCommand, GetCommand, GetRangeCommand, GetSetCommand, HDelCommand, HExistsCommand, HGetAllCommand, HGetCommand, HIncrByCommand, HIncrByFloatCommand, HKeysCommand, HLenCommand, HMGetCommand, HMSetCommand, HScanCommand, HSetCommand, HSetNXCommand, HStrLenCommand, HValsCommand, IncrByCommand, IncrByFloatCommand, IncrCommand, KeysCommand, LIndexCommand, LInsertCommand, LLenCommand, LPopCommand, LPushCommand, LPushXCommand, LRangeCommand, LRemCommand, LSetCommand, LTrimCommand, MGetCommand, MSetCommand, MSetNXCommand, PersistCommand, PExpireAtCommand, PExpireCommand, PingCommand, PSetEXCommand, PTtlCommand, PublishCommand, RandomKeyCommand, RenameCommand, RenameNXCommand, RPopCommand, RPushCommand, RPushXCommand, SAddCommand, ScanCommand, SCardCommand, ScoreMember, ScriptExistsCommand, ScriptFlushCommand, ScriptLoadCommand, SDiffCommand, SDiffStoreCommand, SetBitCommand, SetCommand, SetCommandOptions, SetExCommand, SetNxCommand, SetRangeCommand, SInterCommand, SInterStoreCommand, SIsMemberCommand, SMembersCommand, SMoveCommand, SPopCommand, SRandMemberCommand, SRemCommand, SScanCommand, StrLenCommand, SUnionCommand, SUnionStoreCommand, TimeCommand, TouchCommand, TtlCommand, TypeCommand, UnlinkCommand, ZAddCommand, ZAddCommandOptions, ZAddCommandOptionsWithIncr, ZCardCommand, ZCountCommand, ZIncrByCommand, ZInterStoreCommand, ZLexCountCommand, ZPopMaxCommand, ZPopMinCommand, ZRangeCommand, ZRangeCommandOptions, ZRankCommand, ZRemCommand, ZRemRangeByLexCommand, ZRemRangeByRankCommand, ZRemRangeByScoreCommand, ZRevRankCommand, ZScanCommand, ZScoreCommand, ZUnionStoreCommand, } from "./commands/mod.ts"; import { Command, CommandOptions } from "./commands/command.ts"; import { UpstashError } from "./error.ts"; import { Requester } from "./http.ts"; import { UpstashResponse } from "./http.ts"; import { CommandArgs } from "./types.ts"; /** * Upstash REST API supports command pipelining to send multiple commands in * batch, instead of sending each command one by one and waiting for a response. * When using pipelines, several commands are sent using a single HTTP request, * and a single JSON array response is returned. Each item in the response array * corresponds to the command in the same order within the pipeline. * * **NOTE:** * * Execution of the pipeline is not atomic. Even though each command in * the pipeline will be executed in order, commands sent by other clients can * interleave with the pipeline. * * **Examples:** * * ```ts * const p = redis.pipeline() * p.set("key","value") * p.get("key") * const res = await p.exec() * ``` * * You can also chain commands together * ```ts * const p = redis.pipeline() * const res = await p.set("key","value").get("key").exec() * ``` * * It's not possible to infer correct types with a dynamic pipeline, so you can * override the response type manually: * ```ts * redis.pipeline() * .set("key", { greeting: "hello"}) * .get("key") * .exec<["OK", { greeting: string } ]>() * * ``` */ export class Pipeline { private client: Requester; private commands: Command<unknown, unknown>[]; private commandOptions?: CommandOptions<any, any>; constructor(client: Requester, commandOptions?: CommandOptions<any, any>) { this.client = client; this.commands = []; this.commandOptions = commandOptions; } /** * Send the pipeline request to upstash. * * Returns an array with the results of all pipelined commands. * * You can define a return type manually to make working in typescript easier * ```ts * redis.pipeline().get("key").exec<[{ greeting: string }]>() * ``` */ exec = async < TCommandResults extends unknown[] = unknown[], >(): Promise<TCommandResults> => { if (this.commands.length === 0) { throw new Error("Pipeline is empty"); } const res = (await this.client.request({ path: ["pipeline"], body: Object.values(this.commands).map((c) => c.command), })) as UpstashResponse<any>[]; return res.map(({ error, result }, i) => { if (error) { throw new UpstashError( `Command ${i + 1} [ ${ this.commands[i].command[0] } ] failed: ${error}`, ); } return this.commands[i].deserialize(result); }) as TCommandResults; }; /** * Pushes a command into the pipelien and returns a chainable instance of the * pipeline */ private chain<T>(command: Command<any, T>): this { this.commands.push(command); return this; } /** * @see https://redis.io/commands/append */ append = (...args: CommandArgs<typeof AppendCommand>) => this.chain(new AppendCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/bitcount */ bitcount = (...args: CommandArgs<typeof BitCountCommand>) => this.chain(new BitCountCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/bitop */ bitop: { ( op: "and" | "or" | "xor", destinationKey: string, sourceKey: string, ...sourceKeys: string[] ): Pipeline; (op: "not", destinationKey: string, sourceKey: string): Pipeline; } = ( op: "and" | "or" | "xor" | "not", destinationKey: string, sourceKey: string, ...sourceKeys: string[] ): Pipeline => this.chain( new BitOpCommand( [op as any, destinationKey, sourceKey, ...sourceKeys], this.commandOptions, ), ); /** * @see https://redis.io/commands/bitpos */ bitpos = (...args: CommandArgs<typeof BitPosCommand>) => this.chain(new BitPosCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/dbsize */ dbsize = () => this.chain(new DBSizeCommand(this.commandOptions)); /** * @see https://redis.io/commands/decr */ decr = (...args: CommandArgs<typeof DecrCommand>) => this.chain(new DecrCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/decrby */ decrby = (...args: CommandArgs<typeof DecrByCommand>) => this.chain(new DecrByCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/del */ del = (...args: CommandArgs<typeof DelCommand>) => this.chain(new DelCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/echo */ echo = (...args: CommandArgs<typeof EchoCommand>) => this.chain(new EchoCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/eval */ eval = <TArgs extends unknown[], TData = unknown>( ...args: [script: string, keys: string[], args: TArgs] ) => this.chain(new EvalCommand<TArgs, TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/evalsha */ evalsha = <TArgs extends unknown[], TData = unknown>( ...args: [sha1: string, keys: string[], args: TArgs] ) => this.chain(new EvalshaCommand<TArgs, TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/exists */ exists = (...args: CommandArgs<typeof ExistsCommand>) => this.chain(new ExistsCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/expire */ expire = (...args: CommandArgs<typeof ExpireCommand>) => this.chain(new ExpireCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/expireat */ expireat = (...args: CommandArgs<typeof ExpireAtCommand>) => this.chain(new ExpireAtCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/flushall */ flushall = (args?: CommandArgs<typeof FlushAllCommand>) => this.chain(new FlushAllCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/flushdb */ flushdb = (...args: CommandArgs<typeof FlushDBCommand>) => this.chain(new FlushDBCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/get */ get = <TData>(...args: CommandArgs<typeof GetCommand>) => this.chain(new GetCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/getbit */ getbit = (...args: CommandArgs<typeof GetBitCommand>) => this.chain(new GetBitCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/getrange */ getrange = (...args: CommandArgs<typeof GetRangeCommand>) => this.chain(new GetRangeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/getset */ getset = <TData>(key: string, value: TData) => this.chain(new GetSetCommand<TData>([key, value], this.commandOptions)); /** * @see https://redis.io/commands/hdel */ hdel = (...args: CommandArgs<typeof HDelCommand>) => this.chain(new HDelCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hexists */ hexists = (...args: CommandArgs<typeof HExistsCommand>) => this.chain(new HExistsCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hget */ hget = <TData>(...args: CommandArgs<typeof HGetCommand>) => this.chain(new HGetCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/hgetall */ hgetall = <TData extends Record<string, unknown>>( ...args: CommandArgs<typeof HGetAllCommand> ) => this.chain(new HGetAllCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/hincrby */ hincrby = (...args: CommandArgs<typeof HIncrByCommand>) => this.chain(new HIncrByCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hincrbyfloat */ hincrbyfloat = (...args: CommandArgs<typeof HIncrByFloatCommand>) => this.chain(new HIncrByFloatCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hkeys */ hkeys = (...args: CommandArgs<typeof HKeysCommand>) => this.chain(new HKeysCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hlen */ hlen = (...args: CommandArgs<typeof HLenCommand>) => this.chain(new HLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hmget */ hmget = <TData extends Record<string, unknown>>( ...args: CommandArgs<typeof HMGetCommand> ) => this.chain(new HMGetCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/hmset */ hmset = <TData>(key: string, kv: { [field: string]: TData }) => this.chain(new HMSetCommand([key, kv], this.commandOptions)); /** * @see https://redis.io/commands/hscan */ hscan = (...args: CommandArgs<typeof HScanCommand>) => this.chain(new HScanCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hset */ hset = <TData>(key: string, kv: { [field: string]: TData }) => this.chain(new HSetCommand<TData>([key, kv], this.commandOptions)); /** * @see https://redis.io/commands/hsetnx */ hsetnx = <TData>(key: string, field: string, value: TData) => this.chain( new HSetNXCommand<TData>([key, field, value], this.commandOptions), ); /** * @see https://redis.io/commands/hstrlen */ hstrlen = (...args: CommandArgs<typeof HStrLenCommand>) => this.chain(new HStrLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hvals */ hvals = (...args: CommandArgs<typeof HValsCommand>) => this.chain(new HValsCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/incr */ incr = (...args: CommandArgs<typeof IncrCommand>) => this.chain(new IncrCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/incrby */ incrby = (...args: CommandArgs<typeof IncrByCommand>) => this.chain(new IncrByCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/incrbyfloat */ incrbyfloat = (...args: CommandArgs<typeof IncrByFloatCommand>) => this.chain(new IncrByFloatCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/keys */ keys = (...args: CommandArgs<typeof KeysCommand>) => this.chain(new KeysCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lindex */ lindex = (...args: CommandArgs<typeof LIndexCommand>) => this.chain(new LIndexCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/linsert */ linsert = <TData>( key: string, direction: "before" | "after", pivot: TData, value: TData, ): Pipeline => this.chain( new LInsertCommand<TData>( [key, direction, pivot, value], this.commandOptions, ), ); /** * @see https://redis.io/commands/llen */ llen = (...args: CommandArgs<typeof LLenCommand>) => this.chain(new LLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lpop */ lpop = <TData>(...args: CommandArgs<typeof LPopCommand>) => this.chain(new LPopCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/lpush */ lpush = <TData>(key: string, ...elements: TData[]) => this.chain( new LPushCommand<TData>([key, ...elements], this.commandOptions), ); /** * @see https://redis.io/commands/lpushx */ lpushx = <TData>(key: string, ...elements: TData[]) => this.chain( new LPushXCommand<TData>([key, ...elements], this.commandOptions), ); /** * @see https://redis.io/commands/lrange */ lrange = <TResult = string>(...args: CommandArgs<typeof LRangeCommand>) => this.chain(new LRangeCommand<TResult>(args, this.commandOptions)); /** * @see https://redis.io/commands/lrem */ lrem = <TData>(key: string, count: number, value: TData) => this.chain(new LRemCommand([key, count, value], this.commandOptions)); /** * @see https://redis.io/commands/lset */ lset = <TData>(key: string, index: number, value: TData) => this.chain(new LSetCommand([key, index, value], this.commandOptions)); /** * @see https://redis.io/commands/ltrim */ ltrim = (...args: CommandArgs<typeof LTrimCommand>) => this.chain(new LTrimCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/mget */ mget = <TData extends unknown[]>(...args: CommandArgs<typeof MGetCommand>) => this.chain(new MGetCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/mset */ mset = <TData>(kv: { [key: string]: TData }) => this.chain(new MSetCommand<TData>([kv], this.commandOptions)); /** * @see https://redis.io/commands/msetnx */ msetnx = <TData>(kv: { [key: string]: TData }) => this.chain(new MSetNXCommand<TData>([kv], this.commandOptions)); /** * @see https://redis.io/commands/persist */ persist = (...args: CommandArgs<typeof PersistCommand>) => this.chain(new PersistCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/pexpire */ pexpire = (...args: CommandArgs<typeof PExpireCommand>) => this.chain(new PExpireCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/pexpireat */ pexpireat = (...args: CommandArgs<typeof PExpireAtCommand>) => this.chain(new PExpireAtCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/ping */ ping = (args?: CommandArgs<typeof PingCommand>) => this.chain(new PingCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/psetex */ psetex = <TData>(key: string, ttl: number, value: TData) => this.chain( new PSetEXCommand<TData>([key, ttl, value], this.commandOptions), ); /** * @see https://redis.io/commands/pttl */ pttl = (...args: CommandArgs<typeof PTtlCommand>) => this.chain(new PTtlCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/publish */ publish = (...args: CommandArgs<typeof PublishCommand>) => this.chain(new PublishCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/randomkey */ randomkey = () => this.chain(new RandomKeyCommand(this.commandOptions)); /** * @see https://redis.io/commands/rename */ rename = (...args: CommandArgs<typeof RenameCommand>) => this.chain(new RenameCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/renamenx */ renamenx = (...args: CommandArgs<typeof RenameNXCommand>) => this.chain(new RenameNXCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/rpop */ rpop = <TData = string>(...args: CommandArgs<typeof RPopCommand>) => this.chain(new RPopCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/rpush */ rpush = <TData>(key: string, ...elements: TData[]) => this.chain(new RPushCommand([key, ...elements], this.commandOptions)); /** * @see https://redis.io/commands/rpushx */ rpushx = <TData>(key: string, ...elements: TData[]) => this.chain(new RPushXCommand([key, ...elements], this.commandOptions)); /** * @see https://redis.io/commands/sadd */ sadd = <TData>(key: string, ...members: TData[]) => this.chain(new SAddCommand<TData>([key, ...members], this.commandOptions)); /** * @see https://redis.io/commands/scan */ scan = (...args: CommandArgs<typeof ScanCommand>) => this.chain(new ScanCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/scard */ scard = (...args: CommandArgs<typeof SCardCommand>) => this.chain(new SCardCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/script-exists */ scriptExists = (...args: CommandArgs<typeof ScriptExistsCommand>) => this.chain(new ScriptExistsCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/script-flush */ scriptFlush = (...args: CommandArgs<typeof ScriptFlushCommand>) => this.chain(new ScriptFlushCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/script-load */ scriptLoad = (...args: CommandArgs<typeof ScriptLoadCommand>) => this.chain(new ScriptLoadCommand(args, this.commandOptions)); /*)* * @see https://redis.io/commands/sdiff */ sdiff = (...args: CommandArgs<typeof SDiffCommand>) => this.chain(new SDiffCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sdiffstore */ sdiffstore = (...args: CommandArgs<typeof SDiffStoreCommand>) => this.chain(new SDiffStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/set */ set = <TData>(key: string, value: TData, opts?: SetCommandOptions) => this.chain(new SetCommand<TData>([key, value, opts], this.commandOptions)); /** * @see https://redis.io/commands/setbit */ setbit = (...args: CommandArgs<typeof SetBitCommand>) => this.chain(new SetBitCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/setex */ setex = <TData>(key: string, ttl: number, value: TData) => this.chain(new SetExCommand<TData>([key, ttl, value], this.commandOptions)); /** * @see https://redis.io/commands/setnx */ setnx = <TData>(key: string, value: TData) => this.chain(new SetNxCommand<TData>([key, value], this.commandOptions)); /** * @see https://redis.io/commands/setrange */ setrange = (...args: CommandArgs<typeof SetRangeCommand>) => this.chain(new SetRangeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sinter */ sinter = (...args: CommandArgs<typeof SInterCommand>) => this.chain(new SInterCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sinterstore */ sinterstore = (...args: CommandArgs<typeof SInterStoreCommand>) => this.chain(new SInterStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sismember */ sismember = <TData>(key: string, member: TData) => this.chain(new SIsMemberCommand<TData>([key, member], this.commandOptions)); /** * @see https://redis.io/commands/smembers */ smembers = (...args: CommandArgs<typeof SMembersCommand>) => this.chain(new SMembersCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/smove */ smove = <TData>(source: string, destination: string, member: TData) => this.chain( new SMoveCommand<TData>( [source, destination, member], this.commandOptions, ), ); /** * @see https://redis.io/commands/spop */ spop = <TData>(...args: CommandArgs<typeof SPopCommand>) => this.chain(new SPopCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/srandmember */ srandmember = <TData>(...args: CommandArgs<typeof SRandMemberCommand>) => this.chain(new SRandMemberCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/srem */ srem = <TData>(key: string, ...members: TData[]) => this.chain(new SRemCommand<TData>([key, ...members], this.commandOptions)); /** * @see https://redis.io/commands/sscan */ sscan = (...args: CommandArgs<typeof SScanCommand>) => this.chain(new SScanCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/strlen */ strlen = (...args: CommandArgs<typeof StrLenCommand>) => this.chain(new StrLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sunion */ sunion = (...args: CommandArgs<typeof SUnionCommand>) => this.chain(new SUnionCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sunionstore */ sunionstore = (...args: CommandArgs<typeof SUnionStoreCommand>) => this.chain(new SUnionStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/time */ time = () => this.chain(new TimeCommand(this.commandOptions)); /** * @see https://redis.io/commands/touch */ touch = (...args: CommandArgs<typeof TouchCommand>) => this.chain(new TouchCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/ttl */ ttl = (...args: CommandArgs<typeof TtlCommand>) => this.chain(new TtlCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/type */ type = (...args: CommandArgs<typeof TypeCommand>) => this.chain(new TypeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/unlink */ unlink = (...args: CommandArgs<typeof UnlinkCommand>) => this.chain(new UnlinkCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zadd */ zadd = <TData>( ...args: | [ key: string, scoreMember: ScoreMember<TData>, ...scoreMemberPairs: ScoreMember<TData>[], ] | [ key: string, opts: ZAddCommandOptions | ZAddCommandOptionsWithIncr, ...scoreMemberPairs: [ScoreMember<TData>, ...ScoreMember<TData>[]], ] ) => { if ("score" in args[1]) { return this.chain( new ZAddCommand<TData>( [args[0], args[1] as ScoreMember<TData>, ...(args.slice(2) as any)], this.commandOptions, ), ); } return this.chain( new ZAddCommand<TData>( [args[0], args[1] as any, ...(args.slice(2) as any)], this.commandOptions, ), ); }; /** * @see https://redis.io/commands/zcard */ zcard = (...args: CommandArgs<typeof ZCardCommand>) => this.chain(new ZCardCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zcount */ zcount = (...args: CommandArgs<typeof ZCountCommand>) => this.chain(new ZCountCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zincrby */ zincrby = <TData>(key: string, increment: number, member: TData) => this.chain( new ZIncrByCommand<TData>([key, increment, member], this.commandOptions), ); /** * @see https://redis.io/commands/zinterstore */ zinterstore = (...args: CommandArgs<typeof ZInterStoreCommand>) => this.chain(new ZInterStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zlexcount */ zlexcount = (...args: CommandArgs<typeof ZLexCountCommand>) => this.chain(new ZLexCountCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zpopmax */ zpopmax = <TData>(...args: CommandArgs<typeof ZPopMaxCommand>) => this.chain(new ZPopMaxCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/zpopmin */ zpopmin = <TData>(...args: CommandArgs<typeof ZPopMinCommand>) => this.chain(new ZPopMinCommand<TData>(args, this.commandOptions)); /** * @see https://redis.io/commands/zrange */ zrange = <TData extends unknown[]>( ...args: | [key: string, min: number, max: number, opts?: ZRangeCommandOptions] | [ key: string, min: `(${string}` | `[${string}` | "-" | "+", max: `(${string}` | `[${string}` | "-" | "+", opts: { byLex: true } & ZRangeCommandOptions, ] | [ key: string, min: number | `(${number}` | "-inf" | "+inf", max: number | `(${number}` | "-inf" | "+inf", opts: { byScore: true } & ZRangeCommandOptions, ] ) => this.chain(new ZRangeCommand<TData>(args as any, this.commandOptions)); /** * @see https://redis.io/commands/zrank */ zrank = <TData>(key: string, member: TData) => this.chain(new ZRankCommand<TData>([key, member], this.commandOptions)); /** * @see https://redis.io/commands/zrem */ zrem = <TData>(key: string, ...members: TData[]) => this.chain(new ZRemCommand<TData>([key, ...members], this.commandOptions)); /** * @see https://redis.io/commands/zremrangebylex */ zremrangebylex = (...args: CommandArgs<typeof ZRemRangeByLexCommand>) => this.chain(new ZRemRangeByLexCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zremrangebyrank */ zremrangebyrank = (...args: CommandArgs<typeof ZRemRangeByRankCommand>) => this.chain(new ZRemRangeByRankCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zremrangebyscore */ zremrangebyscore = (...args: CommandArgs<typeof ZRemRangeByScoreCommand>) => this.chain(new ZRemRangeByScoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zrevrank */ zrevrank = <TData>(key: string, member: TData) => this.chain(new ZRevRankCommand<TData>([key, member], this.commandOptions)); /** * @see https://redis.io/commands/zscan */ zscan = (...args: CommandArgs<typeof ZScanCommand>) => this.chain(new ZScanCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zscore */ zscore = <TData>(key: string, member: TData) => this.chain(new ZScoreCommand<TData>([key, member], this.commandOptions)); /** * @see https://redis.io/commands/zunionstore */ zunionstore = (...args: CommandArgs<typeof ZUnionStoreCommand>) => this.chain(new ZUnionStoreCommand(args, this.commandOptions)); }
the_stack
import type * as dfd from 'danfojs-node'; import { sendMessage } from '../comms'; import { v4 as uuid } from 'uuid'; function generatePlot(data, config, eleId: string) { const parentId = uuid().replace(/-/g, ''); const html = ` <script src="https://cdn.plot.ly/plotly-2.3.0.min.js"></script> <div id="${parentId}"></div> <script type="text/javascript"> function plotIt${parentId}(){ if (!window.Plotly){ plotIt${parentId}._tryCount += 1; if (plotIt${parentId}._tryCount === 120){ return console.error('Failed to load plotly in 120s'); } console.info('Plotly not yet ready, retrying'); return setTimeout(plotIt${parentId}, 500); } const ele = document.getElementById("${eleId || parentId}") || document.getElementById("${parentId}"); console.info('Plotly is ready, plotting'); window.Plotly.newPlot( ele, ${JSON.stringify(data)}, ${JSON.stringify(config['layout'])}, ${JSON.stringify(config)} ); } plotIt${parentId}._tryCount = 0; plotIt${parentId}(); </script> `; sendMessage({ type: 'output', requestId: DanfoNodePlotter.requestId, data: { type: 'html', value: html, requestId: DanfoNodePlotter.requestId } }); } export class DanfoNodePlotter { public static requestId: string = ''; constructor(private readonly ndframe, private readonly danfojs: typeof dfd, private readonly div: string = '') {} line(config = {}) { const ret_params = this.__get_plot_params(config); const this_config = ret_params[0]; // eslint-disable-next-line @typescript-eslint/no-explicit-any const params = ret_params[1] as string[]; if (this.ndframe instanceof this.danfojs.Series) { const trace = {}; const y = this.ndframe.values; params.forEach((param) => { // if (!param === 'layout') { if (param !== 'layout') { trace[param] = config[param]; } }); trace['y'] = y; trace['type'] = 'line'; generatePlot([trace], this_config, this.div); } else { if ('x' in this_config && 'y' in this_config) { if (!this.ndframe.column_names.includes(this_config['x'])) { throw Error(`Column Error: ${this_config['x']} not found in columns`); } if (!this.ndframe.column_names.includes(this_config['y'])) { throw Error(`Column Error: ${this_config['y']} not found in columns`); } const x = this.ndframe[this_config['x']].values; const y = this.ndframe[this_config['y']].values; const trace = {}; trace['x'] = x; trace['y'] = y; const xaxis = {}; const yaxis = {}; xaxis['title'] = this_config['x']; yaxis['title'] = this_config['y']; this_config['layout']['xaxis'] = xaxis; this_config['layout']['yaxis'] = yaxis; generatePlot([trace], this_config, this.div); } else if ('x' in this_config || 'y' in this_config) { const data: any[] = []; let cols_to_plot; if ('columns' in this_config) { cols_to_plot = this.____check_if_cols_exist(this_config['columns']); } else { cols_to_plot = this.ndframe.column_names; } cols_to_plot.forEach((c_name) => { const trace = {}; params.forEach((param) => { trace[param] = config[param]; }); if ('x' in this_config) { trace['x'] = this.ndframe[this_config['x']].values; trace['y'] = this.ndframe[c_name].values; trace['name'] = c_name; } else { trace['y'] = this.ndframe[this_config['y']].values; trace['x'] = this.ndframe[c_name].values; trace['name'] = c_name; } data.push(trace); }); generatePlot(data, this_config, this.div); } else { const data: any[] = []; let cols_to_plot; if ('columns' in this_config) { cols_to_plot = this.____check_if_cols_exist(this_config['columns']); } else { cols_to_plot = this.ndframe.column_names; } cols_to_plot.forEach((c_name) => { const trace = {}; params.forEach((param) => { trace[param] = config[param]; }); trace['x'] = this.ndframe.index; trace['y'] = this.ndframe[c_name].values; trace['name'] = c_name; data.push(trace); }); generatePlot(data, this_config, this.div); } } } bar(config = {}) { const ret_params = this.__get_plot_params(config); const this_config = ret_params[0]; const params = ret_params[1] as any; if (this.ndframe instanceof this.danfojs.Series) { const trace = {}; const y = this.ndframe.values; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); trace['y'] = y; trace['type'] = 'bar'; generatePlot([trace], this_config, this.div); } else { if ('x' in this_config && 'y' in this_config) { if (!this.ndframe.column_names.includes(this_config['x'])) { throw Error(`Column Error: ${this_config['x']} not found in columns`); } if (!this.ndframe.column_names.includes(this_config['y'])) { throw Error(`Column Error: ${this_config['y']} not found in columns`); } const x = this.ndframe[this_config['x']].values; const y = this.ndframe[this_config['y']].values; const trace = {}; trace['x'] = x; trace['y'] = y; trace['type'] = 'bar'; const xaxis = {}; const yaxis = {}; xaxis['title'] = this_config['x']; yaxis['title'] = this_config['y']; this_config['layout']['xaxis'] = xaxis; this_config['layout']['yaxis'] = yaxis; generatePlot([trace], this_config, this.div); } else if ('x' in this_config || 'y' in this_config) { const trace = {}; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); if ('x' in this_config) { trace['y'] = this.ndframe[this_config['x']].values; } else { trace['y'] = this.ndframe[this_config['y']].values; } trace['type'] = 'bar'; generatePlot([trace], this_config, this.div); } else { const data: any[] = []; let cols_to_plot; if ('columns' in this_config) { cols_to_plot = this.____check_if_cols_exist(this_config['columns']); } else { cols_to_plot = this.ndframe.column_names; } cols_to_plot.forEach((c_name) => { const trace = {}; trace['x'] = this.ndframe.index; trace['y'] = this.ndframe[c_name].values; trace['name'] = c_name; trace['type'] = 'bar'; data.push(trace); }); generatePlot(data, this_config, this.div); } } } scatter(config = {}) { const ret_params = this.__get_plot_params(config); const this_config = ret_params[0]; // eslint-disable-next-line @typescript-eslint/no-explicit-any const params = ret_params[1] as any; if (this.ndframe instanceof this.danfojs.Series) { const trace = {}; params.forEach((param) => { // if (!param == 'layout') { if (param !== 'layout') { trace[param] = config[param]; } }); trace['x'] = this.ndframe.values; trace['y'] = this.ndframe.index; trace['type'] = 'scatter'; trace['mode'] = 'markers'; generatePlot([trace], this_config, this.div); } else { if ('x' in this_config && 'y' in this_config) { if (!this.ndframe.column_names.includes(this_config['x'])) { throw Error(`Column Error: ${this_config['x']} not found in columns`); } if (!this.ndframe.column_names.includes(this_config['y'])) { throw Error(`Column Error: ${this_config['y']} not found in columns`); } const x = this.ndframe[this_config['x']].values; const y = this.ndframe[this_config['y']].values; const trace = {}; trace['x'] = x; trace['y'] = y; trace['type'] = 'scatter'; trace['mode'] = 'markers'; const xaxis = {}; const yaxis = {}; xaxis['title'] = this_config['x']; yaxis['title'] = this_config['y']; this_config['layout']['xaxis'] = xaxis; this_config['layout']['yaxis'] = yaxis; generatePlot([trace], this_config, this.div); } else if ('x' in this_config || 'y' in this_config) { const trace = {}; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); if ('x' in this_config) { trace['y'] = this.ndframe.index; trace['x'] = this.ndframe[this_config['x']].values; } else { trace['x'] = this.ndframe.index; trace['y'] = this.ndframe[this_config['y']].values; } trace['type'] = 'scatter'; trace['mode'] = 'markers'; generatePlot([trace], this_config, this.div); } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any const data: any[] = []; let cols_to_plot; if ('columns' in this_config) { cols_to_plot = this.____check_if_cols_exist(this_config['columns']); } else { cols_to_plot = this.ndframe.column_names; } cols_to_plot.forEach((c_name) => { const trace = {}; trace['y'] = this.ndframe.index; trace['x'] = this.ndframe[c_name].values; trace['name'] = c_name; trace['type'] = 'scatter'; trace['mode'] = 'markers'; data.push(trace); }); generatePlot(data, this_config, this.div); } } } hist(config = {}) { const ret_params = this.__get_plot_params(config); const this_config = ret_params[0]; const params = ret_params[1] as any; if (this.ndframe instanceof this.danfojs.Series) { const trace = {}; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); trace['x'] = this.ndframe.values; trace['type'] = 'histogram'; generatePlot([trace], this_config, this.div); } else if ('x' in this_config) { const trace = {}; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); trace['x'] = this.ndframe[this_config['y']].values; trace['type'] = 'histogram'; generatePlot([trace], this_config, this.div); } else if ('y' in this_config) { const trace = {}; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); trace['y'] = this.ndframe[this_config['y']].values; trace['type'] = 'histogram'; generatePlot([trace], this_config, this.div); } else { const data: any[] = []; let cols_to_plot; if ('columns' in this_config) { cols_to_plot = this.____check_if_cols_exist(this_config['columns']); } else { cols_to_plot = this.ndframe.column_names; } cols_to_plot.forEach((c_name) => { const trace = {}; trace['x'] = this.ndframe[c_name].values; trace['name'] = c_name; trace['type'] = 'histogram'; data.push(trace); }); generatePlot(data, this_config, this.div); } } pie(config = {}) { const ret_params = this.__get_plot_params(config); const this_config = ret_params[0]; if (this.ndframe instanceof this.danfojs.Series) { const data = [ { values: this.ndframe.values, labels: this.ndframe.index, type: 'pie', name: this_config['labels'], hoverinfo: 'label+percent+name', automargin: true } ]; generatePlot(data, this_config, this.div); } else if ('values' in this_config && 'labels' in this_config) { if (!this.ndframe.column_names.includes(this_config['labels'])) { throw Error( `Column Error: ${this_config['labels']} not found in columns. labels name must be one of [ ${this.ndframe.column_names}]` ); } if (!this.ndframe.column_names.includes(this_config['values'])) { throw Error( `Column Error: ${this_config['values']} not found in columns. value name must be one of [ ${this.ndframe.column_names}]` ); } const data = [ { values: this.ndframe[this_config['values']].values, labels: this.ndframe[this_config['labels']].values, type: 'pie', name: this_config['labels'], hoverinfo: 'label+percent+name', automargin: true } ]; generatePlot(data, this_config, this.div); } else { let cols_to_plot; if ('columns' in this_config) { cols_to_plot = this.____check_if_cols_exist(this_config['columns']); } else { cols_to_plot = this.ndframe.column_names; } if ('row_pos' in this_config) { if (this_config['row_pos'].length != cols_to_plot.length - 1) { throw Error( `Lenght of row_pos array must be equal to number of columns. Got ${ this_config['row_pos'].length }, expected ${cols_to_plot.length - 1}` ); } } else { const temp_arr: any[] = []; for (let i = 0; i < cols_to_plot.length - 1; i++) { temp_arr.push(0); } this_config['row_pos'] = temp_arr; } if ('col_pos' in this_config) { if (this_config['col_pos'].length != cols_to_plot.length - 1) { throw Error( `Lenght of col_pos array must be equal to number of columns. Got ${ this_config['col_pos'].length }, expected ${cols_to_plot.length - 1}` ); } } else { const temp_arr: any = []; for (let i = 0; i < cols_to_plot.length - 1; i++) { temp_arr.push(i); } this_config['col_pos'] = temp_arr; } const data: any[] = []; cols_to_plot.forEach((c_name, i) => { const trace = {}; trace['values'] = this.ndframe[c_name].values; trace['labels'] = this.ndframe[this_config['labels']].values; trace['name'] = c_name; trace['type'] = 'pie'; trace['domain'] = { row: this_config['row_pos'][i], column: this_config['col_pos'][i] }; trace['hoverinfo'] = 'label+percent+name'; trace['textposition'] = 'outside'; trace['automargin'] = true; data.push(trace); }); if (!('grid' in this_config)) { const size = Number((this.ndframe.shape[1] / 2).toFixed()) + 1; this_config['grid'] = { rows: size, columns: size }; } this_config['layout']['grid'] = this_config['grid']; generatePlot(data, this_config, this.div); } } box(config = {}) { const ret_params = this.__get_plot_params(config); const this_config = ret_params[0]; // eslint-disable-next-line @typescript-eslint/no-explicit-any const params = ret_params[1] as any[]; if (this.ndframe instanceof this.danfojs.Series) { const trace = {}; const y = this.ndframe.values; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); trace['y'] = y; trace['type'] = 'box'; generatePlot([trace], this_config, this.div); } else { if ('x' in this_config && 'y' in this_config) { if (!this.ndframe.column_names.includes(this_config['x'])) { throw Error(`Column Error: ${this_config['x']} not found in columns`); } if (!this.ndframe.column_names.includes(this_config['y'])) { throw Error(`Column Error: ${this_config['y']} not found in columns`); } const x = this.ndframe[this_config['x']].values; const y = this.ndframe[this_config['y']].values; const trace = {}; trace['x'] = x; trace['y'] = y; trace['type'] = 'box'; const xaxis = {}; const yaxis = {}; xaxis['title'] = this_config['x']; yaxis['title'] = this_config['y']; this_config['layout']['xaxis'] = xaxis; this_config['layout']['yaxis'] = yaxis; generatePlot([trace], this_config, this.div); } else if ('x' in this_config || 'y' in this_config) { const trace = {}; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); if ('x' in this_config) { trace['x'] = this.ndframe[this_config['x']].values; trace['y'] = this.ndframe.index; trace['type'] = 'box'; } else { trace['x'] = this.ndframe.index; trace['y'] = this_config['y']; trace['type'] = 'box'; } generatePlot([trace], this_config, this.div); } else { const data: any[] = []; let cols_to_plot; if ('columns' in this_config) { cols_to_plot = this.____check_if_cols_exist(this_config['columns']); } else { cols_to_plot = this.ndframe.column_names; } cols_to_plot.forEach((c_name) => { const trace = {}; params.forEach((param) => { trace[param] = config[param]; }); trace['y'] = this.ndframe[c_name].values; trace['name'] = c_name; trace['type'] = 'box'; data.push(trace); }); generatePlot(data, this_config, this.div); } } } violin(config = {}) { const ret_params = this.__get_plot_params(config); const this_config = ret_params[0]; // eslint-disable-next-line @typescript-eslint/no-explicit-any const params = ret_params[1] as any[]; if (this.ndframe instanceof this.danfojs.Series) { const trace = {}; const y = this.ndframe.values; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); trace['y'] = y; trace['type'] = 'violin'; generatePlot([trace], this_config, this.div); } else { if ('x' in this_config && 'y' in this_config) { if (!this.ndframe.column_names.includes(this_config['x'])) { throw Error(`Column Error: ${this_config['x']} not found in columns`); } if (!this.ndframe.column_names.includes(this_config['y'])) { throw Error(`Column Error: ${this_config['y']} not found in columns`); } const x = this.ndframe[this_config['x']].values; const y = this.ndframe[this_config['y']].values; const trace = {}; trace['x'] = x; trace['y'] = y; trace['type'] = 'violin'; const xaxis = {}; const yaxis = {}; xaxis['title'] = this_config['x']; yaxis['title'] = this_config['y']; this_config['layout']['xaxis'] = xaxis; this_config['layout']['yaxis'] = yaxis; generatePlot([trace], this_config, this.div); } else if ('x' in this_config || 'y' in this_config) { const trace = {}; params.forEach((param) => { if (param !== 'layout') { trace[param] = config[param]; } }); if ('x' in this_config) { trace['x'] = this.ndframe[this_config['x']].values; trace['y'] = this.ndframe.index; trace['type'] = 'violin'; } else { trace['x'] = this.ndframe.index; trace['y'] = this_config['y']; trace['type'] = 'violin'; } generatePlot([trace], this_config, this.div); } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any const data: any[] = []; let cols_to_plot; if ('columns' in this_config) { cols_to_plot = this.____check_if_cols_exist(this_config['columns']); } else { cols_to_plot = this.ndframe.column_names; } cols_to_plot.forEach((c_name) => { const trace = {}; params.forEach((param) => { trace[param] = config[param]; }); trace['y'] = this.ndframe[c_name].values; trace['name'] = c_name; trace['type'] = 'violin'; data.push(trace); }); generatePlot(data, this_config, this.div); } } } table(config = {}) { const ret_params = this.__get_plot_params(config); const this_config = ret_params[0]; const header = {}; const cells = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any let cols_data: any[] = []; let cols_2_show; if ('columns' in this_config) { this_config['columns'].forEach((cname) => { if (!this.ndframe.column_names.includes(cname)) { throw Error( `Column Error: ${cname} not found in columns. Columns should be one of [ ${this.ndframe.column_names} ]` ); } const idx = this.ndframe.column_names.indexOf(cname); cols_data.push(this.ndframe.col_data[idx]); }); cols_2_show = this_config['columns']; } else { cols_2_show = this.ndframe.column_names; cols_data = this.ndframe.col_data; } header['values'] = cols_2_show; cells['values'] = cols_data; if (this_config['header_style']) { Object.keys(this_config['header_style']).forEach((param) => { header[param] = this_config['header_style'][param]; }); } if (this_config['cell_style']) { Object.keys(this_config['cell_style']).forEach((param) => { cells[param] = this_config['cell_style'][param]; }); } const data = [ { type: 'table', header: header, cells: cells } ]; generatePlot(data, this_config, this.div); } __get_plot_params(config) { const params = Object.keys(config); const this_config = {}; params.forEach((param) => { this_config[param] = config[param]; }); if (!('layout' in config)) { this_config['layout'] = {}; } return [this_config, params]; } ____check_if_cols_exist(cols) { cols.forEach((col) => { if (!this.ndframe.column_names.includes(col)) { throw Error( `Column Error: ${col} not found in columns. Columns should be one of [ ${this.ndframe.column_names} ]` ); } }); return cols; } }
the_stack
import * as ui from "../../ui"; import * as React from "react"; import * as ReactDOM from "react-dom"; import * as tab from "./tab"; import * as tabRegistry from "./tabRegistry"; import * as commands from "../../commands/commands"; import * as utils from "../../../common/utils"; import * as csx from '../../base/csx'; import {createId} from "../../../common/utils"; import * as types from "../../../common/types"; import {connect} from "react-redux"; import * as styles from "../../styles/styles"; import {Tips} from "./../tips"; import {Icon} from "../../components/icon"; import {cast, server} from "../../../socket/socketClient"; import {Types} from "../../../socket/socketContract"; import * as alertOnLeave from "../../utils/alertOnLeave"; import {getSessionId, setSessionId} from "../../state/clientSession"; import * as onresize from "onresize"; import {TypedEvent} from "../../../common/events"; import {CodeEditor} from "../../monaco/editor/codeEditor"; import * as state from "../../state/state"; import * as pure from "../../../common/pure"; import * as settings from "../../state/settings"; import {errorsCache} from "../../globalErrorCacheClient"; /** * Singleton + tab state migrated from redux to the local component * This is because the component isn't very react friendly */ declare var _helpMeGrabTheType: AppTabsContainer; export let tabState: typeof _helpMeGrabTheType.tabState; export type TabInstance = types.TabInstance; /** * * Golden layout * */ import * as GoldenLayout from "golden-layout"; require('golden-layout/src/css/goldenlayout-base.css'); require('golden-layout/src/css/goldenlayout-dark-theme.css'); /** Golden layout wants react / react-dom to be global */ (window as any).React = React; (window as any).ReactDOM = ReactDOM; /** Golden layout injects this prop into all react components */ interface GLProps extends React.Props<any>{ /** https://golden-layout.com/docs/Container.html */ glContainer: { setTitle:(title:string)=>any; } } /** Some additional styles */ require('./appTabsContainer.css') export interface Props { } export interface State { } export class AppTabsContainer extends ui.BaseComponent<Props, State>{ /** The Golden Layout */ layout: GoldenLayout; constructor(props: Props) { super(props); /** Setup the singleton */ tabState = this.tabState; } componentDidMount() { server.getOpenUITabs({ sessionId: getSessionId() }).then(res => { const config = GLUtil.unserializeConfig(res.tabLayout, this); /** This is needed as we use this ordered information in quite a few places */ this.tabs = GLUtil.orderedTabs(config); /** * Setup golden layout * https://golden-layout.com/docs/Config.html */ this.layout = new GoldenLayout(config, this.ctrls.root); /** * Register all the tab components with layout */ tabRegistry.getTabConfigs().forEach(({protocol, config}) => { this.layout.registerComponent(protocol, config.component); }); /** Setup window resize */ this.disposible.add(onresize.on(() => this.tabState.resize())); /** * Tab selection * I tried to use the config to figure out the selected tab. * That didn't work out so well * So the plan is to intercept the tab clicks to focus * and on state changes just focus on the last selected tab if any */ (this.layout as any).on('tabCreated', (tabInfo) => { this.createTabHandle(tabInfo); }); (this.layout as any).on('itemDestroyed', (evt) => { if (evt.config && evt.config.id){ this.tabState.tabClosedInLayout(evt.config.id); } }); let oldConfig = config; let initialStateChange = true; (this.layout as any).on('stateChanged', (evt) => { if (initialStateChange) { // Select the last tab this.tabs.length && res.selectedTabId && this.tabs.find(t=>t.id === res.selectedTabId) && tabState.triggerFocusAndSetAsSelected(res.selectedTabId); initialStateChange = false; } const newConfig = this.layout.toConfig(); /** * `golden-layout` plugs into the `componentWillUpdate` on our tab components * If any tab component state changes it calls us with `stateChanged` * These are not relevant for us so we use our super special diff to ignore these cases * * This diff can be improved (its too strict) */ type SimpleContentItem = { type: string, dimension: any, content?: SimpleContentItem[], activeItemIndex?: number, width?: number; height?: number } const contentEqual = (a: SimpleContentItem, b: SimpleContentItem) => { if (a.type !== b.type) return false; if (a.activeItemIndex !== b.activeItemIndex) return false; if (!pure.shallowEqual(a.dimension, b.dimension)) return false; if (a.height !== b.height) return false; if (a.width !== b.width) return false; if (a.content) { if (!b.content) return false; if (a.content.length !== b.content.length) return false; return a.content.every((c, i) => contentEqual(c, b.content[i])); } return true; } const equal = contentEqual(oldConfig, newConfig); oldConfig = newConfig; if (equal) { return; } // Due to state changes layout needs to happen on *all tabs* (because it might expose some other tabs) // PREF : you can go thorough all the `stack` in the layout and only call resize on the active ones. this.tabState.resizeTheTabs(); // Ignore the events where the user is dragging stuff // This is because at this time the `config` doesn't contain the *dragged* item. const orderedtabs = GLUtil.orderedTabs(newConfig); if (orderedtabs.length !== this.tabs.length) { return; } // Store the tabs in the right order this.tabState.setTabs(orderedtabs); // If there was a selected tab focus on it again. if (this.tabState._resizingDontReFocus) { this.tabState._resizingDontReFocus = false; } else { this.selectedTabInstance && this.tabState.selectTab(this.selectedTabInstance.id); } }); // initialize the layout this.layout.init(); // If there are no tabs then show the tip help if (!this.tabs.length) this.tabState.refreshTipHelp(); /** * General command handling */ this.setupCommandHandling() }); } /** Used to undo close tab */ closedTabs: TabInstance[] = []; /** * Lots of commands are raised in the app that we need to care about * e.g. tab saving / tab switching / file opening etc. * We do that all in here */ setupCommandHandling(){ // commands.bas.on((e) => { // const filePath = getCurrentFilePathOrWarn(); // if (!filePath) return; // server.gitDiff({ filePath }).then(res => { // console.log(res); // }); // }); commands.saveTab.on((e) => { this.getSelectedTabApiIfAny().save.emit({}); }); commands.esc.on(() => { // Focus selected tab this.tabState.focusSelectedTabIfAny(); // Exit jump tab mode this.tabState.hideTabIndexes(); // Hide search if (this.tabApi[this.selectedTabInstance && this.selectedTabInstance.id]){ this.tabApi[this.selectedTabInstance && this.selectedTabInstance.id].search.hideSearch.emit({}); } }); commands.jumpToTab.on(()=>{ // jump to tab this.tabState.showTabIndexes(); }); /** * File opening commands */ commands.toggleOutputJS.on(()=>{ const filePath = getCurrentFilePathOrWarn(); if (!filePath) return; const outputStatus = state.getState().outputStatusCache[filePath]; if (!outputStatus) { ui.notifyWarningNormalDisappear('Your current tab needs to be a TypeScript file in project and project should have compileOnSave enabled'); return; } commands.doToggleFileTab.emit({ filePath: outputStatus.outputFilePath }); }); commands.doToggleFileTab.on(({filePath}) => { // If tab is open we just close it const existing = this.tabs.find(t => { return utils.getFilePathFromUrl(t.url) == filePath; }); if (existing) { this.tabState.closeTabById(existing.id); return; } // Othewise we open the tab, and select back to the current tab const currentTabId = this.selectedTabInstance && this.selectedTabInstance.id; commands.doOpenOrActivateFileTab.emit({ filePath }); this.moveCurrentTabRightIfAny(); if (currentTabId) { this.tabState.triggerFocusAndSetAsSelected(currentTabId) } }); commands.doOpenFile.on((e) => { let codeTab: TabInstance = { id: createId(), url: `file://${e.filePath}`, additionalData: null, } // Add tab this.addTabToLayout(codeTab); // Focus this.tabState.selectTab(codeTab.id); if (e.position) { this.tabApi[codeTab.id].gotoPosition.emit(e.position); } }); commands.doOpenOrFocusFile.on((e)=>{ // if open and not focused then focus and goto pos const existingTab = // Open and current ( this.selectedTabInstance && utils.getFilePathFromUrl(this.selectedTabInstance.url) === e.filePath && utils.getFilePathAndProtocolFromUrl(this.selectedTabInstance.url).protocol === tabRegistry.tabs.file.protocol && this.selectedTabInstance ) // Open but not current || this.tabs.find(t => { return utils.getFilePathFromUrl(t.url) == e.filePath && utils.getFilePathAndProtocolFromUrl(t.url).protocol === tabRegistry.tabs.file.protocol; }); if (existingTab) { // Focus if not focused if (!this.selectedTabInstance || this.selectedTabInstance.id !== existingTab.id) { this.tabState.triggerFocusAndSetAsSelected(existingTab.id); } if (e.position) { this.tabState.gotoPosition(existingTab.id, e.position); } } else { commands.doOpenFile.emit(e); } }); commands.doOpenOrActivateFileTab.on((e) => { // Basically we have to maintain the current focus const activeElement = document.activeElement; commands.doOpenOrFocusFile.emit(e); if (activeElement) { setTimeout(() => $(activeElement).focus(), 100); } }); commands.doOpenOrFocusTab.on(e=>{ // if open and not focused then focus and goto pos const existingTab = this.tabs.find(t => { return t.id == e.tabId; }); if (existingTab) { // Focus if not focused if (!this.selectedTabInstance || this.selectedTabInstance.id !== existingTab.id){ this.tabState.triggerFocusAndSetAsSelected(existingTab.id); } if (e.position) { this.tabState.gotoPosition(existingTab.id, e.position); } } else { // otherwise reopen let codeTab: TabInstance = { id: e.tabId, url: e.tabUrl, additionalData: null } // Add tab this.addTabToLayout(codeTab); // Focus this.tabState.selectTab(codeTab.id); if (e.position) { this.tabState.gotoPosition(codeTab.id, e.position); } } }); commands.closeFilesDirs.on((e)=>{ let toClose = (filePath:string) => { return e.files.indexOf(filePath) !== -1 || e.dirs.some(dirPath => filePath.startsWith(dirPath)); } let tabsToClose = this.tabs.filter((t, i) => { let {protocol, filePath} = utils.getFilePathAndProtocolFromUrl(t.url); return protocol === 'file' && toClose(filePath); }); tabsToClose.forEach(t => this.tabHandle[t.id].triggerClose()); }); commands.undoCloseTab.on(() => { if (this.closedTabs.length) { let tab = this.closedTabs.pop(); // Add tab this.addTabToLayout(tab); // Focus this.tabState.selectTab(tab.id); } }); commands.duplicateTab.on((e) => { const currentFilePath = getCurrentFilePathOrWarn(); if (!currentFilePath) return; if (!this.selectedTabInstance) return; let codeTab: TabInstance = { id: createId(), url: this.selectedTabInstance.url, additionalData: this.selectedTabInstance.additionalData } // Add tab this.addTabToLayout(codeTab); // Focus this.tabState.selectTab(codeTab.id); }); /** * Goto tab by index */ const gotoNumber = this.tabState._jumpToTabNumber; commands.gotoTab1.on(() => gotoNumber(1)); commands.gotoTab2.on(() => gotoNumber(2)); commands.gotoTab3.on(() => gotoNumber(3)); commands.gotoTab4.on(() => gotoNumber(4)); commands.gotoTab5.on(() => gotoNumber(5)); commands.gotoTab6.on(() => gotoNumber(6)); commands.gotoTab7.on(() => gotoNumber(7)); commands.gotoTab8.on(() => gotoNumber(8)); commands.gotoTab9.on(() => gotoNumber(9)); /** * Next and previous tabs */ commands.nextTab.on(() => { const currentTabId = this.selectedTabInstance && this.selectedTabInstance.id; const currentIndex = this.tabs.findIndex(t => t.id === currentTabId); let nextIndex = utils.rangeLimited({ min: 0, max: this.tabs.length - 1, num: currentIndex + 1, loopAround: true }); setTimeout(() => { // No idea why :-/ this.tabState.triggerFocusAndSetAsSelected(this.tabs[nextIndex].id); }); }); commands.prevTab.on(() => { const currentTabId = this.selectedTabInstance && this.selectedTabInstance.id; const currentIndex = this.tabs.findIndex(t => t.id === currentTabId); let nextIndex = utils.rangeLimited({ min: 0, max: this.tabs.length - 1, num: currentIndex - 1, loopAround: true }); setTimeout(() => { // No idea why :-/ this.tabState.triggerFocusAndSetAsSelected(this.tabs[nextIndex].id); }); }); /** * Close tab commands */ commands.closeTab.on((e) => { // Remove the selected this.tabState.closeCurrentTab(); }); commands.closeOtherTabs.on((e) => { const currentTabId = this.selectedTabInstance && this.selectedTabInstance.id; const otherTabs = this.tabs.filter(t => t.id !== currentTabId); otherTabs.forEach(t => this.tabHandle[t.id].triggerClose()); }); commands.closeAllTabs.on((e) => { commands.closeOtherTabs.emit({}); commands.closeTab.emit({}); }); /** * Find and Replace */ state.subscribeSub(state => state.findOptions, (findQuery) => { let api = this.getSelectedTabApiIfAny(); const options = state.getState().findOptions; if (options.isShown) { api.search.doSearch.emit(options); } else { api.search.hideSearch.emit(options); } }); commands.findNext.on(() => { let component = this.getSelectedTabApiIfAny(); let findOptions = state.getState().findOptions; component.search.findNext.emit(findOptions); }); commands.findPrevious.on(() => { let component = this.getSelectedTabApiIfAny(); let findOptions = state.getState().findOptions; component.search.findPrevious.emit(findOptions); }); commands.replaceNext.on((e) => { let component = this.getSelectedTabApiIfAny(); component.search.replaceNext.emit(e); }); commands.replacePrevious.on((e) => { let component = this.getSelectedTabApiIfAny(); component.search.replacePrevious.emit(e); }); commands.replaceAll.on((e) => { let component = this.getSelectedTabApiIfAny(); component.search.replaceAll.emit(e); }); /** * Other Types Of tabs */ commands.doOpenDependencyView.on((e) => { let codeTab: TabInstance = { id: createId(), url: `dependency://Dependency View`, additionalData: null, } // Add tab this.addTabToLayout(codeTab); // Focus this.tabState.selectTab(codeTab.id); }); /** Only allows a single tab of a type */ const openOrFocusSingletonTab = ({protocol, url}: { protocol: string, url: string }) => { // if open and active => focus // if open and not active => active // if not open and active if (this.selectedTabInstance && utils.getFilePathAndProtocolFromUrl(this.selectedTabInstance && this.selectedTabInstance.url).protocol === protocol) { this.tabState.focusSelectedTabIfAny(); return; } let openTabIndex = this.tabs.findIndex(t => utils.getFilePathAndProtocolFromUrl(t.url).protocol === protocol); if (openTabIndex != -1) { this.tabState.triggerFocusAndSetAsSelected(this.tabs[openTabIndex].id); return; } let newTab: TabInstance = { id: createId(), url, additionalData: null, } // Add tab this.addTabToLayout(newTab); // Focus this.tabState.selectTab(newTab.id); } /** Documentation view */ commands.toggleDocumentationBrowser.on(()=>{ const protocol = tabRegistry.tabs.documentation.protocol; const url = `${protocol}://Documentation`; openOrFocusSingletonTab({ protocol, url }); }); /** Tested view */ commands.doOpenTestResultsView.on(()=>{ const protocol = tabRegistry.tabs.tested.protocol; const url = `${protocol}://Tested`; openOrFocusSingletonTab({ protocol, url }); }); /** Find and replace multi */ commands.findAndReplaceMulti.on((e) => { const protocol = tabRegistry.tabs.farm.protocol; const url = `${protocol}://Find And Replace`; openOrFocusSingletonTab({ protocol, url }); }); /** Live demo view */ commands.ensureLiveDemoTab.on((e) => { const protocol = tabRegistry.tabs.livedemo.protocol; const url = `${protocol}://${e.filePath}`; const currentTabId = this.selectedTabInstance && this.selectedTabInstance.id; openOrFocusSingletonTab({ protocol, url }); this.moveCurrentTabRightIfAny(); if (currentTabId) { this.tabState.triggerFocusAndSetAsSelected(currentTabId) } }); commands.closeDemoTab.on(e => { // If tab is open we just close it const protocol = tabRegistry.tabs.livedemo.protocol; const existing = this.tabs.find(t => { return utils.getFilePathAndProtocolFromUrl(t.url).protocol == protocol; }); if (existing) { this.tabState.closeTabById(existing.id); return; } }); commands.ensureLiveDemoReactTab.on((e) => { const protocol = tabRegistry.tabs.livedemoreact.protocol; const url = `${protocol}://${e.filePath}`; const currentTabId = this.selectedTabInstance && this.selectedTabInstance.id; openOrFocusSingletonTab({ protocol, url }); this.moveCurrentTabRightIfAny(); if (currentTabId) { this.tabState.triggerFocusAndSetAsSelected(currentTabId) } }); commands.closeDemoReactTab.on(e => { // If tab is open we just close it const protocol = tabRegistry.tabs.livedemoreact.protocol; const existing = this.tabs.find(t => { return utils.getFilePathAndProtocolFromUrl(t.url).protocol == protocol; }); if (existing) { this.tabState.closeTabById(existing.id); return; } }); /** AST view */ let getCurrentFilePathOrWarn = () => { let tab = this.tabState.getSelectedTab(); let notify = () => ui.notifyWarningNormalDisappear('Need a valid file path for this action. Make sure you have a *file* tab as active'); if (!tab) { notify(); return; } let {protocol, filePath} = utils.getFilePathAndProtocolFromUrl(tab.url); if (protocol !== 'file') { notify(); return; } return filePath; } let openAnalysisViewForCurrentFilePath = (getUrl: (filePath: string) => string) => { let filePath = getCurrentFilePathOrWarn(); if (!filePath) return; let codeTab: TabInstance = { id: createId(), url: getUrl(filePath), additionalData: null } // Add tab this.addTabToLayout(codeTab); // Focus this.tabState.selectTab(codeTab.id); } commands.doOpenASTView.on((e) => { openAnalysisViewForCurrentFilePath((filePath)=>{ return `${tabRegistry.tabs.ast.protocol}://${filePath}` }); }); commands.doOpenASTFullView.on((e) => { openAnalysisViewForCurrentFilePath((filePath)=>{ return `${tabRegistry.tabs.astfull.protocol}://${filePath}` }); }); commands.doOpenUmlDiagram.on((e) => { openAnalysisViewForCurrentFilePath((filePath)=>{ return `${tabRegistry.tabs.uml.protocol}://${filePath}` }); }); commands.launchTsFlow.on((e) => { let filePath = getCurrentFilePathOrWarn(); if (!filePath) return; let tsFlowTab: TabInstance = { id: createId(), url: `${tabRegistry.tabs.tsflow.protocol}://${filePath}`, additionalData: { position: 0 /** TODO: tsflow load from actual file path current cursor */ } } // Add tab this.addTabToLayout(tsFlowTab); // Focus this.tabState.selectTab(tsFlowTab.id); }); } ctrls: { root?: HTMLDivElement } = {} render() { return ( <div ref={root => this.ctrls.root = root} style={csx.extend(csx.vertical, csx.flex, { maxWidth: '100%', overflow: 'hidden' }) } className="app-tabs"> </div> ); } onSavedChanged(tab: TabInstance, saved: boolean) { if (this.tabHandle[tab.id]) { this.tabHandle[tab.id].setSaved(saved); } } /** * Does exactly what it says. */ addTabToLayout = (tab: TabInstance, sendToServer = true) => { this.tabs.push(tab); if (sendToServer) { this.sendTabInfoToServer(); this.tabState.refreshTipHelp(); } const {url, id} = tab; const {protocol,filePath} = utils.getFilePathAndProtocolFromUrl(tab.url); const props: tab.TabProps = { url, additionalData: tab.additionalData, onSavedChanged: (saved)=>this.onSavedChanged(tab,saved), onFocused: () => { if (this.selectedTabInstance && this.selectedTabInstance.id === id) return; this.tabState.selectTab(id) }, api: this.createTabApi(id), setCodeEditor: (codeEditor: CodeEditor) => this.codeEditorMap[id] = codeEditor }; const title = tabRegistry.getTabConfigByUrl(url).getTitle(url); // Find the active stack if any let currentItemAndParent = this.getCurrentTabRootStackIfAny(); // By default we try to add to (in desending order) // The current stack // the root stack // the root let contentRoot = (currentItemAndParent && currentItemAndParent.parent) || this.layout.root.contentItems[0] || this.layout.root; contentRoot.addChild({ type: 'react-component', component: protocol, title, props, id }); } private getCurrentTabRootStackIfAny(): {item: GoldenLayout.ContentItem, parent: GoldenLayout.ContentItem} | undefined{ if (this.selectedTabInstance) { const id = this.selectedTabInstance.id; const item: GoldenLayout.ContentItem = this.layout.root.contentItems[0].getItemsById(id)[0] as any; if (item && item.parent && item.parent.type == 'stack') { return { item, parent: item.parent }; } } } private moveTabUtils = { /** * Utility to create a container that doesn't reinitialize its children */ createContainer: (type:'stack'|'row'|'column') => { const item = this.layout.createContentItem({ type: type, content: [] }) as any as GoldenLayout.ContentItem; item.isInitialised = true; // Prevents initilizing its children return item; }, /** * Utility that doesn't *uninitalize* the child it is removing */ detachFromParent: (item: GoldenLayout.ContentItem) => { item.parent.removeChild(item, true); }, } private moveCurrentTabRightIfAny = () => { let currentItemAndParent = this.getCurrentTabRootStackIfAny(); if (!currentItemAndParent) return; const {item,parent} = currentItemAndParent; const root = parent.parent; /** Can't move the last item */ if (parent.contentItems.length === 1) { return; } // If parent.parent is a `row` its prettier to just add to that row ;) if (root.type === 'row') { // Create a new container for just this tab this.moveTabUtils.detachFromParent(item); const newItemRootElement = this.moveTabUtils.createContainer('stack'); newItemRootElement.addChild(item); // Add this new container to the root root.addChild(newItemRootElement); } else { const indexOfParentInRoot = parent.parent.contentItems.findIndex((c) => c == parent); // Create a new container for just this tab this.moveTabUtils.detachFromParent(item); const newItemRootElement = this.moveTabUtils.createContainer('stack'); newItemRootElement.addChild(item); // Create a new layout to be the root of the two stacks const newRootLayout = this.moveTabUtils.createContainer('row'); newRootLayout.addChild(newItemRootElement); // Also add the old parent to this new row const doTheDetachAndAdd = ()=>{ // Doing this detach immediately breaks the layout // This is because for column / row when a child is removed the splitter is gone // And by chance this is the splitter that the new item was going to :-/ this.moveTabUtils.detachFromParent(parent); newRootLayout.addChild(parent, 0); } if (root.type === 'column') { setTimeout(doTheDetachAndAdd, 10); } else { // type `root` *must* only have a single item at a time :) // So we *must* do it sync for that case doTheDetachAndAdd(); } // Add this new container to the root root.addChild(newRootLayout, indexOfParentInRoot); } } private moveCurrentTabDownIfAny = () => { // Very similar to moveCurrentTabRightIfAny // Just replaced `row` with `column` and `column` with `row`. // This code can be consolidated but leaving as seperate as I suspect they might diverge let currentItemAndParent = this.getCurrentTabRootStackIfAny(); if (!currentItemAndParent) return; const {item,parent} = currentItemAndParent; const root = parent.parent; /** Can't move the last item */ if (parent.contentItems.length === 1) { return; } // If parent.parent is a `column` its prettier to just add to that column ;) if (root.type === 'column') { // Create a new container for just this tab this.moveTabUtils.detachFromParent(item); const newItemRootElement = this.moveTabUtils.createContainer('stack'); newItemRootElement.addChild(item); // Add this new container to the root root.addChild(newItemRootElement); } else { const indexOfParentInRoot = parent.parent.contentItems.findIndex((c) => c == parent); // Create a new container for just this tab this.moveTabUtils.detachFromParent(item); const newItemRootElement = this.moveTabUtils.createContainer('stack'); newItemRootElement.addChild(item); // Create a new layout to be the root of the two stacks const newRootLayout = this.moveTabUtils.createContainer('column'); newRootLayout.addChild(newItemRootElement); // Also add the old parent to this new row const doTheDetachAndAdd = ()=>{ // Doing this detach immediately breaks the layout // This is because for column / row when a child is removed the splitter is gone // And by chance this is the splitter that the new item was going to :-/ this.moveTabUtils.detachFromParent(parent); newRootLayout.addChild(parent, 0); } if (root.type === 'row') { setTimeout(doTheDetachAndAdd, 10); } else { // type `root` *must* only have a single item at a time :) // So we *must* do it sync for that case doTheDetachAndAdd(); } // Add this new container to the root root.addChild(newRootLayout, indexOfParentInRoot); } } private sendTabInfoToServer = () => { const serialized = GLUtil.serializeConfig(this.layout.toConfig(), this); server.setOpenUITabs({ sessionId: getSessionId(), tabLayout: serialized, selectedTabId: this.selectedTabInstance && this.selectedTabInstance.id }); } createTabApi(id: string) { const api = newTabApi(); this.tabApi[id] = api; return api; } debugLayoutTree() { const config = this.layout.toConfig(); const root = config.content; const generateSpaces = (indent:number) => Array((indent * 2) + 1).map(i => " ").join(' '); const printItem = (item, depth = 0) => { if (!depth){ console.log('ROOT-----') } else { const indent = generateSpaces(depth); console.log(indent + item.type); } if (item.content) { item.content.forEach(c => printItem(c, depth + 1)); } } // console.log(config); printItem(config); } /** * If we have a selected tab we return its api. * Otherwise we create one on the fly so you don't need to worry about * constantly checking if selected tab. (pain from v1). */ getSelectedTabApiIfAny() { if (this.selectedTabInstance && this.tabApi[this.selectedTabInstance.id]) { return this.tabApi[this.selectedTabInstance.id]; } else { return newTabApi(); } } getTabApi(id: string) { return this.tabApi[id]; } createTabHandle(tabInfo){ // console.log(tabInfo); const item = tabInfo.contentItem; const tab:JQuery = tabInfo.element; const tabConfig = tabInfo.contentItem.config; const id = tabConfig.id; // mouse down because we want tab state to change even if user initiates a drag tab.on('mousedown', (evt) => { // if the user is center clicking, close the tab const centerClick = evt.button === 1; if (centerClick) { tab.find('.lm_close_tab').trigger('click'); return; } // But not if the user is clicking the close button const closeButtonClicked = evt.target && evt.target.className == "lm_close_tab"; if (closeButtonClicked) { return; } this.tabState.selectTab(id); }); let tabIndexDisplay: JQuery = null; const removeTabIndexDisplayIfAny = () => { if (tabIndexDisplay) { tabIndexDisplay.remove(); tabIndexDisplay = null; } } this.tabHandle[id] = { saved: true, setSaved: (saved)=> { this.tabHandle[id].saved = saved; tab.toggleClass('unsaved', !saved); }, triggerFocus: () => { /** * setTimeout needed because we call `triggerFocus` when * golden-layout is still in the process of changing tabs sometimes */ setTimeout(() => { tabInfo.header.parent.setActiveContentItem(item); }); }, showIndex: (index: number) => { if (index > 9) { // Wow this user has too many tabs. Abort return; } tabIndexDisplay = $('<div class="alm_jumpIndex">' + index + '</div>'); tab.append(tabIndexDisplay); }, hideIndex: removeTabIndexDisplayIfAny, triggerClose: () => { tab.find('.lm_close_tab').trigger('click'); }, /** Selected class */ addSelectedClass: () => { tab.addClass('alm_selected'); }, removeSelectedClass: () => { tab.removeClass('alm_selected'); }, } } /** * Tab State */ /** Our way to send stuff (events) down to the tab */ tabApi: {[id:string]: tab.TabApi } = Object.create(null); /** This is different from the Tab Api in that its stuff *we* render for the tab */ tabHandle: { [id: string]: { saved: boolean; setSaved: (saved: boolean) => void; triggerFocus: () => void; showIndex: (i: number) => void; hideIndex: () => void; triggerClose: () => void; /** Selected class */ addSelectedClass: () => void; removeSelectedClass: () => void; } } = Object.create(null); /** * Having access to the current code editor is vital for some parts of the application * For this reason we allow the CodeTab to tell us about its codeEditor instance */ codeEditorMap : {[id:string]: CodeEditor} = Object.create(null); tabs: TabInstance[] = []; /** Selected tab instance */ _selectedTabInstance: TabInstance; set selectedTabInstance(value: TabInstance) { // The active tab class management if (this._selectedTabInstance && this.tabHandle[this._selectedTabInstance.id]) { this.tabHandle[this._selectedTabInstance.id].removeSelectedClass(); } if (value && value.id && this.tabHandle[value.id]) { this.tabHandle[value.id].addSelectedClass(); } // We don't tell non current tabs about search states. // So we need to tell them if they *come into focus* if (value && value.id && this.tabApi[value.id]) { const api = this.tabApi[value.id]; const options = state.getState().findOptions; if (!options.isShown || !options.query) { api.search.hideSearch.emit({}); } else { api.search.doSearch.emit(options); } } this._selectedTabInstance = value; tabStateChanged.emit({}); } get selectedTabInstance() { return this._selectedTabInstance; } /** Tab Sate */ tabState = { /** * Resize handling */ _resizingDontReFocus: false, debouncedResize: utils.debounce(() => { this.tabState._resizingDontReFocus = true; this.tabState.resize(); },200), resize: () => { this.layout.updateSize(); this.tabState.resizeTheTabs(); }, resizeTheTabs: () => { this.tabs.forEach(t => this.tabApi[t.id].resize.emit({})); }, setTabs: (tabs: TabInstance[]) => { this.tabs = tabs; this.sendTabInfoToServer(); this.tabState.refreshTipHelp(); }, selectTab: (id: string) => { let lastSelectedTab = this.selectedTabInstance; if (lastSelectedTab && id !== lastSelectedTab.id) { this.tabApi[lastSelectedTab.id] && this.tabApi[lastSelectedTab.id].willBlur.emit({}); } this.selectedTabInstance = this.tabs.find(t => t.id == id); this.tabState.focusSelectedTabIfAny(); if (!lastSelectedTab || (lastSelectedTab && lastSelectedTab.id !== id)) { this.sendTabInfoToServer(); } }, focusSelectedTabIfAny: () => { this.selectedTabInstance && this.tabApi[this.selectedTabInstance.id].focus.emit({}); }, triggerFocusAndSetAsSelected: (id:string) => { this.tabHandle[id].triggerFocus(); this.tabState.selectTab(id); }, refreshTipHelp: () =>{ // If no tabs show tips // If some tabs hide tips this.tabs.length ? TipRender.hideTips() : TipRender.showTips(); }, tabClosedInLayout: (id: string) => { const closedTabInstance = this.tabs.find(t => t.id == id); this.closedTabs.push(closedTabInstance); const index = this.tabs.map(t=>t.id).indexOf(id); delete this.tabHandle[id]; delete this.tabApi[id]; delete this.codeEditorMap[id]; this.tabState.setTabs(this.tabs.filter(t=>t.id !== id)); // Figure out the tab which will become active if (this.selectedTabInstance && this.selectedTabInstance.id === id){ this.selectedTabInstance = GLUtil.prevOnClose({ id, config: this.layout.toConfig() }); } // The close tab logic inside golden layout, can disconnect the active tab logic of ours // (we try to preserve current tab if some other tab closes) // So no matter what we need to refocus on the selected tab from within Golden-Layout if (this.selectedTabInstance) { this.tabHandle[this.selectedTabInstance.id].triggerFocus(); } }, gotoPosition: (id: string, position: EditorPosition) => { setTimeout(()=>this.tabApi[id].gotoPosition.emit(position)); }, /** * Tab closing */ closeCurrentTab: () => { if (!this.selectedTabInstance) return; this.tabState.closeTabById(this.selectedTabInstance.id); }, closeTabById: (id: string) => { this.tabHandle[id].triggerClose(); }, /** * Fast tab jumping */ _showingTabIndexes: false, _jumpToTabNumber: (oneBasedIndex: number) => { const index = oneBasedIndex - 1; if (!this.tabs[index]) { return; } const tab = this.tabs[index]; this.tabState.triggerFocusAndSetAsSelected(tab.id); this.tabState.hideTabIndexes(); }, _fastTabJumpListener: (evt: KeyboardEvent) => { const keyCodeFor1 = 49; const tabNumber = evt.keyCode - keyCodeFor1 + 1; if (tabNumber >= 1 && tabNumber <= 9) { this.tabState._jumpToTabNumber(tabNumber); } if (evt.keyCode == 39) /* Right */ { this.moveCurrentTabRightIfAny(); } if (evt.keyCode == 40) /* Down */ { this.moveCurrentTabDownIfAny(); } if (evt.keyCode == 68) /* d */ { commands.duplicateTab.emit({}); } // prevent key prop evt.preventDefault(); evt.stopPropagation(); evt.stopImmediatePropagation(); this.tabState.hideTabIndexes(); // console.log(evt, tabNumber); // DEBUG }, _removeOnMouseDown: (evt:MouseEvent) => { this.tabState.hideTabIndexes(); }, showTabIndexes: () => { if (this.tabState._showingTabIndexes) { this.tabState.hideTabIndexes(); } // this.debugLayoutTree(); // DEBUG this.tabState._showingTabIndexes = true; window.addEventListener('keydown', this.tabState._fastTabJumpListener); window.addEventListener('mousedown', this.tabState._removeOnMouseDown); this.tabs.map((t,i)=>{ if (!this.tabHandle[t.id]){ return; } this.tabHandle[t.id].showIndex(i + 1); }); if (this.selectedTabInstance) { TabMoveHelp.showHelp(); } }, hideTabIndexes: () => { this.tabState._showingTabIndexes = false; window.removeEventListener('keydown', this.tabState._fastTabJumpListener); window.removeEventListener('mousedown', this.tabState._removeOnMouseDown); this.tabs.map((t,i)=>{ if (!this.tabHandle[t.id]){ return; } this.tabHandle[t.id].hideIndex(); }); TabMoveHelp.hideHelp(); }, /** * Not to be used locally. * This is an external API used to drive app tabs contianer for refactorings etc. */ getFocusedCodeEditorIfAny: (): CodeEditor => { if (!this.selectedTabInstance || !this.selectedTabInstance.id || !this.selectedTabInstance.url.startsWith('file:') || !this.codeEditorMap[this.selectedTabInstance.id]) { return null; } return this.codeEditorMap[this.selectedTabInstance.id]; }, getSelectedTab: (): TabInstance => { return this.selectedTabInstance; }, getSelectedFilePath: (): string | undefined => { const selected = this.selectedTabInstance; if (selected) { let url = selected.url; if (url.startsWith('file://')) { return utils.getFilePathFromUrl(url); } } }, getOpenFilePaths: (): string[] => { return this.tabs.filter(t => t.url.startsWith('file://')).map(t => utils.getFilePathFromUrl(t.url)); }, addTabs: (tabs: TabInstance[]) => { tabs.forEach(tab => this.addTabToLayout(tab)); }, /** * TODO: this function is a bit heavy so can use some caching */ errorsByFilePathFiltered: (): { errorsFlattened: types.CodeError[], errorsByFilePath: types.ErrorsByFilePath } => { const allState = state.getState(); const filter = allState.errorsFilter.trim(); const mode = allState.errorsDisplayMode; const allErrors = errorsCache.getErrors(); /** Flatten errors as we need those for "gotoHistory" */ let errorsFlattened = utils.selectMany(Object.keys(allErrors).map(x => allErrors[x])); /** Filter by string if any */ if (filter) { errorsFlattened = errorsFlattened.filter(e => e.filePath.includes(filter) || e.message.includes(filter) || e.preview.includes(filter)); } /** Filter by path if any */ if (mode === types.ErrorsDisplayMode.openFiles) { const openFilePaths = utils.createMap(this.tabState.getOpenFilePaths()); errorsFlattened = errorsFlattened.filter(e => openFilePaths[e.filePath]); } return { errorsFlattened, errorsByFilePath: utils.createMapByKey(errorsFlattened, (e) => e.filePath) }; } } } const NoSelectedTab = -1; const newTabApi = ()=>{ // Note : i am using any as `new TypedEvent<FindOptions>()` breaks syntax highlighting // but don't worry api is still type checked for members const api: tab.TabApi = { resize: new TypedEvent(), focus: new TypedEvent(), save: new TypedEvent(), close: new TypedEvent() as any, gotoPosition: new TypedEvent() as any, willBlur: new TypedEvent() as any, search: { doSearch: new TypedEvent() as any, hideSearch: new TypedEvent() as any, findNext: new TypedEvent() as any, findPrevious: new TypedEvent() as any, replaceNext: new TypedEvent() as any, replacePrevious: new TypedEvent() as any, replaceAll: new TypedEvent() as any } }; return api; } /** * Golden layout helpers */ namespace GLUtil { /** The layout for serialization */ type Layout = types.TabLayout; /** * Specialize the `Stack` type in the golden-layout config * because of how we configure golden-layout originally */ type Stack = { type: 'stack' content: { id: string; props: tab.TabProps }[]; activeItemIndex: number; } /** We map the stack to a tab stack which is more relevant to our configuration queries */ interface TabStack { selectedIndex: number; tabs: TabInstance[]; } /** * A visitor for stack * Navigates down to any root level stack or the stack as a child of an row / columns */ export const visitAllStacks = (content: GoldenLayout.ItemConfig[], cb: (stack: Stack) => void) => { content.forEach(c => { if (c.type === 'row' || c.type === 'column') { visitAllStacks(c.content, cb); } if (c.type === 'stack') { cb(c as any); } }); } /** * Gets the tab instaces for a given stack */ export function toTabStack(stack: Stack): TabStack { const tabs: TabInstance[] = (stack.content || []).map(c => { const props: tab.TabProps = c.props; const id = c.id; return { id: id, url: props.url, additionalData: props.additionalData }; }); return { selectedIndex: stack.activeItemIndex, tabs }; } /** * Get the gl layout instances for a given tab */ export function fromTabStack(tabs: TabInstance[], appTabsContainer: AppTabsContainer): GoldenLayout.ItemConfig[] { return tabs.map(tab => { const {url, id, additionalData} = tab; const {protocol, filePath} = utils.getFilePathAndProtocolFromUrl(tab.url); const props: tab.TabProps = { url, additionalData, onSavedChanged: (saved) => appTabsContainer.onSavedChanged(tab, saved), onFocused: () => { if (appTabsContainer.selectedTabInstance && appTabsContainer.selectedTabInstance.id === id) return; appTabsContainer.tabState.selectTab(id) }, api: appTabsContainer.createTabApi(id), setCodeEditor: (codeEditor: CodeEditor) => appTabsContainer.codeEditorMap[id] = codeEditor }; const title = tabRegistry.getTabConfigByUrl(url).getTitle(url); return { type: 'react-component', component: protocol, title, props, id }; }); } /** * Get the tabs in order */ export function orderedTabs(config:GoldenLayout.Config): TabInstance[] { let result: TabInstance[] = []; const addFromStack = (stack: Stack) => result = result.concat(toTabStack(stack).tabs); // Add from all stacks visitAllStacks(config.content, addFromStack); return result; } /** * Serialize the tab layout */ export function serializeConfig(config: GoldenLayout.Config, appTabsContainer: AppTabsContainer) { /** Assume its a stack to begin with */ let result: Layout = { type: 'stack', width: 100, height: 100, tabs:[], subItems: [], activeItemIndex: 0, } /** The root is actually just `root` with a single content item if any */ const goldenLayoutRoot = config.content[0]; // and its empty so we good if (!goldenLayoutRoot) { return result; } /** * Recursion helpers */ function addStackItemsToLayout(layout: Layout, glStack: GoldenLayout.ItemConfig) { const stack: Layout = { type: 'stack', width: glStack.width || 100, height: glStack.height || 100, tabs: toTabStack(glStack as any).tabs, subItems: [], activeItemIndex: (glStack as any).activeItemIndex, } layout.subItems.push(stack); } function addRowItemsToLayout(layout: Layout, glRow: GoldenLayout.ItemConfig) { const row: Layout = { type: 'row', width: glRow.width || 100, height: glRow.height || 100, tabs: [], subItems: [], activeItemIndex: 0, } layout.subItems.push(row); (glRow.content || []).forEach(c => callRightFunctionForGlChild(row, c)); } function addColumnItemsToLayout(layout: Layout, glColumn: GoldenLayout.ItemConfig) { const column: Layout = { type: 'column', width: glColumn.width || 100, height: glColumn.height || 100, tabs: [], subItems: [], activeItemIndex: 0, } layout.subItems.push(column); (glColumn.content || []).forEach(c => callRightFunctionForGlChild(column, c)); } function callRightFunctionForGlChild(layout: Layout, c: GoldenLayout.ItemConfigType) { if (c.type === 'column') { addColumnItemsToLayout(layout, c); } if (c.type === 'row') { addRowItemsToLayout(layout, c); } if (c.type === 'stack') { addStackItemsToLayout(layout, c); } } // So the root `type` is whatever it really is result.type = goldenLayoutRoot.type; /** If the root is a stack .. we done */ if (goldenLayoutRoot.type === 'stack') { result.tabs = toTabStack(goldenLayoutRoot as any).tabs; } else { /** Start the recursion at the root */ (goldenLayoutRoot.content || []).forEach(c => callRightFunctionForGlChild(result, c)); } // console.log(result); // unserializeConfig(result, appTabsContainer); // DEBUG : how it will unserilize later return result; } export function unserializeConfig(layout: Layout, appTabsContainer: AppTabsContainer): any { /** * Recursion helpers */ function stackLayout(layout: Layout): GoldenLayout.ItemConfig { const stack: GoldenLayout.ItemConfig = { type: 'stack', width: layout.width || 100, height: layout.height || 100, content: fromTabStack(layout.tabs, appTabsContainer), activeItemIndex: layout.activeItemIndex, } return stack; } function rowLayout(layout: Layout): GoldenLayout.ItemConfig { const row: GoldenLayout.ItemConfig = { type: 'row', width: layout.width || 100, height: layout.height || 100, content: layout.subItems.map(c => callRightFunctionForLayoutChild(c)), } return row; } function columnLayout(layout: Layout): GoldenLayout.ItemConfig { const column: GoldenLayout.ItemConfig = { type: 'column', width: layout.width || 100, height: layout.height || 100, content: layout.subItems.map(c => callRightFunctionForLayoutChild(c)), } return column; } function callRightFunctionForLayoutChild(layout: Layout): GoldenLayout.ItemConfigType { if (layout.type === 'column') { return columnLayout(layout); } if (layout.type === 'row') { return rowLayout(layout); } if (layout.type === 'stack') { return stackLayout(layout); } } const result: GoldenLayout.Config = { content: [callRightFunctionForLayoutChild(layout)] }; // console.log(result); // DEBUG : the outcome of unserialization return result; } /** * It will be the previous tab on the current stack * and if the stack is empty it will be the active tab on previous stack (if any) */ export function prevOnClose(args: { id: string, config: GoldenLayout.Config }): TabInstance | null { const stacksInOrder: TabStack[] = []; visitAllStacks(args.config.content, (stack) => stacksInOrder.push(toTabStack(stack))); /** Find the stack that has this id */ const stackWithClosingTab = stacksInOrder.find(s => s.tabs.some(t => t.id === args.id)); /** if the last tab in the stack */ if (stackWithClosingTab.tabs.length === 1) { /** if this is the last stack then we will run out of tabs. Return null */ if (stacksInOrder.length == 1) { return null; } /** return the active in the previous stack (with loop around) */ const previousStackIndex = utils.rangeLimited({ num: stacksInOrder.indexOf(stackWithClosingTab) - 1, min: 0, max: stacksInOrder.length - 1, loopAround: true }); const previousStack = stacksInOrder[previousStackIndex]; return previousStack.tabs[previousStack.selectedIndex]; } /** Otherwise return the previous in the same stack (with loop around)*/ else { const previousIndex = utils.rangeLimited({ num: stackWithClosingTab.tabs.map(t => t.id).indexOf(args.id) - 1, min: 0, max: stackWithClosingTab.tabs.length - 1, loopAround: true }); return stackWithClosingTab.tabs[previousIndex]; } } } namespace TabMoveHelp { let tabMoveDisplay: JQuery = null; export function showHelp(){ tabMoveDisplay = $(` <div class="alm_tabMove"> <div> <span class="keyStrokeStyle">Tab Number</span> Jump to tab </div> <div> <span class="keyStrokeStyle">ESC</span> Exit </div> <div> <span class="keyStrokeStyle"><i class="fa fa-arrow-right"></i></span> Move active tab to a new rightmost pane </div> <div> <span class="keyStrokeStyle"><i class="fa fa-arrow-down"></i></span> Move active tab to a new bottom pane </div> <div> <span class="keyStrokeStyle">d</span> Duplicate current tab </div> </div> `); $(document.body).append(tabMoveDisplay); } export function hideHelp(){ if (tabMoveDisplay){ tabMoveDisplay.remove(); tabMoveDisplay = null; } } } namespace TipRender { let tipDisplay: JQuery = null; export function showTips() { if (!tipDisplay) { const node = document.createElement('div'); node.className="alm_tipRoot"; tipDisplay = $(node); $('.lm_root').append(node); ReactDOM.render(<Tips/>,node); } tipDisplay.show(); } export function hideTips() { if (tipDisplay){ tipDisplay.hide(); } } } /** * Emitted whenever the state changes * This bad boy is at the bottom because it broke syntax highlighting in atom :-/ */ export const tabStateChanged = new TypedEvent<{}>();
the_stack
// You should call obj_light_table_init whenever the tilemap // changes (such as through elevation change, or map load.) // // obj_rebuild_all_light should be called whenever an object // moves or the tilemap changes. module Lightmap { function light_reset(): void { for(var i = 0; i < tile_intensity.length; i++) tile_intensity[i] = 655 } // Tile lightmap export var tile_intensity = new Array(40000) light_reset() var light_offsets = new Array(532) zeroArray(light_offsets) // length 36 var light_distance = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 5, 6, 7, 8, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 5, 6, 7, 8, 6, 7, 8, 7, 8, 8] var isInit = false function light_subtract_from_tile(tileNum: number, intensity: number) { tile_intensity[tileNum] -= intensity } function light_add_to_tile(tileNum: number, intensity: number) { tile_intensity[tileNum] += intensity } function zeroArray(arr: any[]) { for(var i = 0; i < arr.length; i++) arr[i] = 0 } // obj_adjust_light(eax=obj_ptr, ebx=0, edx=0) // edx controls whether light is added or subtracted function obj_adjust_light(obj: Obj, isSub: boolean=false) { var pos = obj.position var lightModifier = isSub ? light_subtract_from_tile : light_add_to_tile lightModifier(toTileNum(obj.position), obj.lightIntensity) obj.lightIntensity = Math.min(obj.lightIntensity, 65536) if(!isInit) { // init console.log("initializing light tables") obj_light_table_init() isInit = true } var edx: any, eax edx = (pos.x%2)*3 * 32 eax = edx*9 //var lightOffsetsStart = light_offsets + eax // so &light_offsets[eax/4|0], we'd use an index here var lightOffsetsStart = eax // starting offset into light_offsets var light_per_dist = /* obj.lightIntensity - */ (((obj.lightIntensity - 655) / (obj.lightRadius+1)) | 0) //console.log("light per dist: %d", light_per_dist) var stackArray = new Array(36) var light = obj.lightIntensity light -= light_per_dist stackArray[0] = light light -= light_per_dist stackArray[4/4|0] = light stackArray[32/4|0] = light light -= light_per_dist stackArray[8/4|0] = light stackArray[36/4|0] = light stackArray[60/4|0] = light light -= light_per_dist stackArray[12/4|0] = light stackArray[40/4|0] = light stackArray[64/4|0] = light stackArray[84/4|0] = light light -= light_per_dist stackArray[16/4|0] = light stackArray[44/4|0] = light stackArray[68/4|0] = light stackArray[88/4|0] = light stackArray[104/4|0] = light light -= light_per_dist stackArray[20/4|0] = light stackArray[48/4|0] = light stackArray[72/4|0] = light stackArray[92/4|0] = light stackArray[108/4|0] = light stackArray[120/4|0] = light light -= light_per_dist stackArray[24/4|0] = light stackArray[52/4|0] = light stackArray[76/4|0] = light stackArray[96/4|0] = light stackArray[112/4|0] = light stackArray[124/4|0] = light stackArray[132/4|0] = light light -= light_per_dist stackArray[28/4|0] = light stackArray[56/4|0] = light stackArray[80/4|0] = light stackArray[100/4|0] = light stackArray[116/4|0] = light stackArray[128/4|0] = light stackArray[136/4|0] = light stackArray[140/4|0] = light var _light_blocked = new Array(36*6) // XXX: Is this the exact size? // zero arrays zeroArray(_light_blocked) var isLightBlocked // var_C function light_blocked(index: number) { return _light_blocked[index]; } for(var i = 0; i < 36; i++) { if(obj.lightRadius >= light_distance[i]) { var v26, v27, v28, v29, v30, v31, v32, v33, v34 // temporaries for(var dir = 0; dir < 6; dir++) { var nextDir = (dir + 1) % 6 switch(i) { case 0: isLightBlocked = 0; break; case 1: isLightBlocked = light_blocked(36 * dir); break case 2: isLightBlocked = light_blocked(36 * dir + 1); break case 3: isLightBlocked = light_blocked(36 * dir + 2); break case 4: isLightBlocked = light_blocked(36 * dir + 3); break case 5: isLightBlocked = light_blocked(36 * dir + 4); break case 6: isLightBlocked = light_blocked(36 * dir + 5); break case 7: isLightBlocked = light_blocked(36 * dir + 6); break case 8: isLightBlocked = light_blocked(36 * nextDir) & light_blocked(36 * dir); break case 9: isLightBlocked = light_blocked(36 * dir + 1) & light_blocked(36 * dir + 8); break case 10: isLightBlocked = light_blocked(36 * dir + 2) & light_blocked(36 * dir + 9); break case 11: isLightBlocked = light_blocked(36 * dir + 3) & light_blocked(36 * dir + 10); break case 12: isLightBlocked = light_blocked(36 * dir + 4) & light_blocked(36 * dir + 11); break case 13: isLightBlocked = light_blocked(36 * dir + 5) & light_blocked(36 * dir + 12); break case 14: isLightBlocked = light_blocked(36 * dir + 6) & light_blocked(36 * dir + 13); break case 15: isLightBlocked = light_blocked(36 * nextDir + 1) & light_blocked(36 * dir + 8); break case 16: isLightBlocked = light_blocked(36 * dir + 15) & light_blocked(36 * dir + 9) | light_blocked(36 * dir + 8); break; case 17: v26 = light_blocked(36 * dir + 10) | light_blocked(36 * dir + 9); isLightBlocked = light_blocked(36 * dir + 9) & (light_blocked(36 * dir + 15) | light_blocked(36 * dir + 10)) | light_blocked(36 * dir + 16) & v26 | v26 & light_blocked(36 * dir + 8); break; case 18: isLightBlocked = (light_blocked(36 * dir + 11) | light_blocked(36 * dir + 10) | light_blocked(36 * dir + 9) | light_blocked(36 * dir)) & light_blocked(36 * dir + 17) | light_blocked(36 * dir + 9) | light_blocked(36 * dir + 16) & light_blocked(36 * dir + 10); break; case 19: isLightBlocked = light_blocked(36 * dir + 18) & light_blocked(36 * dir + 12) | light_blocked(36 * dir + 10) | light_blocked(36 * dir + 9) | (light_blocked(36 * dir + 18) | light_blocked(36 * dir + 17)) & light_blocked(36 * dir + 11); break; case 20: v27 = light_blocked(36 * dir + 12) | light_blocked(36 * dir + 11) | light_blocked(36 * dir + 2); isLightBlocked = (light_blocked(36 * dir + 19) | light_blocked(36 * dir + 18) | light_blocked(36 * dir + 17) | light_blocked(36 * dir + 16)) & light_blocked(36 * dir + 11) | v27 & light_blocked(36 * dir + 8) | light_blocked(36 * dir + 9) & v27 | light_blocked(36 * dir + 10); break; case 21: isLightBlocked = light_blocked(36 * nextDir + 2) & light_blocked(36 * dir + 15) | light_blocked(36 * dir + 8) & light_blocked(36 * nextDir + 1); break; case 22: isLightBlocked = (light_blocked(36 * dir + 21) | light_blocked(36 * dir + 15)) & light_blocked(36 * dir + 16) | light_blocked(36 * dir + 15) & (light_blocked(36 * dir + 21) | light_blocked(36 * dir + 9)) | (light_blocked(36 * dir + 21) | light_blocked(36 * dir + 15) | light_blocked(36 * nextDir + 1)) & light_blocked(36 * dir + 8); break; case 23: isLightBlocked = light_blocked(36 * dir + 22) & light_blocked(36 * dir + 17) | light_blocked(36 * dir + 15) & light_blocked(36 * dir + 9) | light_blocked(36 * dir + 3) | light_blocked(36 * dir + 16); break; case 24: v28 = light_blocked(36 * dir + 23); isLightBlocked = v28 & light_blocked(36 * dir + 18) | light_blocked(36 * dir + 17) & (v28 | light_blocked(36 * dir + 22) | light_blocked(36 * dir + 15)) | light_blocked(36 * dir + 8) | light_blocked(36 * dir + 9) & (light_blocked(36 * dir + 23) | light_blocked(36 * dir + 16) | light_blocked(36 * dir + 15)) | (light_blocked(36 * dir + 18) | light_blocked(36 * dir + 17) | light_blocked(36 * dir + 10) | light_blocked(36 * dir + 9) | light_blocked(36 * dir)) & light_blocked(36 * dir + 16); break; case 25: v29 = light_blocked(36 * dir + 16) | light_blocked(36 * dir + 8); isLightBlocked = light_blocked(36 * dir + 24) & (light_blocked(36 * dir + 19) | light_blocked(36 * dir)) | light_blocked(36 * dir + 18) & (light_blocked(36 * dir + 24) | light_blocked(36 * dir + 23) | v29) | light_blocked(36 * dir + 17) | light_blocked(36 * dir + 10) & (light_blocked(36 * dir + 24) | v29 | light_blocked(36 * dir + 17)) | light_blocked(36 * dir + 1) & light_blocked(36 * dir + 8) | (light_blocked(36 * dir + 24) | light_blocked(36 * dir + 23) | light_blocked(36 * dir + 16) | light_blocked(36 * dir + 15) | light_blocked(36 * dir + 8)) & light_blocked(36 * dir + 9); break; case 26: isLightBlocked = light_blocked(36 * nextDir + 3) & light_blocked(36 * dir + 21) | light_blocked(36 * dir + 8) & light_blocked(36 * nextDir + 1) | light_blocked(36 * nextDir + 2) & light_blocked(36 * dir + 15); break; case 27: isLightBlocked = light_blocked(36 * dir + 21) & (light_blocked(36 * dir + 16) | light_blocked(36 * dir + 8)) | light_blocked(36 * dir + 15) | light_blocked(36 * nextDir + 1) & light_blocked(36 * dir + 8) | (light_blocked(36 * dir + 26) | light_blocked(36 * dir + 21) | light_blocked(36 * dir + 15) | light_blocked(36 * nextDir)) & light_blocked(36 * dir + 22); break; case 28: isLightBlocked = light_blocked(36 * dir + 27) & light_blocked(36 * dir + 23) | light_blocked(36 * dir + 22) & (light_blocked(36 * dir + 23) | light_blocked(36 * dir + 17) | light_blocked(36 * dir + 9)) | light_blocked(36 * dir + 16) & (light_blocked(36 * dir + 27) | light_blocked(36 * dir + 22) | light_blocked(36 * dir + 21) | light_blocked(36 * nextDir)) | light_blocked(36 * dir + 8) | light_blocked(36 * dir + 15) & (light_blocked(36 * dir + 23) | light_blocked(36 * dir + 16) | light_blocked(36 * dir + 9)); break; case 29: isLightBlocked = light_blocked(36 * dir + 28) & light_blocked(36 * dir + 24) | light_blocked(36 * dir + 22) & light_blocked(36 * dir + 17) | light_blocked(36 * dir + 15) & light_blocked(36 * dir + 9) | light_blocked(36 * dir + 16) | light_blocked(36 * dir + 8) | light_blocked(36 * dir + 23); break; case 30: isLightBlocked = light_blocked(36 * nextDir + 4) & light_blocked(36 * dir + 26) | light_blocked(36 * nextDir + 2) & light_blocked(36 * dir + 15) | light_blocked(36 * dir + 8) & light_blocked(36 * nextDir + 1) | light_blocked(36 * nextDir + 3) & light_blocked(36 * dir + 21); break; case 31: isLightBlocked = light_blocked(36 * dir + 30) & light_blocked(36 * dir + 27) | light_blocked(36 * dir + 26) & (light_blocked(36 * dir + 27) | light_blocked(36 * dir + 22) | light_blocked(36 * dir + 8)) | light_blocked(36 * dir + 15) | light_blocked(36 * nextDir + 1) & light_blocked(36 * dir + 8) | light_blocked(36 * dir + 21); break; case 32: // XXX: v30 here could be lightOffsetsStart, but that is unlikely v30 = light_blocked(36 * nextDir + 1) & light_blocked(36 * dir + 8) | (light_blocked(36 * dir + 28) | light_blocked(36 * dir + 23) | light_blocked(36 * dir + 16) | light_blocked(36 * dir + 9) | light_blocked(36 * dir + 8)) & light_blocked(36 * dir + 15); v31 = light_blocked(36 * dir + 16) | light_blocked(36 * dir + 8); isLightBlocked = light_blocked(36 * dir + 28) & (light_blocked(36 * dir + 31) | light_blocked(36 * dir)) | light_blocked(36 * dir + 27) & (light_blocked(36 * dir + 28) | light_blocked(36 * dir + 23) | v31) | light_blocked(36 * dir + 22) | v30 | light_blocked(36 * dir + 21) & (v31 | light_blocked(36 * dir + 28)); break; case 33: v32 = 36 * nextDir; isLightBlocked = light_blocked(v32 + 5) & light_blocked(36 * dir + 30) | light_blocked(v32 + 3) & light_blocked(36 * dir + 21) | light_blocked(v32 + 2) & light_blocked(36 * dir + 15) | light_blocked(v32 + 1) & light_blocked(36 * dir + 8) | light_blocked(v32 + 4) & light_blocked(36 * dir + 26); break; case 34: v33 = light_blocked(36 * dir + 30) | light_blocked(36 * dir + 26) | light_blocked(36 * nextDir + 2); isLightBlocked = (light_blocked(36 * dir + 31) | light_blocked(36 * dir + 27) | light_blocked(36 * dir + 22) | light_blocked(36 * dir + 16)) & light_blocked(36 * dir + 26) | light_blocked(36 * dir + 21) | light_blocked(36 * dir + 15) & v33 | v33 & light_blocked(36 * dir + 8); break; case 35: v34 = 36 * nextDir; isLightBlocked = light_blocked(v34 + 6) & light_blocked(36 * dir + 33) | light_blocked(v34 + 4) & light_blocked(36 * dir + 26) | light_blocked(v34 + 3) & light_blocked(36 * dir + 21) | light_blocked(v34 + 2) & light_blocked(36 * dir + 15) | light_blocked(36 * dir + 8) & light_blocked(v34 + 1) | light_blocked(v34 + 5) & light_blocked(36 * dir + 30); break; } if(isLightBlocked === 0) { // loc_4A7500: var nextTile = toTileNum(obj.position) + light_offsets[(lightOffsetsStart/4|0) + 36 * dir + i] if(nextTile > 0 && nextTile < 40000) { // nextTile is within valid tile range var edi = 1 // for each object at position nextTile var objs = objectsAtPosition(fromTileNum(nextTile)) for(var objsN = 0; objsN < objs.length; objsN++) { var curObj = objs[objsN] if(!curObj.pro) // XXX: why wouldn't an object have pro? continue // if(curObj+24h & 1 === 0) { continue } if((curObj.flags & 1) !== 0) { // internal flag? console.log("continue (%s)", curObj.flags.toString(16)) continue } // LightThru flag isn't set -> blocked isLightBlocked = (curObj.flags & 0x20000000 /* LightThru */) ? 0 : 1 // ebx = (curObj+20h) & 0x0F000000 >> 24 if(curObj.type === "wall") { //console.log("obj flags: " + curObj.flags.toString(16)) if(!(curObj.flags & 8)) { // Flat flag? //proto_ptr(*(v37 + 100), &v43, 3, v11); //var flags = (pro+24) var flags = curObj.pro.flags // XXX: flags directly from PRO? //console.log("pro flags: " + flags.toString(16)) if(flags & 0x8000000 || flags & 0x40000000) { if(dir != 4 && dir != 5 && (dir || i >= 8) && (dir != 3 || i <= 15)) edi = 0 } else if(flags & 0x10000000) { if(dir && dir != 5) edi = 0 } else if(flags & 0x20000000) { if(dir && dir != 1 && dir != 4 && dir != 5 && (dir != 3 || i <= 15)) edi = 0 } else if(dir && dir != 1 && (dir != 5 || i <= 7)) { edi = 0 } } } // XXX: Is this just an elevation check? /*else { // TODO: check logic if(edx !== 0) { // XXX: what is edx? if(dir >= 2) { if(dir === 3) { edi = 0 } } else if(dir === 1) edi = 0 } }*/ } if(edi !== 0) { var lightAdjustment = stackArray[i] // eax = 0 // should be set to obj+28h, aka elevation (we don't take elevation into account so we don't need this) lightModifier(nextTile, lightAdjustment) } } } _light_blocked[36 * dir + i] = isLightBlocked } } } return tile_intensity } export function obj_light_table_init(): void { setCenterTile() //var centerTile_: Point = centerTile() // should we use the center tile at all? var edi = toTileNum(tile_center) var edx = edi & 1 var eax = edx*4 eax -= edx eax <<= 5 edx = eax eax <<= 3 var ecx = 0 eax += edx var v2c = ecx var v54 = eax var v48 var ebx, ebp, esi, v3c, v40, v50, v20, v24, lightOffsetsStart, v58 var v44, v4c, v38, v34, v28, v1c, v28 do { eax = v54 edx = v2c edx++ v48 = eax eax = edx edx = eax % 6 //eax = eax / 6 | 0 ebp = 0 esi = 8 v3c = ebp v40 = esi v50 = edx do { ebx = v3c edx = v50 eax = edi eax = tile_num_in_direction(eax, edx, ebx) // ? esi = ebp*4 v24 = eax eax = v40 ecx = 0 v20 = eax eax = v48 edx = v40 esi += eax if(edx > 0) { do { edx = v2c eax = v24 ecx++ esi += 4 ebx = ecx ebp++ eax = tile_num_in_direction(eax, edx, ebx) eax -= edi ebx = v20 //console.log("light_offsets[%d] = %d", (esi-4)/4|0, eax) light_offsets[(esi-4)/4|0] = eax } while(ecx < ebx) } eax = v3c esi = v40 eax++ esi-- v3c = eax v40 = esi } while(eax < 8) ebx = v2c ecx = v54 ebx++ ecx += 144 v2c = ebx v54 = ecx } while(ebx < 6) // second part edi++ edx = edi edx &= 1 eax = edx*4 eax -= edx eax <<= 5 edx = eax eax <<= 3 ebp = 0 eax += edx lightOffsetsStart = ebp v58 = eax do { eax = v58 edx = lightOffsetsStart edx++ v44 = eax eax = edx edx = eax % 6 ebp = 0 v4c = edx edx = 8 v38 = ebp v34 = edx do { ebx = v38 edx = v4c eax = edi eax = tile_num_in_direction(eax, edx, ebx) esi = ebp*4 ecx = 0 ebx = v44 v28 = eax eax = v34 esi += ebx v1c = eax if(eax > 0) { do { edx = lightOffsetsStart eax = v28 ecx++ esi += 4 ebx = ecx ebp++ eax = tile_num_in_direction(eax, edx, ebx) eax -= edi edx = v1c //console.log("light_offsets[%d] = %d", (esi-4)/4|0, eax) light_offsets[(esi-4)/4|0] = eax } while(ecx < edx) } ebx = v38 ecx = v34 ebx++ ecx-- v38 = ebx v34 = ecx } while(ebx < 8) eax = lightOffsetsStart ebp = v58 eax++ ebp += 144 lightOffsetsStart = eax v58 = ebp } while(eax < 6) } // eax = tile, edx = direction, ebx = distance function tile_num_in_direction(tileNum: number, dir: number, distance: number): number { //console.log("tileNum: " + tileNum + " (" + tileNum.toString(16) + ")") if(dir < 0 || dir > 5) throw "tile_num_in_direction: dir = " + dir if(distance === 0) return tileNum var hex = hexInDirectionDistance(fromTileNum(tileNum), dir, distance) if(!hex) { console.log("hex (input tile is %s) is %o; dir=%d distance=%d", tileNum.toString(16), hex, dir, distance) return -1 } //console.log("tile: %d,%d -> %d,%d", fromTileNum(tileNum).x, fromTileNum(tileNum).y, hex.x, hex.y) return toTileNum(hex) } function obj_rebuild_all_light(): void { light_reset() gMap.getObjects().forEach(obj => { obj_adjust_light(obj, false) }) } export function resetLight(): void { light_reset() obj_light_table_init() } export function rebuildLight(): void { obj_rebuild_all_light() } }
the_stack
import BoxClient from '../box-client'; import urlPath from '../util/url-path'; // ----------------------------------------------------------------------------- // Typedefs // ----------------------------------------------------------------------------- /** * Enum of valid policy assignment types, which specify what object the policy applies to * @readonly * @enum {LegalHoldPolicyAssignmentType} */ enum LegalHoldPolicyAssignmentType { FOLDER = 'folder', USER = 'user', FILE = 'file', FILE_VERSION = 'file_version', } // ----------------------------------------------------------------------------- // Private // ----------------------------------------------------------------------------- const BASE_PATH = '/legal_hold_policies', ASSIGNMENTS_PATH = '/legal_hold_policy_assignments', FILE_VERSION_LEGAL_HOLDS_PATH = '/file_version_legal_holds'; // ----------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------- /** * Simple manager for interacting with all Legal Holds endpoints and actions. * * @constructor * @param {BoxClient} client - The Box API Client that is responsible for making calls to the API * @returns {void} */ class LegalHoldPolicies { client: BoxClient; assignmentTypes!: typeof LegalHoldPolicyAssignmentType; constructor(client: BoxClient) { this.client = client; } /** * Used to create a single legal hold policy for an enterprise * * API Endpoint: '/legal_hold_policies' * Method: POST * * @param {string} name - The name of the legal hold policy to be created * @param {Object} [options] - Additional parameters * @param {string} [options.description] - Description of the legal hold policy * @param {string} [options.filter_started_at] - Date filter, any Custodian assignments will apply only to file versions created or uploaded inside of the date range * @param {string} [options.filter_ended_at] - Date filter, any Custodian assignments will apply only to file versions created or uploaded inside of the date range * @param {boolean} [options.is_ongoing] - After initialization, Assignments under this Policy will continue applying to files based on events, indefinitely * @param {Function} [callback] - Passed the new policy information if it was acquired successfully, error otherwise * @returns {Promise<Object>} A promise resolving to the created policy */ create( name: string, options?: { description?: string; filter_started_at?: string; filter_ended_at?: string; is_ongoing?: boolean; }, callback?: Function ) { var apiPath = urlPath(BASE_PATH), params: Record<string, any> = { body: options || {}, }; params.body.policy_name = name; return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Fetches details about a specific legal hold policy * * API Endpoint: '/legal_hold_policies/:policyID' * Method: GET * * @param {string} policyID - The Box ID of the legal hold policy being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the policy information if it was acquired successfully, error otherwise * @returns {Promise<Object>} A promise resolving to the policy object */ get(policyID: string, options?: Record<string, any>, callback?: Function) { var apiPath = urlPath(BASE_PATH, policyID), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Update or modify a legal hold policy. * * API Endpoint: '/legal_hold_policies/:policyID' * Method: PUT * * @param {string} policyID - The Box ID of the legal hold policy to update * @param {Object} updates - The information to be updated * @param {string} [updates.policy_name] - Name of Legal Hold Policy * @param {string} [updates.description] - Description of Legal Hold Policy * @param {string} [updates.release_notes] - Notes around why the policy was released * @param {Function} [callback] - Passed the updated policy information if it was acquired successfully, error otherwise * @returns {Promise<Object>} A promise resolving to the updated policy */ update( policyID: string, updates: { policy_name?: string; description?: string; release_notes?: string; }, callback?: Function ) { var apiPath = urlPath(BASE_PATH, policyID), params = { body: updates, }; return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Fetches a list of legal hold policies for the enterprise * * API Endpoint: '/legal_hold_policies' * Method: GET * * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {string} [options.policy_name] - A full or partial name to filter the legal hold policies by * @param {int} [options.limit] - Limit result size to this number * @param {string} [options.marker] - Paging marker, leave blank to start at the first page * @param {Function} [callback] - Passed the policy objects if they were acquired successfully, error otherwise * @returns {Promise<Object>} A promise resolving to the collection of policies */ getAll( options?: { policy_name?: string; limit?: number; marker?: string; }, callback?: Function ) { var apiPath = urlPath(BASE_PATH), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Sends request to delete an existing legal hold policy. Note that this is an * asynchronous process - the policy will not be fully deleted yet when the * response comes back. * * API Endpoint: '/legal_hold_policies/:policyID' * Method: DELETE * * @param {string} policyID - The legal hold policy to delete * @param {Function} [callback] - Passed nothing if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ delete(policyID: string, callback?: Function) { var apiPath = urlPath(BASE_PATH, policyID); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, null, callback ); } /** * Fetch a list of assignments for a given legal hold policy * * API Endpoint: '/legal_hold_policies/:policyID/assignments' * Method: GET * * @param {string} policyID - The Box ID of the legal hold policy to get assignments for * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {LegalHoldPolicyAssignmentType} [options.assign_to_type] - Filter assignments of this type only * @param {string} [options.assign_to_id] - Filter assignments to this ID only. Note that this will only show assignments applied directly to this entity. * @param {Function} [callback] - Passed the assignment objects if they were acquired successfully, error otherwise * @returns {Promise<Object>} A promise resolving to the collection of policy assignments */ getAssignments( policyID: string, options?: { assign_to_type?: LegalHoldPolicyAssignmentType; assign_to_id?: string; }, callback?: Function ) { var apiPath = urlPath(ASSIGNMENTS_PATH), params = { qs: Object.assign({ policy_id: policyID }, options), }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Assign a lehal hold policy to an object * * API Endpoint: '/legal_hold_policy_assignments * Method: POST * * @param {string} policyID - The ID of the policy to assign * @param {LegalHoldPolicyAssignmentType} assignType - The type of object the policy will be assigned to * @param {string} assignID - The Box ID of the object to assign the legal hold policy to * @param {Function} [callback] - Passed the new assignment object if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the created assignment object */ assign( policyID: string, assignType: LegalHoldPolicyAssignmentType, assignID: string, callback?: Function ) { var apiPath = urlPath(ASSIGNMENTS_PATH), params = { body: { policy_id: policyID, assign_to: { type: assignType, id: assignID, }, }, }; return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Fetch a specific policy assignment * * API Endpoint: '/legal_hold_policy_assignments/:assignmentID' * Method: GET * * @param {string} assignmentID - The Box ID of the policy assignment object to fetch * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the assignment object if it was acquired successfully, error otherwise * @returns {Promise<Object>} A promise resolving to the assignment object */ getAssignment( assignmentID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(ASSIGNMENTS_PATH, assignmentID), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Sends request to delete an existing legal hold policy. Note that this is an * asynchronous process - the policy will not be fully deleted yet when the * response comes back. * * API Endpoint: '/legal_hold_policy_assignments/:assignmentID' * Method: DELETE * * @param {string} assignmentID - The legal hold policy assignment to delete * @param {Function} [callback] - Passed nothing if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ deleteAssignment(assignmentID: string, callback?: Function) { var apiPath = urlPath(ASSIGNMENTS_PATH, assignmentID); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, null, callback ); } /** * Get the specific legal hold record for a held file version. * * API Endpoint: '/file_version_legal_holds/:legalHoldID' * Method: GET * * @param {string} legalHoldID - The ID for the file legal hold record to retrieve * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Pass the file version legal hold record if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the legal hold record */ getFileVersionLegalHold( legalHoldID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(FILE_VERSION_LEGAL_HOLDS_PATH, legalHoldID), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Get a list of legal hold records for held file versions in an enterprise. * * API Endpoint: '/file_version_legal_holds' * Method: GET * * @param {string} policyID - ID of Legal Hold Policy to get File Version Legal Holds for * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Pass the file version legal holds records if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the collection of all file version legal holds */ getAllFileVersionLegalHolds( policyID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(FILE_VERSION_LEGAL_HOLDS_PATH), params = { qs: Object.assign({ policy_id: policyID }, options), }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } } /** * Enum of valid policy assignment types, which specify what object the policy applies to * @readonly * @enum {LegalHoldPolicyAssignmentType} */ LegalHoldPolicies.prototype.assignmentTypes = LegalHoldPolicyAssignmentType; export = LegalHoldPolicies;
the_stack
import { Map, Set } from "immutable"; import { WorkerSubmittedHitState, QualificationComparator } from "./worker-mturk-api"; export interface RootState { readonly account: MaybeAccount; readonly tab: number; readonly queue: QueueMap; readonly watchers: WatcherMap; readonly search: SearchResults; readonly dailyEarningsGoal: number; readonly searchingActive: boolean; readonly waitingForMturk: boolean; readonly waitingForHitDbRefresh: boolean; readonly timeNextSearch: Date | null; readonly searchOptions: SearchOptions; readonly sortingOption: SortingOption; readonly hitDatabase: HitDatabaseMap; readonly topticonSettings: TOpticonSettings; readonly hitBlocklist: HitBlockMap; readonly selectedHitDbDate: LegacyDateFormat | null; readonly requesterBlocklist: RequesterBlockMap; readonly audioSettingsV1: AudioSettings; readonly watcherTimers: WatcherTimerMap; readonly uploadedState: Partial<PersistedState> | null; readonly expandedSearchResults: ExpandedSearchResultsSet; readonly expandedQueueItems: ExpandedQueueItemsSet; readonly notificationSettings: NotificationSettings; readonly notifiedSearchResultIds: Set<GroupId>; readonly watcherTreeSettings: WatcherTreeSettings; readonly searchAudioEnabled: boolean; readonly watcherFolders: WatcherFolderMap; readonly expandedWatcherFolderIds: Set<GroupId>; readonly watcherStatistics: WatcherStatisticsMap; readonly queueSortingOption: QueueSortingOption; readonly loggedRequesters: RequesterMap; readonly databaseFilterSettings: DatabaseFilterSettings; readonly markedAsReadGroupIds: Set<GroupId>; readonly hitBlocklistFilterSettings: HitBlocklistFilterSettings; } export type Primitive = string | number | boolean; export type GroupId = string; export type HitId = string; export type RequesterId = string; export type FolderId = string; export type AssignmentId = string; export type TaskId = string; /** * Format: MMDDYYY */ export type LegacyDateFormat = string; /** * Format: YYYY-MM-DD */ export type WorkerDateFormat = string; export type SearchResults = Map<GroupId, SearchResult>; export type QueueMap = Map<HitId, QueueItem>; export type RequesterMap = Map<RequesterId, Requester>; export type HitBlockMap = Map<GroupId, BlockedHit>; export type RequesterBlockMap = Map<RequesterId, BlockedRequester>; export type WatcherMap = Map<GroupId, Watcher>; export type WatcherTimerMap = Map<GroupId, WatcherTimer>; export type WatcherFolderMap = Map<FolderId, WatcherFolder>; export type HitDatabaseMap = Map<HitId, HitDatabaseEntry>; export type ExpandedSearchResultsSet = Set<GroupId>; export type ExpandedQueueItemsSet = Set<HitId>; export type WatcherStatisticsMap = Map<GroupId, WatcherStatistics>; export type BlockList = RequesterBlockMap | HitBlockMap; export type BlockedEntry = BlockedHit | BlockedRequester; /** * The keys of RootState that are persisted by redux-persist. * See `PERSISTED_STATE_WHITELIST` in ./constants/settings */ export type PersistedStateKey = | "tab" | "account" | "hitBlocklist" | "hitDatabase" | "requesterBlocklist" | "sortingOption" | "searchOptions" | "topticonSettings" | "watchers" | "watcherFolders" | "watcherTreeSettings" | "audioSettingsV1" | "dailyEarningsGoal" | "notificationSettings" | "searchAudioEnabled"; export type ImmutablePersistedStateKey = | "hitDatabase" | "hitBlocklist" | "watchers" | "watcherFolders" | "requesterBlocklist"; export type ImmutablePersistedDataType = | HitBlockMap | RequesterBlockMap | WatcherMap | HitDatabaseMap; export type PersistedState = Pick<RootState, PersistedStateKey>; export type ImmutablePersistedState = Pick< RootState, ImmutablePersistedStateKey >; export type MaybeAccount = AccountInfo | null; export type FormTarget = | "searchOptions" | "topticonSettings" | "notificationSettings"; export type SearchSort = "Latest" | "Batch Size" | "Reward"; export interface SearchOptions { readonly searchTerm: string; readonly delay: number; readonly minReward: number; readonly sortType: SearchSort; readonly qualifiedOnly: boolean; } export type SortingOption = | "Batch Size" | "Reward" | "Latest" | "Weighted T.O."; /** * On the legacy Mturk website, 'Approved' was called 'Pending Payment' * and 'Pending' was called 'Pending Approval'. Some users may have the legacy * hit statuses in their databases. */ export type HitStatus = | WorkerSubmittedHitState | "Pending Payment" | "Pending Approval"; export interface AccountInfo { readonly id: string; readonly fullName: string; readonly availableEarnings: number; readonly lifetimeHitEarnings: number; readonly lifetimeBonusEarnings: number; readonly lifetimeTotalEarnings: number; readonly lifetimeSubmitted: number; readonly lifetimeApproved: number; readonly lifetimeRejected: number; readonly numPending: number; } export interface HumanIntelligenceTask { readonly title: string; readonly requester: Requester; readonly reward: number; readonly groupId: string; readonly description: string; readonly timeAllottedInSeconds: number; readonly qualsRequired: WorkerQualification[]; readonly batchSize: number; } export interface SearchResult extends HumanIntelligenceTask { readonly creationTime: number; // Date converted to number readonly lastUpdatedTime: number; // Date converted to number readonly qualified: boolean; readonly canPreview: boolean; } export interface LoggedSearchResult { readonly groupId: GroupId; readonly markedAsRead: boolean; readonly notificationSent: boolean; } export interface LegacyHitDatabaseEntry { readonly id: HitId; readonly date: LegacyDateFormat; readonly title: string; readonly reward: number; readonly bonus: number; readonly status: HitStatus; readonly requester: { readonly id: RequesterId; readonly name: string; }; readonly groupId?: GroupId; readonly feedback?: string; readonly assignmentId?: AssignmentId; } export interface WorkerHitDatabaseEntry extends LegacyHitDatabaseEntry { readonly assignmentId: AssignmentId; } export type HitDatabaseEntry = LegacyHitDatabaseEntry | WorkerHitDatabaseEntry; export type StatusFilterType = "PENDING" | "APPROVED" | "PAID" | "REJECTED"; export type FilterOrderType = | "PAY_DESC" | "DATE_RECENT_FIRST" | "DATE_OLDEST_FIRST"; export interface DatabaseFilterSettings { readonly searchTerm: string; readonly statusFilters: StatusFilterType[]; readonly sortOrder: FilterOrderType; } export interface HitBlocklistFilterSettings { readonly shouldRender: boolean; readonly searchTerm: string; readonly sortOrder: FilterOrderType; } export interface QueueItem extends HumanIntelligenceTask { /** * fresh will be false when QueueItems are not created from an API response. */ readonly fresh: boolean; readonly description: string; readonly hitId: HitId; readonly taskId: TaskId; readonly assignmentId: AssignmentId; readonly timeLeftInSeconds: number; } export interface NotificationSettings { readonly hasPermission: boolean; readonly enabled: boolean; readonly minReward: number; readonly durationInSeconds: number; } export interface BlockedHit { readonly groupId: GroupId; readonly title: string; readonly requester: Requester; readonly dateBlocked: Date; } export interface Requester { readonly id: RequesterId; readonly name: string; readonly turkopticon?: RequesterInfo; } export interface BlockedRequester extends Requester { readonly dateBlocked: Date; } export interface TOpticonRequester { readonly name: string; readonly attrs: TOpticonAttributes; readonly reviews: number; readonly tos_flags: number; } export interface TOpticonResponse { readonly [id: string]: TOpticonRequester; } export interface RequesterInfo { readonly scores: RequesterAttributes; readonly numReviews: number; readonly numTosFlags: number; } export interface RequesterAttributes { readonly comm?: number; readonly pay?: number; readonly fair?: number; readonly fast?: number; } export interface TOpticonAttributes { readonly comm?: string; readonly pay?: string; readonly fair?: string; readonly fast?: string; } export interface TOpticonSettings extends AttributeWeights { readonly hideBelowThresholdEnabled: boolean; readonly hideNoToEnabled: boolean; readonly minimumWeightedTO: number; } export interface AttributeWeights { readonly payWeight: number; readonly fairWeight: number; readonly commWeight: number; readonly fastWeight: number; } export interface Watcher { readonly groupId: GroupId; readonly title: string; readonly delay: number; readonly description: string; readonly createdOn: Date; readonly folderId: string; readonly stopAfterFirstSuccess: boolean; readonly playSoundAfterSuccess: boolean; } export interface WatcherTimer { readonly date: Date; readonly origin: number; } export interface WatcherStatistics { readonly successes: number; readonly failures: number; } export interface AudioSettings { readonly enabled: boolean; readonly volume: number; } export interface WorkerQualification { readonly qualificationId: string; readonly name: string; readonly description: string; readonly hasTest: boolean; readonly requestable: boolean; readonly comparator: QualificationComparator; readonly userValue: string | number | null; readonly userMeetsQualification: boolean; readonly qualificationValues: (string | number)[]; } export interface AudioFiles { readonly audioNewSearch: HTMLAudioElement; readonly audioWatcherSuccess: HTMLAudioElement; } export interface HeatMapValue { readonly date: string; readonly count: number; } export interface DailyEarnings { readonly reward: number; readonly bonus: number; } export interface WatcherTreeSettings { readonly selectionKind: SelectionKind; readonly selectionId: FolderId | GroupId | null; } export type WatcherKind = "groupId" | "searchTerm" | "requesterId"; export type SelectionKind = WatcherKind | "folder" | "none"; export interface WatcherFolder { readonly id: FolderId; readonly name: string; readonly dateNumCreation: number; } export type QueueSortingOption = "REWARD_DESC" | "TIME_LEFT_ASC";
the_stack
import { expect } from 'chai' import { ulid } from 'ulid' import { Query } from '../middleware/mongo' import { NewDexie } from '../utils' import { shouldHaveThrown } from '../utils/spec.utils' import { Collection } from './collection' // import { ChangeTableName } from "../middleware/changes"; const databaseName = 'collection' describe('ThreadDB', function () { context('collection', function () { const db = NewDexie(databaseName) after(async function () { // Cleanup time! db.close() await db.delete() }) describe('workflows', async function () { before(async function () { // Super low-level access db.version(1).stores({ things: '++_id,thing' }) }) it('should handle a normal db workflow', async function () { interface Info { _id?: string other?: number thing: string } const Thing = new Collection<Info>(db.table('things')) const data: Info = { _id: ulid(), thing: 'one' } const thing1 = data expect(thing1.thing).to.equal('one') thing1.other = 1 // Won't compile because typed instances can't have extra properties, // which is exactly what we want! // thing1.more = 'something' expect(thing1.other).to.equal(1) expect(await Thing.find({}).count()).to.equal(0) await Thing.save(thing1) expect(await Thing.find({}).count()).to.equal(1) await Thing.save(data) try { await Thing.insert(data) throw shouldHaveThrown // TODO: Better error reporting to mask out dexie stuff } catch (err) { expect(err).to.not.equal(shouldHaveThrown) } await Thing.insert( { other: -1, thing: 'five' }, { other: 2, thing: 'two' }, { other: 3, thing: 'three' }, { other: 4, thing: 'four' }, ) const all = await Thing.find({ $or: [{ other: { $gt: 1 } }, { thing: { $eq: 'one' } }], }).sortBy('_id') const last = all[0] expect(last).to.have.haveOwnProperty('other', 1) }) }) describe('units', () => { // Default Person interface to work with types type Person = { name: string age: number } // Default person data, frozen to keep from modifying directly const defaultPerson: Person = Object.freeze({ name: 'Lucas', age: 7, }) // Function to create a copy of person, rather than mutate const copyPerson = ( person: Person = defaultPerson, _id?: string, ): Person & { _id?: string } => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const out: any = { ...person } if (_id) out._id = _id return out } // Function to setup a new default collection based on the person interface // eslint-disable-next-line @typescript-eslint/explicit-function-return-type const setupCollection = () => { return new Collection<Person>(db.table('Person')) } before(async function () { // Super low-level access db.close() // Create Person store with indexes on _id, name, and age db.version(2).stores({ Person: '++_id,name,age' }) await db.open() }) beforeEach(() => { // Clear out the store before each run db.tables.forEach((table) => table.clear()) }) describe('top-level instance', () => { it('should have a name property', function () { const Person = setupCollection() expect(Person.name).to.equal('Person') }) it('should handle multiple write operations', async function () { const Person = setupCollection() // const test = copyPerson(undefined, ulid()); await Person.insert(copyPerson(), copyPerson(), copyPerson()) const person = copyPerson() const [id] = await Person.insert(person) await Person.delete(id) expect(await Person.find({}).count()).to.equal(3) }) }) describe('creating entities', () => { it('should create single entity from data', async function () { const Person = setupCollection() const person = copyPerson() expect(person).to.not.have.ownProperty('_id') // Should create entity with proper id const entity = Person.create(person) expect(entity).to.have.ownProperty('_id') // Should not exist in underlying storage yet expect(await entity.exists()).to.equal(false) expect(await Person.has(entity._id)).to.equal(false) // Now save it await entity.save() // Now it should exist in underlying storage expect(await entity.exists()).to.equal(true) expect(await Person.has(entity._id)).to.equal(true) }) it('should create entities with ulid ids by default', async function () { const Person = setupCollection() const person1 = copyPerson() const [id] = await Person.insert(person1) // Should update person in place expect(person1._id).to.equal(id) const obj = await Person.findById(id) expect(obj).to.have.ownProperty('_id') expect(obj?._id).to.equal(id) expect(obj?._id).to.have.length(26) }) it('should be able to override ulid id', async function () { const Person = setupCollection() const person1 = copyPerson() person1._id = 'override' const [id] = await Person.insert(person1) // Should update person in place expect(person1._id).to.equal('override') const obj = await Person.findById(id) expect(obj).to.have.ownProperty('_id') expect(obj?._id).to.equal(id) }) it('should create a single entity (w/ type checking) at a time', async function () { const Person = setupCollection() const person1 = copyPerson() const [id] = await Person.insert(person1) const exists = await Person.has(id) const obj = await Person.findById(id) expect(exists).to.be.true expect(obj).to.have.ownProperty('_id', id) expect(obj?.save).to.not.be.undefined const person2 = copyPerson(undefined, ulid()) let has = await Person.has(person2._id!) expect(has).to.equal(false) await Person.insert(person2) has = await Person.has(person2._id!) expect(has).to.equal(true) }) it('should create multiple entities (variadic arguments w/ type checking) at once', async function () { const Person = setupCollection() const person = copyPerson() const [id] = await Person.insert(person, copyPerson(), copyPerson()) expect(await Person.find({}).count()).to.equal(3) expect(await Person.has(id)).to.be.true }) it('should create an entity with a predefined id', async function () { const Person = setupCollection() const _id = ulid() const person = { _id, name: 'Hans', age: 12 } const [id_] = await Person.insert(person) expect(id_).to.equal(_id) }) it('should not overwrite an existing entity', async function () { const Person = setupCollection() const _id = ulid() try { await Person.insert({ _id, name: 'Hans', age: 12 } as Person) const person = { _id, name: 'Hans', age: 12 } await Person.insert(person) throw shouldHaveThrown } catch (err) { expect(err).to.not.equal(shouldHaveThrown) } }) }) describe('creating transactions', () => { it('should create a readonly transaction', async function () { const Person = setupCollection() const person = copyPerson() const [id] = await Person.insert(person) Person.readTransaction(async function () { // await Person.insert(person); expect(await Person.has(id)).to.be.true }) }) it('should create a write transaction', async function () { const Person = setupCollection() const person = copyPerson() await Person.writeTransaction(async function () { const [id] = await Person.insert(person) expect(await Person.has(id)).to.be.true }) }) }) describe('checking for entities', () => { it('should test for existing entity', async function () { const Person = setupCollection() const person = copyPerson() const [id1] = await Person.insert(person) expect(await Person.has(id1)).to.be.true expect(await Person.has('blah')).to.be.false const person2 = copyPerson() const [id2] = await Person.insert(person2) expect(await Person.has(id2)).to.be.true await Person.delete(id2) expect(await Person.has(id2)).to.be.false // Test exists from instance const [id3] = await Person.insert(person2) const personInstance = await Person.findById(id3) if (personInstance) { expect(await personInstance.exists()).to.equal(true) await personInstance.remove() expect(await personInstance.exists()).to.equal(false) } else { throw new Error('should not be undefined') } }) it('should test for multiple entities', async function () { const Person = setupCollection() const persons = [copyPerson(), copyPerson(), copyPerson()] const ids = await Person.insert(...persons) expect( await Promise.all(ids.map((id) => Person.has(id))), ).to.deep.equal([true, true, true]) expect( await Promise.all(['foo', 'bar', 'baz'].map((p) => Person.has(p))), ).to.deep.equal([false, false, false]) }) }) describe('returning entities', () => { it('should get existing entity', async function () { const Person = setupCollection() const person = copyPerson() const [id] = await Person.insert(person) let found = await Person.findById(id) expect(found).to.deep.equal(person) found = await Person.findById('blah') expect(found).to.be.undefined }) it('should get multiple entities', async function () { const Person = setupCollection() const persons = [copyPerson(), copyPerson(), copyPerson()] const ids = await Person.insert(...persons) expect( await Promise.all(ids.map((id) => Person.findById(id))), ).to.deep.equal(persons) const founds = await Promise.all( ['foo', 'bar', 'baz'].map((p) => Person.findById(p)), ) expect(founds.every((found) => found === undefined)).to.be.true }) }) describe('type checking entities', () => { it('should correctly handle typed entities', async function () { const Person = new Collection<Person>(db.table('Person')) const person = copyPerson() const typed = Person.create(person) expect(typed.age).to.equal(person.age) expect(typed.name).to.equal(person.name) expect(typed._id).to.not.be.undefined // Also works with unknown const Unknown = new Collection( db.table('Person'), // Reuse Person table... ) // We can create an empty object of unknown type const empty = Unknown.create() // This is a method from Instance expect(empty.exists).to.not.be.undefined // This is a default _id expect(empty._id).to.not.be.undefined }) }) describe('exporting entities', () => { it('should export entity to JSON string', async function () { const Person = setupCollection() const person = copyPerson() const [id] = await Person.insert(person) const test = await Person.has(id) expect(test).to.be.true const personInstance = await Person.findById(id) // Should be an actual class instance, that we can export to JSON if (personInstance) { const json = personInstance.toJSON() expect(json).to.deep.equal(person) } else { throw new Error('should not be undefined') } }) }) describe('deleting entities', () => { it('should delete existing entity', async function () { const Person = setupCollection() const person = copyPerson() let [id] = await Person.insert(person) expect(await Person.has(id)).to.be.true await Person.delete(id) expect(await Person.has(id)).to.be.false await Person.delete('blah') // Should not throw here, fails gracefully await Person.save(person) expect(await Person.has(id)).to.be.true await Person.delete(id) expect(await Person.has(id)).to.be.false // Test remove from instance ;[id] = await Person.insert(person) expect(await Person.has(id)).to.equal(true) const personInstance = await Person.findById(id) if (personInstance) { await personInstance.remove() expect(await Person.has(id)).to.equal(false) } else { throw new Error('should not be undefined') } }) it('should delete multiple entities', async function () { const Person = setupCollection() const persons = [copyPerson(), copyPerson(), copyPerson()] const ids = await Person.insert(...persons) expect( await Promise.all(ids.map((id) => Person.has(id))), ).to.deep.equal([true, true, true]) await Person.delete(...ids) expect( await Promise.all(ids.map((p) => Person.has(p))), ).to.deep.equal([false, false, false]) await Person.delete('foo', 'bar', 'baz') // Should not error }) it('should delete all entities', async function () { // TODO: We don't support deleteRange for our track changes yet... const Person = setupCollection() await Person.writeTransaction(async function () { const person = copyPerson() await Person.insert(person) }) expect(await Person.find().count()).to.equal(1) // Closer checking into deleting things // const changes = db.table(ChangeTableName); // const beforeClear = await changes.count(); // Delete all entities from Person collection await Person.clear() // Alternative to find() above... directly counting all instances expect(await Person.count()).to.equal(0) // Buuuut, this doesn't yet lead to any changes being recorded // expect(await changes.count()).to.be.greaterThan(beforeClear); }) }) describe('saving entities', () => { it('should save/update existing entity', async function () { const Person = setupCollection() const person = copyPerson() const [id] = await Person.save(person) person.name = 'Mod' await Person.save(person) expect(await Person.findById(id)).to.haveOwnProperty('name', 'Mod') // Test save from instance const personInstance = await Person.findById(id) if (personInstance) { personInstance.age = 99 await personInstance.save() expect(await Person.findById(id)).to.haveOwnProperty('age', 99) } else { throw new Error('should not be undefined') } }) it('should save/update multiple entities', async function () { const Person = setupCollection() const persons = [copyPerson(), copyPerson(), copyPerson()] await Person.insert(...persons) persons.forEach((p) => p.age++) await Person.save(...persons) const array = await Person.find({}).toArray((data) => data.map(({ age }) => age), ) expect(array).to.deep.equal([8, 8, 8]) }) it('should also save/update a non-existent entity', async function () { const Person = setupCollection() await Person.save({ name: 'nothing', age: 55 }) expect(await Person.find().count()).to.equal(1) }) }) describe('find/search', () => { it('should support finding one result at a time', async function () { const Person = setupCollection() const people: Person[] = [ { name: 'Lucas', age: 7 }, { name: 'Clyde', age: 99 }, { name: 'Duke', age: 2 }, ] await Person.insert(...people) const query = { // Query for everyone over the age of 5 age: { $gt: 5 }, } // But only "find" one of them... const result = await Person.findOne(query) expect(result).to.not.be.undefined expect(result).to.have.ownProperty('age') expect(result?.age).to.be.greaterThan(5) }) it('should support simple queries', async function () { const Person = setupCollection() const people: Person[] = [ { name: 'Lucas', age: 7 }, { name: 'Clyde', age: 99 }, { name: 'Duke', age: 2 }, ] await Person.insert(...people) const query = { // Find everyone over the age of 5 age: { $gt: 5 }, } const results = Person.find(query) expect(await results.count()).to.equal(2) const last = await results.last() // Should we 'unravel' the key/value pairs here? expect(last).to.have.ownProperty('age') expect(last?.age).to.be.greaterThan(5) }) it('should support complex queries', async function () { const Person = setupCollection() const people: Person[] = [ { name: 'Lucas', age: 56 }, { name: 'Clyde', age: 55 }, { name: 'Mike', age: 52 }, { name: 'Micheal', age: 52 }, { name: 'Duke', age: 2 }, { name: 'Michelle', age: 2 }, { name: 'Michelangelo', age: 55 }, ] await Person.insert(...people) const query: Query<Person> = { // Find people who are older than 5, and younger than 56, ... // but don't include Michael, he's a jerk... $and: [ { age: { $gt: 5 } }, { age: { $lt: 56 } }, { name: { $not: { $eq: 'Micheal' } } }, ], } const results = Person.find(query) expect(await results.count()).to.equal(3) const last = await results.last() expect(last).to.have.ownProperty('age') expect(last?.age).to.be.greaterThan(5) expect(last?.age).to.be.lessThan(56) expect(await Person.find().count()).to.equal(7) }) }) describe('read transaction', () => { it('should test for existing entity', async function () { const Person = setupCollection() const person = copyPerson() const [id] = await Person.save(person) await Person.readTransaction(async function () { expect(await Person.has(id)).to.be.true }) }) it('should return existing entity', async function () { const Person = setupCollection() const person = copyPerson() const [id] = await Person.save(person) await Person.readTransaction(async function () { const found = await Person.findById(id) expect(found).to.deep.equal(person) // await Person.insert(person); // Compiler won't let us! }) }) it('should support nested transactions, but no writes inside a read transaction', async function () { const Person = setupCollection() const person = copyPerson() await Person.save(person) try { await Person.readTransaction(async function () { // Note that dexie actually console.logs the exception here, which is annoying :shrug: // But the test is still "passing"... await Person.writeTransaction(async function () { return Person.insert(person) }) throw shouldHaveThrown }) } catch (err) { expect(err).to.not.equal(shouldHaveThrown) } }) }) describe('write transaction', () => { it('should perform normal write operations', async function () { const Person = setupCollection() await Person.writeTransaction(async function () { const person = copyPerson() const [id] = await Person.insert(person) expect(await Person.find().count()).to.equal(1) return Person.delete(id) }) expect(await Person.find().count()).to.equal(0) }) it('should allow read transactions inside write transactions', (done) => { const Person = setupCollection() const person = copyPerson() Person.save(person).then(([id]) => { Person.writeTransaction(async function () { const found = await Person.readTransaction(async function () { return Person.findById(id) }) expect(found).to.not.be.undefined }).then(done) }) }).timeout(5000) }) }) }) })
the_stack
import Vue from 'vue' // Utils import mixins, { ExtractVue } from '@/utils/mixins' import { isDef } from '@/utils' import { raf } from '@/utils/raf' import { off, on } from '@/utils/event' import { getElementTop, getScrollEventTarget, getScrollTop, setScrollTop } from '@/utils/scroll' // Mixins import Touchable from '@/mixins/touchable' import WTab from '../WTab' type WTabInstance = InstanceType<typeof WTab> interface options extends Vue { $el: HTMLElement $refs: { wrap: HTMLElement title: HTMLElement[] nav: HTMLElement tabs: WTabInstance[] content: HTMLElement } } export default mixins<options & ExtractVue<[typeof Touchable]> >( Touchable ).extend({ name: 'w-tabs', model: { prop: 'active', }, props: { sticky: Boolean, swipeable: Boolean, animated: Boolean, color: String, background: String, titleActiveColor: String, titleInactiveColor: String, ellipsis: { type: Boolean, default: true, }, lineWidth: { type: Number, default: null, }, lineHeight: { type: Number, default: null, }, active: { type: [Number, String], default: 0, }, type: { type: String, default: 'line', }, duration: { type: Number, default: 0.2, }, swipeThreshold: { type: Number, default: 4, }, offsetTop: Number, }, data () { return { inited: false, tabs: [] as WTabInstance[], position: '' as string, currentActive: 0 as number, lineStyle: { backgroundColor: this.color, } as object, events: { resize: false, sticky: false, swipeable: false, }, } }, computed: { // whether the nav is scrollable scrollable (): boolean { return this.tabs.length > this.swipeThreshold || !this.ellipsis }, wrapStyle (): object | null { switch (this.position) { case 'top': return { top: this.offsetTop + 'px', position: 'fixed', } case 'bottom': return { top: 'auto', bottom: 0, } default: return null } }, navStyle (): object { return { borderColor: this.color, background: this.background, } }, }, watch: { active (val) { if (val !== this.currentActive) { this.correctActive(val) } }, color () { this.setLine() }, tabs () { this.correctActive(this.currentActive || this.active) this.scrollIntoView() this.setLine() }, currentActive () { this.scrollIntoView() this.setLine() // scroll to correct position if (this.position === 'top' || this.position === 'bottom') { setScrollTop(window, getElementTop(this.$el)) } }, sticky () { this.handlers(true) }, swipeable () { this.handlers(true) }, }, mounted () { this.onShow() }, /* istanbul ignore next */ activated () { this.onShow() }, /* istanbul ignore next */ deactivated () { this.handlers(false) }, beforeDestroy () { this.handlers(false) }, methods: { onShow (): void { this.$nextTick(() => { this.inited = true this.handlers(true) this.scrollIntoView(true) }) }, // whether to bind sticky listener handlers (bind: boolean): void { const { events } = this const sticky = this.sticky && bind const swipeable = this.swipeable && bind // listen to window resize event if (events.resize !== bind) { events.resize = bind ;(bind ? on : off)(window, 'resize', this.setLine, true) } // listen to scroll event if (events.sticky !== sticky) { events.sticky = sticky const scrollEl = getScrollEventTarget(this.$el) ;(sticky ? on : off)(scrollEl, 'scroll', this.onScroll, true) this.onScroll() } // listen to touch event if (events.swipeable !== swipeable) { events.swipeable = swipeable const { content } = this.$refs const action = swipeable ? on : off action(content, 'touchstart', this.touchStart as EventListener) action(content, 'touchmove', this.touchMove as EventListener) action(content, 'touchend', this.onTouchend) action(content, 'touchcancel', this.onTouchend) } }, // watch swipe touch end onTouchend (): void { const { direction, deltaX, currentActive } = this const minSwipeDistance = 50 /* istanbul ignore else */ if (direction === 'horizontal' && this.offsetX >= minSwipeDistance) { if (deltaX > 0 && currentActive !== 0) { this.setCurActive(currentActive - 1) } else if (deltaX < 0 && currentActive !== this.tabs.length - 1) { this.setCurActive(currentActive + 1) } } }, // adjust tab position onScroll (): void { const scrollTop = getScrollTop(window) + this.offsetTop const elTopToPageTop = getElementTop(this.$el) const elBottomToPageTop = elTopToPageTop + this.$el.offsetHeight - this.$refs.wrap.offsetHeight if (scrollTop > elBottomToPageTop) { this.position = 'bottom' } else if (scrollTop > elTopToPageTop) { this.position = 'top' } else { this.position = '' } }, // update nav bar style setLine (): void { this.$nextTick(() => { const { tabs } = this.$refs if (!tabs || !tabs[this.currentActive] || this.type !== 'line') { return } const tab = tabs[this.currentActive] as HTMLElement const { lineWidth, lineHeight } = this const width = isDef(lineWidth) ? lineWidth : tab.offsetWidth const left = tab.offsetLeft + (tab.offsetWidth - width) / 2 const lineStyle = { width: `${width}px`, backgroundColor: this.color, transform: `translateX(${left}px)`, transitionDuration: `${this.duration}s`, } as any if (isDef(lineHeight)) { lineStyle.height = `${lineHeight}px` lineStyle.borderRadius = `${lineHeight}px` } this.lineStyle = lineStyle }) }, // correct the value of active correctActive (active: number | string): void { active = +active const exist = this.tabs.some(tab => tab.index === active) const defaultActive = (this.tabs[0] || {}).index || 0 this.setCurActive(exist ? active : defaultActive) }, setCurActive (active: number): void { active = this.findAvailableTab(active, active < this.currentActive) if (active !== this.currentActive) { this.$emit('input', active) if (this.currentActive !== null) { this.$emit('change', active, this.tabs[active].title) } this.currentActive = active } }, findAvailableTab (active: number, reverse: boolean): number { const diff = reverse ? -1 : 1 let index: number = active while (index >= 0 && index < this.tabs.length) { if (!this.tabs[index].disabled) { return index } index += diff } return index }, // emit event when clicked onClick (index: number): void { const { title, disabled } = this.tabs[index] if (disabled) { this.$emit('disabled', index, title) } else { this.setCurActive(index) this.$emit('click', index, title) } }, // scroll active tab into view scrollIntoView (immediate = false): void { if (!this.scrollable || !this.$refs.tabs) { return } const tab = this.$refs.tabs[this.currentActive] const { nav } = this.$refs const { scrollLeft, offsetWidth: navWidth } = nav const { offsetLeft, offsetWidth: tabWidth } = tab as HTMLElement this.scrollTo( nav, scrollLeft, offsetLeft - (navWidth - tabWidth) / 2, immediate ) }, // animate the scrollLeft of nav scrollTo (el: HTMLElement, from: number, to: number, immediate: boolean): void { if (immediate) { el.scrollLeft += to - from return } let count = 0 const frames = Math.round((this.duration * 1000) / 16) const animate = () => { el.scrollLeft += (to - from) / frames /* istanbul ignore next */ if (++count < frames) { raf(animate) } } animate() }, // render title slot of child tab renderTitle (el: HTMLElement, index: number): void { this.$nextTick(() => { const title: Element = this.$refs.title[index] title.parentNode && title.parentNode.replaceChild(el, title) }) }, getTabStyle (item: WTabInstance, index: number): object { const style = {} as any const { color } = this const active = index === this.currentActive const isCard = this.type === 'card' if (color && isCard) { style.borderColor = color if (!item.disabled && !active) { style.color = color } else if (!item.disabled && active) { style.backgroundColor = color } } const titleColor = active ? this.titleActiveColor : this.titleInactiveColor if (titleColor) { style.color = titleColor } return style }, }, render () { const { type, scrollable } = this const Nav = this.tabs.map((tab, index) => ( <div key={index} ref="tabs" refInFor class={{ 'wv-tab': true, 'wv-tab--active': index === this.currentActive, 'wv-tab--disabled': tab.disabled, }} style={this.getTabStyle(tab, index)} onClick={() => { this.onClick(index) }} > <span class="wv-ellipsis" ref="title" refInFor> { tab.title } </span> </div> )) return ( <div class={[ 'wv-tabs', `wv-tabs--${type}`, ]} > <div ref="wrap" style={this.wrapStyle} class={{ 'wv-tabs__wrap': true, 'wv-tabs__wrap--scrollable': scrollable, 'wv-hairline--top-bottom': type === 'line', }} > <div ref="nav" class={[ 'wv-tabs__nav', `wv-tabs__nav--${type}`, ]} style={this.navStyle} > {type === 'line' && <div class="wv-tabs__line" style={this.lineStyle} /> } {Nav} </div> </div> <div class="wv-tabs__content" ref="content"> {this.$slots.default} </div> </div> ) }, })
the_stack
import { member } from "babyioc"; import { Maps as EightBittrMaps } from "eightbittr"; import { Area as MapsCreatrArea, AreaRaw as MapsCreatrAreaRaw, Location as MapsCreatrLocation, LocationRaw as MapsCreatrLocationRaw, Map as MapsCreatrMap, MapRaw as MapsCreatrMapRaw, PreActorLike as MapsCreatrPreActorLike, PreActorsContainers, } from "mapscreatr"; import { MapScreenr as EightBittrMapScreenr } from "mapscreenr"; import { PalletTown } from "../creators/mapsLibrary/PalletTown"; import { PewterCity } from "../creators/mapsLibrary/PewterCity"; import { Route1 } from "../creators/mapsLibrary/Route1"; import { Route2 } from "../creators/mapsLibrary/Route2"; import { Route21 } from "../creators/mapsLibrary/Route21"; import { Route22 } from "../creators/mapsLibrary/Route22"; import { ViridianCity } from "../creators/mapsLibrary/ViridianCity"; import { ViridianForest } from "../creators/mapsLibrary/ViridianForest"; import { FullScreenPokemon } from "../FullScreenPokemon"; import { Direction } from "./Constants"; import { EntranceAnimations } from "./maps/EntranceAnimations"; import { MapMacros } from "./maps/MapMacros"; import { StateSaveable } from "./Saves"; import { AreaGate, AreaSpawner, Player, Actor } from "./Actors"; /** * A flexible container for map attributes and viewport. */ export interface MapScreenr extends EightBittrMapScreenr { /** * Which are the player is currently active in. * * @todo Consider moving this into EightBittr core. */ activeArea: Area; /** * Whether user inputs should be ignored. */ blockInputs: boolean; /** * The currently playing cutscene, if any. */ cutscene?: string; /** * What theme is currently playing. */ theme?: string; /** * Known variables, keyed by name. */ variables: { /** * Whether the current Area allows bicycling. */ allowCycling?: boolean; /** * The current size of the areAn Actors are placed in. */ boundaries: AreaBoundaries; /** * What form of scrolling is currently capable on the screen. */ scrollability: number; }; } /** * A raw JSON-friendly description of a map. */ export interface MapRaw extends MapsCreatrMapRaw { /** * A listing of areas in the Map, keyed by name. */ areas: { [i: number]: AreaRaw; [i: string]: AreaRaw; }; /** * The default location for the Map. */ locationDefault: number | string; /** * Descriptions of locations in the map. */ locations: { [i: number]: LocationRaw; [i: string]: LocationRaw; }; /** * A starting seed to initialize random number generation. */ seed?: number | number[]; /** * What theme to play by default, such as "Pallet Town". */ theme?: string; } /** * A Map parsed from its raw JSON-friendly description. */ export interface Map extends StateSaveable, MapsCreatrMap { /** * A listing of areas in the Map, keyed by name. */ areas: { [i: string]: Area; [i: number]: Area; }; /** * The name of the Map, such as "Pallet Town". */ name: string; /** * The default location for the Map. */ locationDefault?: string; /** * A starting seed to initialize random number generation. */ seed: number | number[]; /** * What theme to play by default, such as "Pallet Town". */ theme: string; } /** * A raw JSON-friendly description of a map area. */ export interface AreaRaw extends MapsCreatrAreaRaw { /** * Whether the Area allows bicycling. */ allowCycling?: boolean; /** * Any additional attributes that should add extra properties to this Area. */ attributes?: { [i: string]: any; }; /** * What background to display behind all Actors. */ background?: string; /** * How tall the area is. * @todo It's not clear if this is different from boundaries.height. */ height?: number; /** * Whether the area should have invisible borders added around it. */ invisibleWallBorders?: boolean; /** * A default theme to override the parent Map's. */ theme?: string; /** * How wide the area is. * @todo It's not clear if this is different from boundaries.width. */ width?: number; /** * Wild Pokemon that may appear in this Area. */ wildPokemon?: AreaWildPokemonOptionGroups; } /** * An Area parsed from a raw JSON-friendly Area description. */ export interface Area extends AreaRaw, StateSaveable, MapsCreatrArea { /** * Whether the Area allows bicycling. */ allowCycling: boolean; /** * What background to display behind all Actors. */ background: string; /** * In-game boundaries of all placed Actors. */ boundaries: AreaBoundaries; /** * The Map this Area is within. */ map: Map; /** * Whether this Area has been spawned. */ spawned: boolean; /** * Which Map spawned this Area and when. */ spawnedBy: AreaSpawnedBy; /** * Whether the Player has encountered a Pokemon in this area's grass. */ pokemonEncountered?: boolean; /** * Wild Pokemon that may appear in this Area. */ wildPokemon?: AreaWildPokemonOptionGroups; } /** * A description of how an Area has been stretched by its placed Actors. */ export interface AreaBoundaries { /** * How wide the Area is. */ width: number; /** * How tall the Area is. */ height: number; /** * The top border of the boundaries' bounding box. */ top: number; /** * The right border of the boundaries' bounding box. */ right: number; /** * The bottom border of the boundaries' bounding box. */ bottom: number; /** * The left border of the boundaries' bounding box. */ left: number; } /** * A description of which Map spawned an Area and when. */ export interface AreaSpawnedBy { /** * The name of the Map that spawned the Area. */ name: string; /** * When the spawning occurred. */ timestamp: number; } /** * Types of Pokemon that may appear in an Area, keyed by terrain type, such as "grass". */ export interface AreaWildPokemonOptionGroups { /** * Types of Pokemon that may appear in grass. */ grass?: WildPokemonSchema[]; /** * Types of Pokemon that may appear while fishing. */ fishing?: WildFishingPokemon; /** * Types of Pokemon that may appear while surfing. */ surfing?: WildPokemonSchema[]; /** * Types of Pokemon that may appear while walking. */ walking?: WildPokemonSchema[]; } /** * A description of a type of Pokemon that may appear in an Area. */ export interface WildPokemonSchemaBase { /** * The type of Pokemon. */ title: string[]; /** * Concatenated names of moves the Pokemon should have. */ moves?: string[]; /** * The rate of appearance for this type of Pokemon, in [0, 1]. */ rate?: number; } /** * A wild Pokemon description with only one possible level. */ export interface WildPokemonSchemaWithLevel extends WildPokemonSchemaBase { /** * What level the Pokemon may be. */ level: number; } /** * A wild Pokemon description with multiple possible levels. */ export interface WildPokemonSchemaWithLevels extends WildPokemonSchemaBase { /** * What levels the Pokemon may be. */ levels: number[]; } export type WildPokemonSchema = WildPokemonSchemaWithLevel | WildPokemonSchemaWithLevels; /** * A raw JSON-friendly description of a location. */ export interface LocationRaw extends MapsCreatrLocationRaw { /** * A cutscene to immediately start upon entering. */ cutscene?: string; /** * A direction to immediately face the player towards. */ direction?: number; /** * Whether the player should immediately walk forward. */ push?: boolean; /** * A cutscene routine to immediately start upon entering. */ routine?: string; /** * A theme to immediately play upon entering. */ theme?: string; /** * The x-location in the parent Area. */ xloc?: number; /** * The y-location in the parent Area. */ yloc?: number; } /** * A Location parsed from a raw JSON-friendly Map description. */ export interface Location extends StateSaveable, MapsCreatrLocation { /** * The Area this Location is a part of. */ area: Area; /** * A cutscene to immediately start upon entering. */ cutscene?: string; /** * A direction to immediately face the player towards. */ direction?: number; /** * Whether the player should immediately walk forward. */ push?: boolean; /** * A cutscene routine to immediately start upon entering. */ routine?: string; /** * A theme to immediately play upon entering. */ theme?: string; /** * The x-location in the parent Area. */ xloc?: number; /** * The y-location in the parent Area. */ yloc?: number; } /** * The types of Pokemon that can be caught with different rods. */ export interface WildFishingPokemon { /** * The Pokemon that can be caught using an Old Rod. */ old?: WildPokemonSchema[]; /** * The Pokemon that can be caught using a Good Rod. */ good?: WildPokemonSchema[]; /** * The Pokemon that can be caught using a Super Rod. */ super?: WildPokemonSchema[]; } /** * A position holder around an in-game Actor. */ export interface PreActorLike extends MapsCreatrPreActorLike { /** * A starting direction to face (by default, up). */ direction?: number; /** * The in-game Actor. */ actor: Actor; /** * The raw x-location from the Area's creation command. */ x: number; /** * The raw y-location from the Area's creation command. */ y: number; /** * How wide the Actor should be. */ width?: number; /** * How tall the Actor should be. */ height: number; } /** * Enters and spawns map areas. */ export class Maps<Game extends FullScreenPokemon> extends EightBittrMaps<Game> { /** * Map entrance animations. */ @member(EntranceAnimations) public readonly entranceAnimations!: EntranceAnimations; /** * Map creation macros. */ @member(MapMacros) public readonly mapMacros!: MapMacros; /** * Entrance Functions that may be used as the openings for Locations. */ public readonly entrances = { Blank: this.entranceAnimations.blank, Normal: this.entranceAnimations.normal, }; /** * Macros that can be used to automate common operations. */ public readonly macros = { Checkered: this.mapMacros.macroCheckered, Water: this.mapMacros.macroWater, House: this.mapMacros.macroHouse, HouseLarge: this.mapMacros.macroHouseLarge, Building: this.mapMacros.macroBuilding, Gym: this.mapMacros.macroGym, Mountain: this.mapMacros.macroMountain, PokeCenter: this.mapMacros.macroPokeCenter, PokeMart: this.mapMacros.macroPokeMart, }; public readonly maps = { Blank: { name: "Blank", locationDefault: "Black", locations: { Black: { area: "Black", entry: "Blank", }, White: { area: "White", entry: "Blank", }, }, areas: { Black: { creation: [], }, White: { background: "white", creation: [], }, }, }, "Pallet Town": PalletTown, "Pewter City": PewterCity, "Route 1": Route1, "Route 2": Route2, "Route 21": Route21, "Route 22": Route22, "Viridian City": ViridianCity, "Viridian Forest": ViridianForest, }; /** * Property names to copy from Areas to the MapScreenr during setLocation. */ public readonly screenAttributes = ["allowCycling"]; /** * Processes additional Actor attributes. For each attribute the Area's * class says it may have, if it has it, the attribute value proliferated * onto the Area. * * @param area The Area being processed. */ public areaProcess = (area: Area): void => { const attributes: { [i: string]: any } | undefined = area.attributes; if (!attributes) { return; } for (const attribute in attributes) { if ((area as any)[attribute]) { this.game.utilities.proliferate(area, attributes[attribute]); } } }; /** * Adds An Actor via addPreActor based on the specifications in a PreActor. * This is done relative to MapScreener.left and MapScreener.top. * * @param preactor A PreActor whose Actor is to be added to the game. */ public addPreActor = (preactor: PreActorLike): void => { const actor: Actor = preactor.actor; const position: string = preactor.position || actor.position; if (actor.spawned) { return; } actor.spawned = true; actor.areaName = actor.areaName || this.game.areaSpawner.getAreaName(); actor.mapName = actor.mapName || this.game.areaSpawner.getMapName(); this.game.actors.add( actor, preactor.left - this.game.mapScreener.left, preactor.top - this.game.mapScreener.top, true ); // Either the preactor or actor, in that order, may request to be in the // front or back of the container if (position) { this.game.timeHandler.addEvent((): void => { switch (position) { case "beginning": this.game.utilities.arrayToBeginning( actor, this.game.groupHolder.getGroup(actor.groupType) ); break; case "end": this.game.utilities.arrayToEnd( actor, this.game.groupHolder.getGroup(actor.groupType) ); break; default: throw new Error("Unknown position: " + position + "."); } }); } this.game.modAttacher.fireEvent(this.game.mods.eventNames.onAddPreActor, preactor); }; /** * Adds a new Player Actor to the game and sets it as eightBitter.player. Any * required additional settings (namely keys, power/size, and swimming) are * applied here. * * @param left A left edge to place the Actor at (by default, 0). * @param bottom A top to place the Actor upon (by default, 0). * @param useSavedInfo Whether an Area's saved info in StateHolder should be * applied to the Actor's position (by default, false). * @returns A newly created Player in the game. */ public addPlayer(left = 0, top = 0, useSavedInfo?: boolean): Player { const player: Player = this.game.objectMaker.make<Player>(this.game.actors.names.player); player.keys = player.getKeys(); this.game.players[0] = player; this.game.actors.add(player, left || 0, top || 0, useSavedInfo); this.game.modAttacher.fireEvent(this.game.mods.eventNames.onAddPlayer, player); return player; } /** * Sets the game state to a new Map, resetting all Actors and inputs in the * process. The mod events are fired. * * @param name The name of the Map. * @param location The name of the Location within the Map. * @param noEntrance Whether or not an entry Function should * be skipped (by default, false). * @remarks Most of the work here is done by setLocation. */ public setMap(name: string, location?: string, noEntrance?: boolean): Location { if (!name) { name = this.game.areaSpawner.getMapName(); } const map: Map = this.game.areaSpawner.setMap(name) as Map; this.game.modAttacher.fireEvent(this.game.mods.eventNames.onPreSetMap, map); this.game.numberMaker.resetFromSeed(map.seed); this.game.modAttacher.fireEvent(this.game.mods.eventNames.onSetMap, map); return this.setLocation(location || map.locationDefault || "Blank", noEntrance); } /** * Sets the game state to a Location within the current map, resetting all * Actors, inputs, the current Area, PixelRender, and MapScreener in the * process. The Location's entry Function is called to bring a new Player * into the game if specified. The mod events are fired. * * @param name The name of the Location within the Map. * @param noEntrance Whether an entry function should be skipped (by default, false). * @todo Separate external module logic to their equivalent components then * pass them as an onPreSetLocation/onSetLocation here to reduce dependencies. */ public setLocation(name: string, noEntrance?: boolean): Location { this.game.groupHolder.clear(); this.game.mapScreener.clearScreen(); this.game.menuGrapher.deleteAllMenus(); this.game.timeHandler.cancelAllEvents(); this.game.areaSpawner.setLocation(name); this.game.mapScreener.setVariables(); const location: Location = this.game.areaSpawner.getLocation(name) as Location; location.area.spawnedBy = { name, timestamp: new Date().getTime(), }; this.game.mapScreener.activeArea = location.area; this.game.modAttacher.fireEvent(this.game.mods.eventNames.onPreSetLocation, location); this.game.pixelDrawer.setBackground((this.game.areaSpawner.getArea() as Area).background); if (location.area.map.name !== "Blank") { this.game.itemsHolder.setItem(this.game.storage.names.map, location.area.map.name); this.game.itemsHolder.setItem(this.game.storage.names.area, location.area.name); this.game.itemsHolder.setItem(this.game.storage.names.location, name); } this.setStateCollection(location.area); this.game.quadsKeeper.resetQuadrants(); const theme: string = location.theme || location.area.theme || location.area.map.theme; this.game.mapScreener.theme = theme; if (theme && !this.game.audioPlayer.hasSound(this.game.audio.aliases.theme, theme)) { this.game.audioPlayer.play(theme, { alias: this.game.audio.aliases.theme, loop: true, }); } if (!noEntrance && location.entry) { location.entry.call(this, location); } this.game.modAttacher.fireEvent(this.game.mods.eventNames.onSetLocation, location); this.game.frameTicker.play(); this.game.animations.fading.animateFadeFromColor({ color: "Black", }); if (location.push) { this.game.actions.walking.startWalkingOnPath(this.game.players[0], [ { blocks: 1, direction: this.game.players[0].direction, }, (): void => this.game.saves.autoSaveIfEnabled(), ]); } return location; } /** * Analyzes a PreActor to be placed in one of the * cardinal directions of the current Map's boundaries * (just outside of the current Area). * * @param preactor A PreActor whose Actor is to be added to the game. * @param direction The cardinal direction the Character is facing. * @remarks Direction is taken in by the .forEach call as the index. */ public addAfter = (preactor: PreActorLike, direction: Direction): void => { const preactors: any = this.game.areaSpawner.getPreActors(); const area: Area = this.game.areaSpawner.getArea() as Area; const map: Map = this.game.areaSpawner.getMap() as Map; const boundaries: AreaBoundaries = this.game.areaSpawner.getArea() .boundaries as AreaBoundaries; preactor.direction = direction; switch (direction) { case Direction.Top: preactor.x = boundaries.left; preactor.y = boundaries.top - 32; preactor.width = boundaries.right - boundaries.left; break; case Direction.Right: preactor.x = boundaries.right; preactor.y = boundaries.top; preactor.height = boundaries.bottom - boundaries.top; break; case Direction.Bottom: preactor.x = boundaries.left; preactor.y = boundaries.bottom; preactor.width = boundaries.right - boundaries.left; break; case Direction.Left: preactor.x = boundaries.left - 32; preactor.y = boundaries.top; preactor.height = boundaries.bottom - boundaries.top; break; default: throw new Error(`Unknown direction: '${direction}'.`); } this.game.mapsCreator.analyzePreSwitch(preactor, preactors, area, map); }; /** * Runs an areaSpawner to place its Area's Actors in the map. * * @param actor An in-game areaSpawner. * @param area The Area associated with actor. */ public activateAreaSpawner(actor: AreaSpawner, area: Area): void { const direction: Direction = actor.direction; const areaCurrent: Area = this.game.areaSpawner.getArea() as Area; const mapCurrent: Map = this.game.areaSpawner.getMap() as Map; const preactorsCurrent: PreActorsContainers = this.game.areaSpawner.getPreActors(); let left: number = actor.left + this.game.mapScreener.left; let top: number = actor.top + this.game.mapScreener.top; switch (direction) { case Direction.Top: top -= area.height!; break; case Direction.Right: left += actor.width; break; case Direction.Bottom: top += actor.height; break; case Direction.Left: left -= area.width!; break; default: throw new Error(`Unknown direction: '${direction}'.`); } const x: number = left + (actor.offsetX || 0); const y: number = top + (actor.offsetY || 0); this.game.scrolling.expandMapBoundariesForArea(area, x, y); for (const creation of area.creation) { // A copy of the command must be used, so as to not modify the original const command: any = this.game.utilities.proliferate( { noBoundaryStretch: true, areaName: area.name, mapName: area.map.name, }, creation ); command.x = (command.x || 0) + x; command.y = (command.y || 0) + y; // Having an entrance might conflict with previously set Locations if ("entrance" in command) { delete command.entrance; } this.game.mapsCreator.analyzePreSwitch( command, preactorsCurrent, areaCurrent, mapCurrent ); } this.game.areaSpawner.spawnArea( this.game.constants.directionSpawns[direction], this.game.quadsKeeper.top, this.game.quadsKeeper.right, this.game.quadsKeeper.bottom, this.game.quadsKeeper.left ); this.game.maps.addAreaGate(actor, area, x, y); area.spawned = true; this.game.death.kill(actor); } /** * Adds an AreaGate on top of an areaSpawner. * * @param actor An areaSpawner that should have a gate. * @param area The Area to spawn into. * @param offsetX Horizontal spawning offset for the Area. * @param offsetY Vertical spawning offset for the Area. * @returns The added AreaGate. */ public addAreaGate(actor: AreaGate, area: Area, offsetX: number, offsetY: number): AreaGate { const properties: any = { area: actor.area, areaOffsetX: offsetX, areaOffsetY: offsetY, direction: actor.direction, height: 8, map: actor.map, width: 8, }; let left: number = actor.left; let top: number = actor.top; switch (actor.direction) { case Direction.Top: top -= this.game.constants.blockSize; properties.width = area.width; break; case Direction.Right: properties.height = area.height; break; case Direction.Bottom: properties.width = area.width; break; case Direction.Left: left -= this.game.constants.blockSize; properties.height = area.height; break; default: throw new Error(`Unknown direction: '${actor.direction}'.`); } return this.game.actors.add([this.game.actors.names.areaGate, properties], left, top); } /** * Sets the current StateHoldr collection to an area. * * @param area Area to store changes within. */ public setStateCollection(area: Area): void { this.game.stateHolder.setCollection(`${area.map.name}::${area.name}`); } }
the_stack
import * as coreHttp from "@azure/core-http"; import * as Parameters from "./models/parameters"; import * as Mappers from "./models/mappers"; import { GeneratedClientContext } from "./generatedClientContext"; import { GeneratedClientOptionalParams, GeneratedClientGetKeysOptionalParams, GeneratedClientGetKeysResponse, GeneratedClientCheckKeysOptionalParams, GeneratedClientCheckKeysResponse, GeneratedClientGetKeyValuesOptionalParams, GeneratedClientGetKeyValuesResponse, GeneratedClientCheckKeyValuesOptionalParams, GeneratedClientCheckKeyValuesResponse, GeneratedClientGetKeyValueOptionalParams, GeneratedClientGetKeyValueResponse, GeneratedClientPutKeyValueOptionalParams, GeneratedClientPutKeyValueResponse, GeneratedClientDeleteKeyValueOptionalParams, GeneratedClientDeleteKeyValueResponse, GeneratedClientCheckKeyValueOptionalParams, GeneratedClientCheckKeyValueResponse, GeneratedClientGetLabelsOptionalParams, GeneratedClientGetLabelsResponse, GeneratedClientCheckLabelsOptionalParams, GeneratedClientCheckLabelsResponse, GeneratedClientPutLockOptionalParams, GeneratedClientPutLockResponse, GeneratedClientDeleteLockOptionalParams, GeneratedClientDeleteLockResponse, GeneratedClientGetRevisionsOptionalParams, GeneratedClientGetRevisionsResponse, GeneratedClientCheckRevisionsOptionalParams, GeneratedClientCheckRevisionsResponse, GeneratedClientGetKeysNextOptionalParams, GeneratedClientGetKeysNextResponse, GeneratedClientGetKeyValuesNextOptionalParams, GeneratedClientGetKeyValuesNextResponse, GeneratedClientGetLabelsNextOptionalParams, GeneratedClientGetLabelsNextResponse, GeneratedClientGetRevisionsNextOptionalParams, GeneratedClientGetRevisionsNextResponse } from "./models"; /** @hidden */ export class GeneratedClient extends GeneratedClientContext { /** * Initializes a new instance of the GeneratedClient class. * @param endpoint The endpoint of the App Configuration instance to send requests to. * @param options The parameter options */ constructor(endpoint: string, options?: GeneratedClientOptionalParams) { super(endpoint, options); } /** * Gets a list of keys. * @param options The options parameters. */ getKeys( options?: GeneratedClientGetKeysOptionalParams ): Promise<GeneratedClientGetKeysResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getKeysOperationSpec ) as Promise<GeneratedClientGetKeysResponse>; } /** * Requests the headers and status of the given resource. * @param options The options parameters. */ checkKeys( options?: GeneratedClientCheckKeysOptionalParams ): Promise<GeneratedClientCheckKeysResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, checkKeysOperationSpec ) as Promise<GeneratedClientCheckKeysResponse>; } /** * Gets a list of key-values. * @param options The options parameters. */ getKeyValues( options?: GeneratedClientGetKeyValuesOptionalParams ): Promise<GeneratedClientGetKeyValuesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getKeyValuesOperationSpec ) as Promise<GeneratedClientGetKeyValuesResponse>; } /** * Requests the headers and status of the given resource. * @param options The options parameters. */ checkKeyValues( options?: GeneratedClientCheckKeyValuesOptionalParams ): Promise<GeneratedClientCheckKeyValuesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, checkKeyValuesOperationSpec ) as Promise<GeneratedClientCheckKeyValuesResponse>; } /** * Gets a single key-value. * @param key The key of the key-value to retrieve. * @param options The options parameters. */ getKeyValue( key: string, options?: GeneratedClientGetKeyValueOptionalParams ): Promise<GeneratedClientGetKeyValueResponse> { const operationArguments: coreHttp.OperationArguments = { key, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getKeyValueOperationSpec ) as Promise<GeneratedClientGetKeyValueResponse>; } /** * Creates a key-value. * @param key The key of the key-value to create. * @param options The options parameters. */ putKeyValue( key: string, options?: GeneratedClientPutKeyValueOptionalParams ): Promise<GeneratedClientPutKeyValueResponse> { const operationArguments: coreHttp.OperationArguments = { key, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, putKeyValueOperationSpec ) as Promise<GeneratedClientPutKeyValueResponse>; } /** * Deletes a key-value. * @param key The key of the key-value to delete. * @param options The options parameters. */ deleteKeyValue( key: string, options?: GeneratedClientDeleteKeyValueOptionalParams ): Promise<GeneratedClientDeleteKeyValueResponse> { const operationArguments: coreHttp.OperationArguments = { key, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, deleteKeyValueOperationSpec ) as Promise<GeneratedClientDeleteKeyValueResponse>; } /** * Requests the headers and status of the given resource. * @param key The key of the key-value to retrieve. * @param options The options parameters. */ checkKeyValue( key: string, options?: GeneratedClientCheckKeyValueOptionalParams ): Promise<GeneratedClientCheckKeyValueResponse> { const operationArguments: coreHttp.OperationArguments = { key, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, checkKeyValueOperationSpec ) as Promise<GeneratedClientCheckKeyValueResponse>; } /** * Gets a list of labels. * @param options The options parameters. */ getLabels( options?: GeneratedClientGetLabelsOptionalParams ): Promise<GeneratedClientGetLabelsResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getLabelsOperationSpec ) as Promise<GeneratedClientGetLabelsResponse>; } /** * Requests the headers and status of the given resource. * @param options The options parameters. */ checkLabels( options?: GeneratedClientCheckLabelsOptionalParams ): Promise<GeneratedClientCheckLabelsResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, checkLabelsOperationSpec ) as Promise<GeneratedClientCheckLabelsResponse>; } /** * Locks a key-value. * @param key The key of the key-value to lock. * @param options The options parameters. */ putLock( key: string, options?: GeneratedClientPutLockOptionalParams ): Promise<GeneratedClientPutLockResponse> { const operationArguments: coreHttp.OperationArguments = { key, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, putLockOperationSpec ) as Promise<GeneratedClientPutLockResponse>; } /** * Unlocks a key-value. * @param key The key of the key-value to unlock. * @param options The options parameters. */ deleteLock( key: string, options?: GeneratedClientDeleteLockOptionalParams ): Promise<GeneratedClientDeleteLockResponse> { const operationArguments: coreHttp.OperationArguments = { key, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, deleteLockOperationSpec ) as Promise<GeneratedClientDeleteLockResponse>; } /** * Gets a list of key-value revisions. * @param options The options parameters. */ getRevisions( options?: GeneratedClientGetRevisionsOptionalParams ): Promise<GeneratedClientGetRevisionsResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getRevisionsOperationSpec ) as Promise<GeneratedClientGetRevisionsResponse>; } /** * Requests the headers and status of the given resource. * @param options The options parameters. */ checkRevisions( options?: GeneratedClientCheckRevisionsOptionalParams ): Promise<GeneratedClientCheckRevisionsResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, checkRevisionsOperationSpec ) as Promise<GeneratedClientCheckRevisionsResponse>; } /** * GetKeysNext * @param nextLink The nextLink from the previous successful call to the GetKeys method. * @param options The options parameters. */ getKeysNext( nextLink: string, options?: GeneratedClientGetKeysNextOptionalParams ): Promise<GeneratedClientGetKeysNextResponse> { const operationArguments: coreHttp.OperationArguments = { nextLink, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getKeysNextOperationSpec ) as Promise<GeneratedClientGetKeysNextResponse>; } /** * GetKeyValuesNext * @param nextLink The nextLink from the previous successful call to the GetKeyValues method. * @param options The options parameters. */ getKeyValuesNext( nextLink: string, options?: GeneratedClientGetKeyValuesNextOptionalParams ): Promise<GeneratedClientGetKeyValuesNextResponse> { const operationArguments: coreHttp.OperationArguments = { nextLink, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getKeyValuesNextOperationSpec ) as Promise<GeneratedClientGetKeyValuesNextResponse>; } /** * GetLabelsNext * @param nextLink The nextLink from the previous successful call to the GetLabels method. * @param options The options parameters. */ getLabelsNext( nextLink: string, options?: GeneratedClientGetLabelsNextOptionalParams ): Promise<GeneratedClientGetLabelsNextResponse> { const operationArguments: coreHttp.OperationArguments = { nextLink, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getLabelsNextOperationSpec ) as Promise<GeneratedClientGetLabelsNextResponse>; } /** * GetRevisionsNext * @param nextLink The nextLink from the previous successful call to the GetRevisions method. * @param options The options parameters. */ getRevisionsNext( nextLink: string, options?: GeneratedClientGetRevisionsNextOptionalParams ): Promise<GeneratedClientGetRevisionsNextResponse> { const operationArguments: coreHttp.OperationArguments = { nextLink, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getRevisionsNextOperationSpec ) as Promise<GeneratedClientGetRevisionsNextResponse>; } } // Operation Specifications const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); const getKeysOperationSpec: coreHttp.OperationSpec = { path: "/keys", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.KeyListResult, headersMapper: Mappers.GeneratedClientGetKeysHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.name, Parameters.apiVersion, Parameters.after], urlParameters: [Parameters.endpoint], headerParameters: [ Parameters.accept, Parameters.syncToken, Parameters.acceptDatetime ], serializer }; const checkKeysOperationSpec: coreHttp.OperationSpec = { path: "/keys", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.GeneratedClientCheckKeysHeaders }, default: {} }, queryParameters: [Parameters.name, Parameters.apiVersion, Parameters.after], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.syncToken, Parameters.acceptDatetime], serializer }; const getKeyValuesOperationSpec: coreHttp.OperationSpec = { path: "/kv", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.KeyValueListResult, headersMapper: Mappers.GeneratedClientGetKeyValuesHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [ Parameters.apiVersion, Parameters.after, Parameters.key, Parameters.label, Parameters.select ], urlParameters: [Parameters.endpoint], headerParameters: [ Parameters.syncToken, Parameters.acceptDatetime, Parameters.accept1 ], serializer }; const checkKeyValuesOperationSpec: coreHttp.OperationSpec = { path: "/kv", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.GeneratedClientCheckKeyValuesHeaders }, default: {} }, queryParameters: [ Parameters.apiVersion, Parameters.after, Parameters.key, Parameters.label, Parameters.select ], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.syncToken, Parameters.acceptDatetime], serializer }; const getKeyValueOperationSpec: coreHttp.OperationSpec = { path: "/kv/{key}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ConfigurationSetting, headersMapper: Mappers.GeneratedClientGetKeyValueHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion, Parameters.label, Parameters.select], urlParameters: [Parameters.endpoint, Parameters.key1], headerParameters: [ Parameters.syncToken, Parameters.acceptDatetime, Parameters.accept2, Parameters.ifMatch, Parameters.ifNoneMatch ], serializer }; const putKeyValueOperationSpec: coreHttp.OperationSpec = { path: "/kv/{key}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ConfigurationSetting, headersMapper: Mappers.GeneratedClientPutKeyValueHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.entity, queryParameters: [Parameters.apiVersion, Parameters.label], urlParameters: [Parameters.endpoint, Parameters.key1], headerParameters: [ Parameters.syncToken, Parameters.accept2, Parameters.ifMatch, Parameters.ifNoneMatch, Parameters.contentType ], mediaType: "json", serializer }; const deleteKeyValueOperationSpec: coreHttp.OperationSpec = { path: "/kv/{key}", httpMethod: "DELETE", responses: { 200: { bodyMapper: Mappers.ConfigurationSetting, headersMapper: Mappers.GeneratedClientDeleteKeyValueHeaders }, 204: { headersMapper: Mappers.GeneratedClientDeleteKeyValueHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion, Parameters.label], urlParameters: [Parameters.endpoint, Parameters.key1], headerParameters: [ Parameters.syncToken, Parameters.accept2, Parameters.ifMatch ], serializer }; const checkKeyValueOperationSpec: coreHttp.OperationSpec = { path: "/kv/{key}", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.GeneratedClientCheckKeyValueHeaders }, default: {} }, queryParameters: [Parameters.apiVersion, Parameters.label, Parameters.select], urlParameters: [Parameters.endpoint, Parameters.key1], headerParameters: [ Parameters.syncToken, Parameters.acceptDatetime, Parameters.ifMatch, Parameters.ifNoneMatch ], serializer }; const getLabelsOperationSpec: coreHttp.OperationSpec = { path: "/labels", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LabelListResult, headersMapper: Mappers.GeneratedClientGetLabelsHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [ Parameters.name, Parameters.apiVersion, Parameters.after, Parameters.select1 ], urlParameters: [Parameters.endpoint], headerParameters: [ Parameters.syncToken, Parameters.acceptDatetime, Parameters.accept3 ], serializer }; const checkLabelsOperationSpec: coreHttp.OperationSpec = { path: "/labels", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.GeneratedClientCheckLabelsHeaders }, default: {} }, queryParameters: [ Parameters.name, Parameters.apiVersion, Parameters.after, Parameters.select1 ], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.syncToken, Parameters.acceptDatetime], serializer }; const putLockOperationSpec: coreHttp.OperationSpec = { path: "/locks/{key}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ConfigurationSetting, headersMapper: Mappers.GeneratedClientPutLockHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion, Parameters.label], urlParameters: [Parameters.endpoint, Parameters.key1], headerParameters: [ Parameters.syncToken, Parameters.accept2, Parameters.ifMatch, Parameters.ifNoneMatch ], serializer }; const deleteLockOperationSpec: coreHttp.OperationSpec = { path: "/locks/{key}", httpMethod: "DELETE", responses: { 200: { bodyMapper: Mappers.ConfigurationSetting, headersMapper: Mappers.GeneratedClientDeleteLockHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.apiVersion, Parameters.label], urlParameters: [Parameters.endpoint, Parameters.key1], headerParameters: [ Parameters.syncToken, Parameters.accept2, Parameters.ifMatch, Parameters.ifNoneMatch ], serializer }; const getRevisionsOperationSpec: coreHttp.OperationSpec = { path: "/revisions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.KeyValueListResult, headersMapper: Mappers.GeneratedClientGetRevisionsHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [ Parameters.apiVersion, Parameters.after, Parameters.key, Parameters.label, Parameters.select ], urlParameters: [Parameters.endpoint], headerParameters: [ Parameters.syncToken, Parameters.acceptDatetime, Parameters.accept1 ], serializer }; const checkRevisionsOperationSpec: coreHttp.OperationSpec = { path: "/revisions", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.GeneratedClientCheckRevisionsHeaders }, default: {} }, queryParameters: [ Parameters.apiVersion, Parameters.after, Parameters.key, Parameters.label, Parameters.select ], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.syncToken, Parameters.acceptDatetime], serializer }; const getKeysNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.KeyListResult, headersMapper: Mappers.GeneratedClientGetKeysNextHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [Parameters.name, Parameters.apiVersion, Parameters.after], urlParameters: [Parameters.endpoint, Parameters.nextLink], headerParameters: [ Parameters.accept, Parameters.syncToken, Parameters.acceptDatetime ], serializer }; const getKeyValuesNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.KeyValueListResult, headersMapper: Mappers.GeneratedClientGetKeyValuesNextHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [ Parameters.apiVersion, Parameters.after, Parameters.key, Parameters.label, Parameters.select ], urlParameters: [Parameters.endpoint, Parameters.nextLink], headerParameters: [ Parameters.syncToken, Parameters.acceptDatetime, Parameters.accept1 ], serializer }; const getLabelsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LabelListResult, headersMapper: Mappers.GeneratedClientGetLabelsNextHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [ Parameters.name, Parameters.apiVersion, Parameters.after, Parameters.select1 ], urlParameters: [Parameters.endpoint, Parameters.nextLink], headerParameters: [ Parameters.syncToken, Parameters.acceptDatetime, Parameters.accept3 ], serializer }; const getRevisionsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.KeyValueListResult, headersMapper: Mappers.GeneratedClientGetRevisionsNextHeaders }, default: { bodyMapper: Mappers.ErrorModel } }, queryParameters: [ Parameters.apiVersion, Parameters.after, Parameters.key, Parameters.label, Parameters.select ], urlParameters: [Parameters.endpoint, Parameters.nextLink], headerParameters: [ Parameters.syncToken, Parameters.acceptDatetime, Parameters.accept1 ], serializer };
the_stack
import { IConnector, IJsonRpcRequest, IRequestOptions, } from "@walletconnect/types"; import { ChainInfo, Keplr, KeplrIntereactionOptions, KeplrMode, KeplrSignOptions, Key, } from "@keplr-wallet/types"; import { DirectSignResponse, OfflineDirectSigner } from "@cosmjs/proto-signing"; import { AminoSignResponse, BroadcastMode, OfflineSigner, StdSignature, StdSignDoc, } from "@cosmjs/launchpad"; import { CosmJSOfflineSigner, CosmJSOfflineSignerOnlyAmino, } from "@keplr-wallet/provider"; import { SecretUtils } from "secretjs/types/enigmautils"; import { payloadId } from "@walletconnect/utils"; import deepmerge from "deepmerge"; import { Buffer } from "buffer/"; import { IndexedDBKVStore, KVStore } from "@keplr-wallet/common"; // VersionFormatRegExp checks if a chainID is in the format required for parsing versions // The chainID should be in the form: `{identifier}-{version}` const ChainVersionFormatRegExp = /(.+)-([\d]+)/; function parseChainId( chainId: string ): { identifier: string; version: number; } { const split = chainId.split(ChainVersionFormatRegExp).filter(Boolean); if (split.length !== 2) { return { identifier: chainId, version: 0, }; } else { return { identifier: split[0], version: parseInt(split[1]) }; } } export type KeplrGetKeyWalletCoonectV1Response = { address: string; algo: string; bech32Address: string; isNanoLedger: boolean; name: string; pubKey: string; }; export type KeplrKeystoreMayChangedEventParam = { algo: string; name: string; isNanoLedger: boolean; keys: { chainIdentifier: string; address: string; bech32Address: string; pubKey: string; }[]; }; export class KeplrWalletConnectV1 implements Keplr { constructor( public readonly connector: IConnector, public readonly options: { kvStore?: KVStore; sendTx?: Keplr["sendTx"]; onBeforeSendRequest?: ( request: Partial<IJsonRpcRequest>, options?: IRequestOptions ) => Promise<void> | void; onAfterSendRequest?: ( response: any, request: Partial<IJsonRpcRequest>, options?: IRequestOptions ) => Promise<void> | void; } = {} ) { if (!options.kvStore) { options.kvStore = new IndexedDBKVStore("keplr_wallet_connect"); } connector.on("disconnect", () => { this.clearSaved(); }); connector.on("call_request", this.onCallReqeust); } readonly version: string = "0.9.0"; readonly mode: KeplrMode = "walletconnect"; defaultOptions: KeplrIntereactionOptions = {}; protected readonly onCallReqeust = async ( error: Error | null, payload: any | null ) => { if (error) { console.log(error); return; } if (!payload) { return; } if ( payload.method === "keplr_keystore_may_changed_event_wallet_connect_v1" ) { const param = payload.params[0] as | KeplrKeystoreMayChangedEventParam | undefined; if (!param) { return; } const lastSeenKeys = await this.getAllLastSeenKey(); if (!lastSeenKeys) { return; } const mayChangedKeyMap: Record< string, KeplrGetKeyWalletCoonectV1Response > = {}; for (const mayChangedKey of param.keys) { mayChangedKeyMap[mayChangedKey.chainIdentifier] = { address: mayChangedKey.address, algo: param.algo, bech32Address: mayChangedKey.bech32Address, isNanoLedger: param.isNanoLedger, name: param.name, pubKey: mayChangedKey.pubKey, }; } let hasChanged = false; for (const chainId of Object.keys(lastSeenKeys)) { const savedKey = lastSeenKeys[chainId]; if (savedKey) { const { identifier } = parseChainId(chainId); const mayChangedKey = mayChangedKeyMap[identifier]; if (mayChangedKey) { if ( mayChangedKey.algo !== savedKey.algo || mayChangedKey.name !== savedKey.name || mayChangedKey.isNanoLedger !== savedKey.isNanoLedger || mayChangedKey.address !== savedKey.address || mayChangedKey.bech32Address !== savedKey.bech32Address || mayChangedKey.pubKey !== savedKey.pubKey ) { hasChanged = true; lastSeenKeys[chainId] = mayChangedKey; } } } } if (hasChanged) { await this.saveAllLastSeenKey(lastSeenKeys); window.dispatchEvent(new Event("keplr_keystorechange")); } } }; protected async clearSaved(): Promise<void> { const kvStore = this.options.kvStore!; await Promise.all([ kvStore.set(this.getKeyHasEnabled(), null), kvStore.set(this.getKeyLastSeenKey(), null), ]); } protected async sendCustomRequest( request: Partial<IJsonRpcRequest>, options?: IRequestOptions ): Promise<any> { if (this.options.onBeforeSendRequest) { await this.options.onBeforeSendRequest(request, options); } const res = await this.connector.sendCustomRequest(request, options); if (this.options.onAfterSendRequest) { await this.options.onAfterSendRequest(res, request, options); } return res; } async enable(chainIds: string | string[]): Promise<void> { if (typeof chainIds === "string") { chainIds = [chainIds]; } const hasEnabledChainIds = await this.getHasEnabledChainIds(); let allEnabled = true; for (const chainId of chainIds) { if (hasEnabledChainIds.indexOf(chainId) < 0) { allEnabled = false; break; } } if (allEnabled) { return; } await this.sendCustomRequest({ id: payloadId(), jsonrpc: "2.0", method: "keplr_enable_wallet_connect_v1", params: chainIds, }); await this.saveHasEnabledChainIds(chainIds); } protected getKeyHasEnabled() { return `${this.connector.session.handshakeTopic}-enabled`; } protected async getHasEnabledChainIds(): Promise<string[]> { return ( (await this.options.kvStore!.get<string[]>(this.getKeyHasEnabled())) ?? [] ); } protected async saveHasEnabledChainIds(chainIds: string[]) { const hasEnabledChainIds = await this.getHasEnabledChainIds(); for (const chainId of chainIds) { if (hasEnabledChainIds.indexOf(chainId) < 0) { hasEnabledChainIds.push(chainId); } } await this.options.kvStore!.set( this.getKeyHasEnabled(), hasEnabledChainIds ); } enigmaDecrypt( _chainId: string, _ciphertext: Uint8Array, _nonce: Uint8Array ): Promise<Uint8Array> { throw new Error("Not yet implemented"); } enigmaEncrypt( _chainId: string, _contractCodeHash: string, // eslint-disable-next-line @typescript-eslint/ban-types _msg: object ): Promise<Uint8Array> { throw new Error("Not yet implemented"); } experimentalSuggestChain(_chainInfo: ChainInfo): Promise<void> { throw new Error("Not yet implemented"); } getEnigmaPubKey(_chainId: string): Promise<Uint8Array> { throw new Error("Not yet implemented"); } getEnigmaTxEncryptionKey( _chainId: string, _nonce: Uint8Array ): Promise<Uint8Array> { throw new Error("Not yet implemented"); } getEnigmaUtils(_chainId: string): SecretUtils { throw new Error("Not yet implemented"); } async getKey(chainId: string): Promise<Key> { const lastSeenKey = await this.getLastSeenKey(chainId); if (lastSeenKey) { return { address: Buffer.from(lastSeenKey.address, "hex"), algo: lastSeenKey.algo, bech32Address: lastSeenKey.bech32Address, isNanoLedger: lastSeenKey.isNanoLedger, name: lastSeenKey.name, pubKey: Buffer.from(lastSeenKey.pubKey, "hex"), }; } const response = ( await this.sendCustomRequest({ id: payloadId(), jsonrpc: "2.0", method: "keplr_get_key_wallet_connect_v1", params: [chainId], }) )[0] as KeplrGetKeyWalletCoonectV1Response; await this.saveLastSeenKey(chainId, response); return { address: Buffer.from(response.address, "hex"), algo: response.algo, bech32Address: response.bech32Address, isNanoLedger: response.isNanoLedger, name: response.name, pubKey: Buffer.from(response.pubKey, "hex"), }; } protected getKeyLastSeenKey() { return `${this.connector.session.handshakeTopic}-key`; } protected async getLastSeenKey( chainId: string ): Promise<KeplrGetKeyWalletCoonectV1Response | undefined> { const saved = await this.getAllLastSeenKey(); if (!saved) { return undefined; } return saved[chainId]; } protected async getAllLastSeenKey() { return await this.options.kvStore!.get<{ [chainId: string]: KeplrGetKeyWalletCoonectV1Response | undefined; }>(this.getKeyLastSeenKey()); } protected async saveAllLastSeenKey(data: { [chainId: string]: KeplrGetKeyWalletCoonectV1Response | undefined; }) { await this.options.kvStore!.set(this.getKeyLastSeenKey(), data); } protected async saveLastSeenKey( chainId: string, response: KeplrGetKeyWalletCoonectV1Response ) { let saved = await this.getAllLastSeenKey(); if (!saved) { saved = {}; } saved[chainId] = response; await this.saveAllLastSeenKey(saved); } signArbitrary( _chainId: string, _signer: string, _data: string | Uint8Array ): Promise<StdSignature> { throw new Error("Not yet implemented"); } verifyArbitrary( _chainId: string, _signer: string, _data: string | Uint8Array, _signature: StdSignature ): Promise<boolean> { throw new Error("Not yet implemented"); } getOfflineSigner(chainId: string): OfflineSigner & OfflineDirectSigner { return new CosmJSOfflineSigner(chainId, this); } async getOfflineSignerAuto( chainId: string ): Promise<OfflineSigner | OfflineDirectSigner> { const key = await this.getKey(chainId); if (key.isNanoLedger) { return new CosmJSOfflineSignerOnlyAmino(chainId, this); } return new CosmJSOfflineSigner(chainId, this); } getOfflineSignerOnlyAmino(chainId: string): OfflineSigner { return new CosmJSOfflineSignerOnlyAmino(chainId, this); } getSecret20ViewingKey( _chainId: string, _contractAddress: string ): Promise<string> { throw new Error("Not yet implemented"); } /** * In the extension environment, this API let the extension to send the tx on behalf of the client. * But, in the wallet connect environment, in order to send the tx on behalf of the client, wallet should receive the tx data from remote. * However, this approach is not efficient and hard to ensure the stability and `KeplrWalletConnect` should have the informations of rpc and rest endpoints. * So, rather than implementing this, just fallback to the client sided implementation or throw error of the client sided implementation is not delivered to the `options`. * @param chainId * @param stdTx * @param mode */ sendTx( chainId: string, tx: Uint8Array, mode: BroadcastMode ): Promise<Uint8Array> { if (this.options.sendTx) { return this.options.sendTx(chainId, tx, mode); } throw new Error("send tx is not delivered by options"); } async signAmino( chainId: string, signer: string, signDoc: StdSignDoc, signOptions: KeplrSignOptions = {} ): Promise<AminoSignResponse> { return ( await this.sendCustomRequest({ id: payloadId(), jsonrpc: "2.0", method: "keplr_sign_amino_wallet_connect_v1", params: [ chainId, signer, signDoc, deepmerge(this.defaultOptions.sign ?? {}, signOptions), ], }) )[0]; } signDirect( _chainId: string, _signer: string, _signDoc: { bodyBytes?: Uint8Array | null; authInfoBytes?: Uint8Array | null; chainId?: string | null; accountNumber?: Long | null; }, _signOptions: KeplrSignOptions = {} ): Promise<DirectSignResponse> { throw new Error("Not yet implemented"); } suggestToken( _chainId: string, _contractAddress: string, _viewingKey?: string ): Promise<void> { throw new Error("Not yet implemented"); } }
the_stack
import { async, fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { By } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { BsDropdownConfig, BsDropdownModule } from 'ngx-bootstrap/dropdown'; import { PopoverModule } from 'ngx-bootstrap/popover'; import { TooltipConfig, TooltipModule } from 'ngx-bootstrap/tooltip'; import { Action } from '../action/action'; import { ActionConfig } from '../action/action-config'; import { ActionModule } from '../action/action.module'; import { Filter } from '../filter/filter'; import { FilterConfig } from '../filter/filter-config'; import { FilterField } from '../filter/filter-field'; import { FilterFieldsComponent } from '../filter/filter-fields.component'; import { FilterResultsComponent } from '../filter/filter-results.component'; import { FilterType } from '../filter/filter-type'; import { SearchHighlightPipeModule } from '../pipe/search-highlight/search-highlight.pipe.module'; import { SortComponent } from '../sort/sort.component'; import { SortConfig } from '../sort/sort-config'; import { SortEvent } from '../sort/sort-event'; import { ToolbarComponent } from './toolbar.component'; import { ToolbarConfig } from './toolbar-config'; import { ToolbarView } from './toolbar-view'; import { TruncatePipeModule } from '../pipe/truncate/truncate.pipe.module'; describe('Toolbar component - ', () => { let comp: ToolbarComponent; let fixture: ComponentFixture<ToolbarComponent>; let config: ToolbarConfig; beforeEach(() => { config = { actionConfig: { primaryActions: [{ id: 'action1', title: 'Action 1', tooltip: 'Do the first thing' }, { id: 'action2', title: 'Action 2', tooltip: 'Do something else' }], moreActions: [{ id: 'moreActions1', title: 'Action', tooltip: 'Perform an action' }, { id: 'moreActions2', title: 'Another Action', tooltip: 'Do something else' }, { disabled: true, id: 'moreActions3', title: 'Disabled Action', tooltip: 'Unavailable action', }, { id: 'moreActions4', title: 'Something Else', tooltip: '' }, { id: 'moreActions5', title: '', separator: true }, { id: 'moreActions6', title: 'Grouped Action 1', tooltip: 'Do something' }, { id: 'moreActions7', title: 'Grouped Action 2', tooltip: 'Do something similar' }] } as ActionConfig, filterConfig: { fields: [{ id: 'name', title: 'Name', placeholder: 'Filter by Name...', type: FilterType.TEXT }, { id: 'age', title: 'Age', placeholder: 'Filter by Age...', type: FilterType.TEXT }, { id: 'address', title: 'Address', placeholder: 'Filter by Address...', type: FilterType.TEXT }, { id: 'birthMonth', title: 'Birth Month', placeholder: 'Filter by Birth Month...', type: FilterType.SELECT, queries: [{ id: 'month1', value: 'January' }, { id: 'month2', value: 'February' }, { id: 'month3', value: 'March' }, { id: 'month4', value: 'April' }, { id: 'month5', value: 'May' }, { id: 'month6', value: 'June' }, { id: 'month7', value: 'July' }, { id: 'month8', value: 'August' }, { id: 'month9', value: 'September' }, { id: 'month10', value: 'October' }, { id: 'month11', value: 'November' }, { id: 'month12', value: 'December' }] }] as FilterField[], resultsCount: 5, appliedFilters: [] } as FilterConfig, sortConfig: { fields: [{ id: 'name', title: 'Name', sortType: 'alpha' }, { id: 'age', title: 'Age', sortType: 'numeric' }, { id: 'address', title: 'Address', sortType: 'alpha' }, { id: 'birthMonth', title: 'Birth Month', sortType: 'alpha' }], isAscending: this.isAscendingSort } as SortConfig, views: [{ id: 'listView', iconStyleClass: 'fa fa-th-list', tooltip: 'List View' }, { id: 'tableView', iconStyleClass: 'fa fa-table', tooltip: 'Table View' }] } as ToolbarConfig; }); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ ActionModule, BsDropdownModule.forRoot(), BrowserAnimationsModule, FormsModule, PopoverModule.forRoot(), SearchHighlightPipeModule, TooltipModule.forRoot(), TruncatePipeModule ], declarations: [ ToolbarComponent, FilterFieldsComponent, FilterResultsComponent, SortComponent ], providers: [BsDropdownConfig, TooltipConfig] }) .compileComponents() .then(() => { fixture = TestBed.createComponent(ToolbarComponent); comp = fixture.componentInstance; comp.config = config; fixture.detectChanges(); }); })); // Filter tests it('should have correct number of filter fields', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('button'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let fields = element.querySelectorAll('.filter-field'); expect(fields.length).toBe(4); })); it('should have correct number of results', function() { let results = fixture.debugElement.query(By.css('h5')); expect(results).toBeNull(); config.filterConfig.appliedFilters = [{ field: { id: 'address', title: 'Address' }, value: 'New York' }] as Filter[]; config.filterConfig.resultsCount = 10; fixture.detectChanges(); results = fixture.debugElement.query(By.css('h5')); expect(results).not.toBeNull(); expect( results.nativeElement.textContent.trim().slice(0, '10 Results'.length) ).toBe('10 Results'); }); it('should show active filters and clear filters button when there are filters', function() { let activeFilters = fixture.debugElement.queryAll(By.css('.active-filter')); let clearFilters = fixture.debugElement.query(By.css('.clear-filters')); expect(activeFilters.length).toBe(0); expect(clearFilters).toBeNull(); config.filterConfig.appliedFilters = [{ field: { id: 'address', title: 'Address' }, value: 'New York' }] as Filter[]; fixture.detectChanges(); activeFilters = fixture.debugElement.queryAll(By.css('.active-filter')); clearFilters = fixture.debugElement.query(By.css('.clear-filters')); expect(activeFilters.length).toBe(1); expect(clearFilters).not.toBeNull(); }); it('should add a dropdown select when a select type is chosen', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('button'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let filterSelect = element.querySelector('.filter-select'); let fields = element.querySelectorAll('.filter-field'); expect(filterSelect).toBeNull(); fields[3].click(); fixture.detectChanges(); filterSelect = element.querySelector('.filter-select'); expect(filterSelect).not.toBeNull(); let selectButton = element.querySelector('.filter-select button'); selectButton.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let items = element.querySelectorAll('.filter-select li'); expect(items.length).toBe(config.filterConfig.fields[3].queries.length); })); it('should clear a filter when the close button is clicked', function() { let closeButtons = fixture.debugElement.queryAll(By.css('.pficon-close')); expect(closeButtons.length).toBe(0); config.filterConfig.appliedFilters = [{ field: { id: 'address', title: 'Address' }, value: 'New York' }] as Filter[]; fixture.detectChanges(); closeButtons = fixture.debugElement.queryAll(By.css('.pficon-close')); expect(closeButtons.length).toBe(1); closeButtons[0].triggerEventHandler('click', {}); fixture.detectChanges(); closeButtons = fixture.debugElement.queryAll(By.css('.pficon-close')); expect(closeButtons.length).toBe(0); }); it('should clear all filters when the clear all filters button is clicked', function() { let activeFilters = fixture.debugElement.queryAll(By.css('.active-filter')); let clearButton = fixture.debugElement.query(By.css('.clear-filters')); expect(activeFilters.length).toBe(0); expect(clearButton).toBeNull(); config.filterConfig.appliedFilters = [{ field: { id: 'address', title: 'Address' }, value: 'New York' }] as Filter[]; fixture.detectChanges(); activeFilters = fixture.debugElement.queryAll(By.css('.active-filter')); clearButton = fixture.debugElement.query(By.css('.clear-filters')); expect(activeFilters.length).toBe(1); expect(clearButton).not.toBeNull(); clearButton.triggerEventHandler('click', {}); fixture.detectChanges(); activeFilters = fixture.debugElement.queryAll(By.css('.active-filter')); clearButton = fixture.debugElement.query(By.css('.clear-filters')); expect(activeFilters.length).toBe(0); expect(clearButton).toBeNull(); }); it('should not show filters when a filter config is not supplied', function() { let filter = fixture.debugElement.queryAll(By.css('.filter-pf')); expect(filter.length).toBe(1); config.filterConfig = undefined; comp.config = config; fixture.detectChanges(); filter = fixture.debugElement.queryAll(By.css('.filter-pf')); expect(filter.length).toBe(0); }); // Sort Tests it('should have correct number of sort fields', fakeAsync(() => { const element = fixture.nativeElement; let button = element.querySelector('.sort-pf button'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let elements = element.querySelectorAll('.sort-pf .sort-field'); expect(elements.length).toBe(4); })); it('should have default to the first sort field', () => { let results = fixture.debugElement.query(By.css('.sort-pf .dropdown-toggle')); expect(results).not.toBeNull(); expect(results.nativeElement.textContent.trim().slice(0, 'Name'.length)).toBe('Name'); }); it('should default to ascending sort', function() { let sortIcon = fixture.debugElement.query(By.css('.sort-pf .fa-sort-alpha-asc')); expect(sortIcon).not.toBeNull(); }); it('should update the current sort when one is selected', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('.sort-pf button'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let results = element.querySelector('.sort-pf .dropdown-toggle'); let fields = element.querySelectorAll('.sort-pf .sort-field'); expect(results).not.toBeNull(); expect(results.textContent.trim().slice(0, 'Name'.length)).toBe('Name'); expect(fields.length).toBe(4); fields[2].click(); fixture.detectChanges(); results = element.querySelector('.sort-pf .dropdown-toggle'); expect(results.textContent.trim().slice(0, 'Address'.length)) .toBe('Address'); })); it('should update the direction icon when the sort type changes', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('.sort-pf button'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let results = element.querySelector('.sort-pf .dropdown-toggle'); let fields = element.querySelectorAll('.sort-pf .sort-field'); let sortIcon = element.querySelector('.sort-pf .fa-sort-alpha-asc'); expect(results).not.toBeNull(); expect(results.textContent.trim().slice(0, 'Name'.length)).toBe('Name'); expect(fields.length).toBe(4); expect(sortIcon).not.toBeNull(); fields[1].click(); fixture.detectChanges(); results = element.querySelector('.sort-pf .dropdown-toggle'); sortIcon = element.querySelector('.sort-pf .fa-sort-numeric-asc'); expect(results).not.toBeNull(); expect(results.textContent.trim().slice(0, 'Age'.length)).toBe('Age'); expect(sortIcon).not.toBeNull(); })); it('should reverse the sort direction when the direction button is clicked', function() { let sortButton = fixture.debugElement.query(By.css('.sort-pf .btn.btn-link')); let sortIcon = fixture.debugElement.query(By.css('.sort-pf .fa-sort-alpha-asc')); expect(sortButton).not.toBeNull(); expect(sortIcon).not.toBeNull(); sortButton.triggerEventHandler('click', {}); fixture.detectChanges(); sortIcon = fixture.debugElement.query(By.css('.sort-pf .fa-sort-alpha-desc')); expect(sortIcon).not.toBeNull(); }); it('should notify when a new sort field is chosen', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('.sort-pf button'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let fields = element.querySelectorAll('.sort-pf .sort-field'); expect(fields.length).toBe(4); comp.onSortChange.subscribe((data: SortEvent) => { expect(data.field).toBe(config.sortConfig.fields[1]); }); fields[1].click(); fixture.detectChanges(); tick(); })); it('should notify when the sort direction changes', function(done) { let sortButton = fixture.debugElement.query(By.css('.sort-pf .btn.btn-link')); comp.onSortChange.subscribe((data: SortEvent) => { expect(data.isAscending).toBe(false); done(); }); expect(sortButton).not.toBeNull(); sortButton.triggerEventHandler('click', {}); fixture.detectChanges(); }); it('should not show sort when a sort config is not supplied', function() { let sort = fixture.debugElement.query(By.css('.sort-pf')); expect(sort).not.toBeNull(); config.sortConfig = undefined; comp.config = config; fixture.detectChanges(); sort = fixture.debugElement.query(By.css('.sort-pf')); expect(sort).toBeNull(); }); // View tests it('should show the correct view selection buttons', function() { let listSelectora = fixture.debugElement.queryAll(By.css('.toolbar-pf-view-selector .btn-link')); expect(listSelectora.length).toBe(2); expect(fixture.debugElement.query(By.css('.fa-th-list'))).not.toBeNull(); expect(fixture.debugElement.query(By.css('.fa-table'))).not.toBeNull(); }); it('should show the currently selected view', function() { let viewSelector = fixture.debugElement.query(By.css('.toolbar-pf-view-selector')); let active = fixture.debugElement.queryAll(By.css('.active')); expect(viewSelector).not.toBeNull(); expect(active.length).toBe(1); config.view = config.views[0]; fixture.detectChanges(); active = fixture.debugElement.queryAll(By.css('.active')); expect(active.length).toBe(1); }); it('should update the currently selected view when a view selector clicked', function() { let active = fixture.debugElement.queryAll(By.css('.active')); let viewSelector = fixture.debugElement.query(By.css('.toolbar-pf-view-selector')); let listSelectora = fixture.debugElement.queryAll(By.css('.toolbar-pf-view-selector .btn-link')); expect(viewSelector).not.toBeNull(); expect(active.length).toBe(1); expect(listSelectora.length).toBe(2); listSelectora[0].triggerEventHandler('click', {}); fixture.detectChanges(); active = fixture.debugElement.queryAll(By.css('.active')); expect(active.length).toBe(1); }); it('should call the callback function when a view selector clicked', function(done) { let listSelectors = fixture.debugElement.queryAll(By.css('.toolbar-pf-view-selector .btn-link')); expect(listSelectors.length).toBe(2); let view: ToolbarView; comp.onViewSelect.subscribe((data: ToolbarView) => { view = data; done(); }); listSelectors[0].triggerEventHandler('click', {}); fixture.detectChanges(); expect(view).not.toBeNull(); }); // Action tests it('should have correct number of primary actions', function() { let fields = fixture.debugElement.queryAll(By.css('.toolbar-pf-actions .primary-action')); expect(fields.length).toBe(2); }); it('should have correct number of secondary actions', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('.toolbar-actions button.dropdown-toggle'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let fields = element.querySelectorAll('.toolbar-actions .secondary-action'); expect(fields.length).toBe(6); })); it('should have correct number of separators', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('.toolbar-actions button.dropdown-toggle'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let fields = element.querySelectorAll('.toolbar-actions .divider'); expect(fields.length).toBe(1); })); it('should correctly disable actions', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('.toolbar-actions .dropdown-kebab-pf button.dropdown-toggle'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let fields = element.querySelectorAll('.toolbar-actions .disabled'); expect(fields.length).toBe(1); })); it('should not show more actions menu when there are no more actions', function() { let menus = fixture.debugElement.queryAll(By.css('.toolbar-pf-actions .fa-ellipsis-v')); expect(menus.length).toBe(1); config.actionConfig.moreActions.length = 0; fixture.detectChanges(); menus = fixture.debugElement.queryAll(By.css('.toolbar-pf-actions .fa-ellipsis-v')); expect(menus.length).toBe(0); }); it('should call the action function with the appropriate action when an action is clicked', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('.toolbar-pf-actions .dropdown-kebab-pf button'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let moreActions = element.querySelectorAll( '.toolbar-pf-actions .dropdown-kebab-pf .dropdown-item.secondary-action'); expect(moreActions.length).toBe(6); let primaryActions = element.querySelectorAll('.toolbar-pf-actions button.primary-action'); expect(primaryActions.length).toBe(2); let action: Action; comp.onActionSelect.subscribe((data: Action) => { action = data; }); primaryActions[0].click(); fixture.detectChanges(); expect(action).toBe(config.actionConfig.primaryActions[0]); moreActions[3].click(); fixture.detectChanges(); expect(action).toBe(config.actionConfig.moreActions[3]); })); it('should not call the action function when a disabled action is clicked', fakeAsync(function() { const element = fixture.nativeElement; let button = element.querySelector('.toolbar-pf-actions .dropdown-kebab-pf button'); button.click(); tick(); fixture.detectChanges(); // Workaround to fix dropdown tests let moreActions = element.querySelectorAll( '.toolbar-pf-actions .dropdown-kebab-pf .dropdown-item.secondary-action'); expect(moreActions.length).toBe(6); let primaryActions = element.querySelectorAll('.toolbar-pf-actions button.primary-action'); expect(primaryActions.length).toBe(2); let action: Action = null; comp.onActionSelect.subscribe((data: Action) => { action = data; }); moreActions[2].click(); fixture.detectChanges(); expect(action).toBeNull(); primaryActions[1].click(); fixture.detectChanges(); expect(action).toBe(config.actionConfig.primaryActions[1]); config.actionConfig.primaryActions[1].disabled = true; fixture.detectChanges(); action = null; primaryActions[1].click(); fixture.detectChanges(); expect(action).toBeNull(); })); });
the_stack
/* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /// <reference path="../Microsoft.Maps.d.ts"/> /** * This module wraps the Query and GeoData REST API’s in the Bing Spatial Dara Services and expose them as an easy to use JavaScript library. * @requires The Microsoft.Maps.SpatialDataService module. */ declare module Microsoft.Maps.SpatialDataService { ////////////////////////////////////////////// /// GeoData API ////////////////////////////////////////////// /** Represents the options for requests boundary data from the GeoData API in the Bing Spatial Data Services. */ export interface IGetBoundaryRequestOptions { /** * The level of detail for the boundary polygons returned. An integer between 0 and 3, where 0 specifies the coarsest level of boundary detail and 3 * specifies the best. Default: 0 */ lod?: number; /** * The entity type to return. Default: CountryRegion * Supported entity types: * AdminDivision1, AdminDivision2, CountryRegion, eighborhood, PopulatedPlace, Postcode1, Postcode2, Postcode3, Postcode4 * Note: Not all entity types are available in all areas. */ entityType?: string; /** * Specifies the preferred language to use for any metadata text about the entity or polygons. Defaults to the culture used by the map control, which * usually automatically detected based on user's browser settings. Setting this property will override the default value. */ culture?: string; /** * Specifies whether the response should include all of the boundary polygons for the requested entity or just return a single polygon that represents * the main outline of the entity. Default: false */ getAllPolygons?: boolean; /** * Specifies whether the response should include metadata about the entity, such as AreaSqKm and others. Default: false */ getEntityMetadata?: boolean; /** * Specifies the user’s home country or region.Defaults to the region setting of the user who loads the map. * Warning: Setting this property will override the default value, which is the region the user is actually in, and will allow the user to see boundaries * which may not align with the views of their region.This could result in geopolitically sensitive borders being returned. */ userRegion?: string; } /** Represents the primitive object for a boundary returned by the GeoData API. */ export interface IGeoDataPrimitive { /** A unique ID associated with this polygon primitive. */ PrimitiveID: string; /** * A comma-delimited sequence starting with the version number of the polygon set followed by a list of compressed polygon * "rings" (closed paths represented by sequences of latitude and-longitude points). */ Shape: string; /** The number of vertex points used to define the polygon. */ NumPoints: string; /** * An ID identifying the data provider that supplied the data. This ID number will reference one of the sources listed in the * array of CopyrightSources in the Copyright property of the GeoDataResultSet object. */ SourceID: string; } /** Represents the copyright source object for a boundary returned by the GeoData API. */ export interface ICopyrightSource { /** The copyright string from the source. */ Copyright: string; /** An ID identifying the data provider that supplied the data. */ SourceID: string; /** The name of the data provider represented by this Source element. */ SourceName: string; } /** Represents the copyright object for a boundary returned by the GeoData API. */ export interface ICopyright { /** The copyright URL for the GeoData service. */ CopyrightURL: string; /** A collection of CopyrightSource objects that give information about the sources of the polygon data that is returned. */ Sources: ICopyrightSource[]; } /** Represents the name object for a boundary returned by the GeoData API. */ export interface IName { /** The name of boundary. Example: "United States" */ EntityName: string; /** The culture of the region. */ Culture: string; /** An ID identifying the data provider that supplied the data. */ SourceID: string; } /** Represents the metadata object for a boundary returned by the GeoData API. Not all properties will be returned for all results. */ export interface IMetadata { /** The approximate total surface area (in square kilometers) covered by all the polygons that comprise this entity. */ AreaSqKm: string; /** * An area on the Earth that provides the best map view for this entity. This area is defined as a bounding box in the format of a * “MULTIPOINT ((WestLongitude SouthLatitude), (EastLongitude NorthLatitude))”. */ BestMapViewBox: string; /** The culture associated with this entity. Example: en */ OfficialCulture: string; /** The approximate population within this entity. Example: PopClass20000to99999 */ PopulationClass: string; /** The regional culture associated with this entity. */ RegionalCulture: string; } /** Represents a single result object returned by the GeoData API. */ export interface IGeoDataResult { /** Copyright information for the returned boundary data. */ Copyright: ICopyright; /** A unique ID number associated with this entity. */ EntityID: string; /** * A collection of metadata information associated with the entity. The getEntityMetadata option of the request must be set * to true. Note, not all boundaries will return this metadata. */ EntityMetadata: IMetadata; /** Information about the name of the boundary location. */ Name: IName; /** A Polygon object that has been generated from the data in the Primitives property. */ Polygons: Polygon[]; /** An array of objects that contain the polygon information for the boundary. */ Primitives: IGeoDataPrimitive[]; } /** Represents the set of results returned by the GeoData API. */ export interface IGeoDataResultSet { /** Copyright information for the GeoData API. */ Copyright: string; /** The location provided in the query that generated this result. */ location: string |  Location; /** Results of the boundary data. */ results: IGeoDataResult[]; } /** * This is a static class that provides the ability to request polygons that describe the boundaries of a geographic entities, such as an AdminDivision1 * (such as a state or province) or a Postcode1 (such as a zip code) that contain a given point (latitude and longitude) or address. This uses the GeoData * API in the Bing Spatial Data Services. * @requires The Microsoft.Maps.SpatialDataService module. */ export module GeoDataAPIManager { /** * Gets a boundary for the specified request. If the specified location value is a string, it will be geocoded and the coordinates of the result will * be used to find a boundary of the specified entityType that intersects with this coordinate. * @requires The Microsoft.Maps.SpatialDataService module. * @param locations The locations to retrieve boundaries for. If the specified location value is a string, it will be geocoded and the coordinates of * the result will be used to find a boundary of the specified entityType that intersects with this coordinate. * @param request The request options for retrieving a boundary. * @param credentials A bing maps key or a map instance which can be used to provide credentials to access the data source. Note that the map will need * to be loaded with a bing maps key that has access to the data source. * @param callback A callback function to return the results to. If an array of locations are specified the callback function will be triggered for each location in the array. */ export function getBoundary(locations: string | Location | (string | Location)[], request: IGetBoundaryRequestOptions, credentials: string | Map, callback: (results: IGeoDataResultSet) => void, styles?: IPolygonOptions): void; } ////////////////////////////////////////////// /// Query API ////////////////////////////////////////////// /** * An enumeration that defines how to compare the filters value against the corresponding property value. * @requires The Microsoft.Maps.SpatialDataService module. */ export enum FilterCompareOperator { /** Determines if a string value ends with a specified string value. */ endsWith, /** Determines if two values are equal. */ equals, /** Determines if a first value is greater than a second value. */ greaterThan, /** Determines if a first value is greater than or equal to a second value. */ greaterThanOrEqual, /** Determines if a value is within an array. */ isIn, /** Determines if a first value is less than a second value. */ lessThan, /** Determines if a first value is less than or equal a second value. */ lessThanOrEqual, /** Determines if a string value does not end with a specified string value. */ notEndsWith, /** Determines if two values are not equal. */ notEquals, /** Determines if a string value does not start with a specified string value. */ notStartsWith, /** Determines if a string value starts with a specified string value. */ startsWith } /** * An enumeration that defines how two or more filters are linked together. * @requires The Microsoft.Maps.SpatialDataService module. */ export enum FilterLogicalOperator { /** Connects two or more filters that both must be true. */ and, /** Connects two or more filters where one of them must be true. */ or } /** * A Fitler object that defines the logic behind a filter expression that can be executed against a JSON object or generate * a filter string that can be used with the Bing Spatial Data Services. */ export interface IFilter { /** * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. * @returns A boolean indicating if the specified object meets the requirements of the Filter. */ execute(object: any): boolean; /** * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. */ toString(): string; } /** * The Fitler class defines the logic behind a filter expression that can be executed against a JSON object or generate * a filter string that can be used with the Bing Spatial Data Services. * @requires The Microsoft.Maps.SpatialDataService module. */ export class Filter implements IFilter { /** * @constructor * @requires The Microsoft.Maps.SpatialDataService module. * @param propertyName The name of the property in the object to test against. Can also provide child properties i.e. 'root.child'. * @param operator The operator to use when comparing the specified property to value to the provided value. * @param value A value to compare against. */ constructor(propertyName: string, operator: string | FilterCompareOperator, value: any); /** * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. * @returns A boolean indicating if the specified object meets the requirements of the Filter. */ public execute(object: any): boolean; /** * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. */ public toString(): string; } /** * A class that groups two or more logical filters or filter groups together. It can be executed against a JSON or generate * a filter string that can be used with the Bing Spatial Data Services. * @requires The Microsoft.Maps.SpatialDataService module. */ export class FilterGroup implements IFilter { /** * @constructor * @requires The Microsoft.Maps.SpatialDataService module. * @param filters An array consisting of Filter or FilterGroup objects to combine. * @param operator The logical operator for combining the filters together. * @param not A boolean is the logical inverse should of the filter should be used. */ constructor(filters: IFilter[], operator: FilterLogicalOperator, not?: boolean) /** * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. * @returns A boolean indicating if the specified object meets the requirements of the Filter. */ public execute(object: any): boolean; /** * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. */ public toString(): string; } /** Options for find near route query API. */ export interface ISpatialFilterOptions { /** * One of the following values: * • nearby – Searches in a radius around a location. * • nearRoute – Searches for results that are within 1 mile of a route. * • intersects – Searches for results that intersect with the specified geometry. * Note: Note that the NavteqNA and NavteqEU data sources only support nearby queries. */ spatialFilterType: string; /** Location at which the filter should be applied (only for nearby filter). */ location?: string | Location; /** * Radius to use when performing a nearby search. The distance in kilometers and must be between 0.16 and 1000 kilometers * (only for nearby filter). */ radius?: number; /** Start location of the route (only for nearroute filter). */ start?: string | Location; /** End location of the route (only for nearroute filter). */ end?: string | Location; /** Intersection object. Can be a well known text string or a LocationRect object (only for intersects filter). */ intersects?: string | LocationRect | IPrimitive; } /** Options for find near route query API. */ export interface IFindNearRouteOptions extends ISpatialFilterOptions { /** * One of the following values: * • Driving [default] * • Walking */ travelMode?: string; /** * An integer value between 0 and 359 that represents degrees from north * where north is 0 degrees and the heading is specified clockwise from north. * For example, setting the heading of 270 degrees creates a route that initially heads west */ heading?: number; /** * An integer distance specified in meters. * Use this parameter to make sure that the moving vehicle has enough distance * to make the first turn */ distanceBeforeFirstTurn?: number; /** * A list of values that limit the use of highways and toll roads in the route. * Use one of the following values: * • highways - Avoids the use of highways in the route. * • tolls - Avoids the use of toll roads in the route. * • minimizeHighways - Minimizes (tries to avoid) the use of highways in the route. * • minimizeTolls - Minimizes (tries to avoid) the use of toll roads in the route. */ avoid?: string[]; /** * One of the following values: * • distance - The route is calculated to minimize the distance.Traffic information is not used. * • time[default] - The route is calculated to minimize the time.Traffic information is not used. * • timeWithTraffic - The route is calculated to minimize the time and uses current traffic information. */ optimize?: string; } /** Set of options that can be specified for query APIs. */ export interface IQueryAPIOptions { /** A queryurl containing the access id, data source name and the entity type name. */ queryUrl: string; /** Specifies a conditional expression for a list of properties and values. */ filter?: string | IFilter; /** Specifies whether or not to return a count of the results in the response. Default: false */ inlineCount?: boolean; /** Specifies to query the staged version of the data source instead of the published version. Default: false */ isStaging?: boolean; /** * Specifies one or more properties to use to sort the results of a query. * You can specify up to three (3) properties. Results are sorted in ascending order. * Note: You cannot use the latitude and longitude properties to sort results. You can use the elevation property. */ orderBy?: string[]; /** * Specifies the data source properties to return in the response. If the $select query option is not specified or * if it is set to "" ($select=), all data source properties are returned. Default: "*,_distance" */ select?: string[]; /** Specifies to not return a specified number of query results. */ skip?: number; /** Spatial filter options to apply. */ spatialFilter?: ISpatialFilterOptions | IFindNearRouteOptions; /** Specifies the maximum number of results to return in the query response. Default: 25 */ top?: number; } /** * This is a static class that provides that ability to query data sources that are hosted by the Bing Spatial Data Services using the Query API. * @requires The Microsoft.Maps.SpatialDataService module. */ export module QueryAPIManager { /** * Perform a search * @requires The Microsoft.Maps.SpatialDataService module. * @param queryOptions - Options for the query * @param credentials - Credentials for the query * @param callback - The function to call once the results are retrieved * @param styles - (Optional) Styles of the data that needs to be rendered on map * @param withoutLocationInfo - * @param errorCallback - */ export function search(queryOptions: IQueryAPIOptions, credentials: string | Map, callback: (data: IPrimitive[], inlineCount?: number) => void, styles?: IStylesOptions): void; } }
the_stack
import { assert, expect } from "chai"; import { SchemaContext } from "../../Context"; import { PrimitiveType } from "../../ECObjects"; import { ECClass, MutableClass } from "../../Metadata/Class"; import { MutableSchema, Schema } from "../../Metadata/Schema"; /* eslint-disable @typescript-eslint/naming-convention */ describe("Property Inheritance", () => { describe("Struct class with two levels of base classes", () => { // Using a struct here, because entity has a different implementation // // [RootClass:P1,P2] // | // [MiddleClass:P2,P1,P3] // | // [TestClass:P4,P3] const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "TestSchema", version: "01.00.00", alias: "ts", items: { RootClass: { schemaItemType: "StructClass", properties: [ { name: "P1", type: "PrimitiveProperty", typeName: "string" }, { name: "P2", type: "PrimitiveProperty", typeName: "string" }, ], }, MiddleClass: { schemaItemType: "StructClass", baseClass: "TestSchema.RootClass", properties: [ { name: "P2", type: "PrimitiveProperty", typeName: "string" }, { name: "P1", type: "PrimitiveProperty", typeName: "string" }, { name: "P3", type: "PrimitiveProperty", typeName: "string" }, ], }, TestClass: { schemaItemType: "StructClass", baseClass: "TestSchema.MiddleClass", properties: [ { name: "P4", type: "PrimitiveProperty", typeName: "string" }, { name: "P3", type: "PrimitiveProperty", typeName: "string" }], }, }, }; const expectedResult = ["P1(MiddleClass)", "P2(MiddleClass)", "P3(TestClass)", "P4(TestClass)"]; it("async iteration", async () => { const schema = (await Schema.fromJson(schemaJson, new SchemaContext())) as MutableSchema; const testClass = await schema.getItem<ECClass>("TestClass"); const props = await testClass!.getProperties(); const names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); }); it("sync iteration", () => { const schema = Schema.fromJsonSync(schemaJson, new SchemaContext()) as MutableSchema; const testClass = schema.getItemSync<ECClass>("TestClass"); const props = testClass!.getPropertiesSync(); const names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); }); }); describe("Entity class with two levels of base classes", () => { // [RootClass:P1,P2] // | // [MiddleClass:P2,P1,P3] // | // [TestClass:P4,P3] const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "TestSchema", version: "01.00.00", alias: "ts", items: { RootClass: { schemaItemType: "EntityClass", properties: [ { name: "P1", type: "PrimitiveProperty", typeName: "string" }, { name: "P2", type: "PrimitiveProperty", typeName: "string" }, ], }, MiddleClass: { schemaItemType: "EntityClass", baseClass: "TestSchema.RootClass", properties: [ { name: "P2", type: "PrimitiveProperty", typeName: "string" }, { name: "P1", type: "PrimitiveProperty", typeName: "string" }, { name: "P3", type: "PrimitiveProperty", typeName: "string" }, ], }, TestClass: { schemaItemType: "EntityClass", baseClass: "TestSchema.MiddleClass", properties: [ { name: "P4", type: "PrimitiveProperty", typeName: "string" }, { name: "P3", type: "PrimitiveProperty", typeName: "string" }, ], }, }, }; const expectedResult = ["P1(MiddleClass)", "P2(MiddleClass)", "P3(TestClass)", "P4(TestClass)"]; it("async iteration", async () => { const schema = (await Schema.fromJson(schemaJson, new SchemaContext())) as MutableSchema; const testClass = await schema.getItem<ECClass>("TestClass"); const props = await testClass!.getProperties(); const names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); }); it("sync iteration", () => { const schema = Schema.fromJsonSync(schemaJson, new SchemaContext()) as MutableSchema; const testClass = schema.getItemSync<ECClass>("TestClass"); const props = testClass!.getPropertiesSync(); const names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); }); }); describe("Cache invalidation when things change", () => { // [RootClass:P1,P2] // | // [MiddleClass:P2,P1,P3] (Mixin:P5) // | / // [TestClass:P4,P3] const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "TestSchema", version: "01.00.00", alias: "ts", items: { RootClass: { schemaItemType: "EntityClass", properties: [{ name: "P1", type: "PrimitiveProperty", typeName: "string" }], }, Mixin: { schemaItemType: "Mixin", appliesTo: "TestSchema.RootClass", properties: [{ name: "P5", type: "PrimitiveProperty", typeName: "string" }], }, TestClass: { schemaItemType: "EntityClass", baseClass: "TestSchema.RootClass", mixins: ["TestSchema.Mixin"] }, }, }; const expectedResult = ["P1(RootClass)", "P5(Mixin)"]; const expectedResult2 = ["P1(RootClass)", "P2(RootClass)", "P5(Mixin)"]; const expectedResult3 = ["P1(RootClass)", "P2(RootClass)", "P5(Mixin)", "P3(TestClass)"]; it("async iteration", async () => { const schema = (await Schema.fromJson(schemaJson, new SchemaContext())) as MutableSchema; const testClass = await schema.getItem("TestClass") as MutableClass; const rootClass = await schema.getItem("RootClass") as MutableClass; let props = await testClass.getProperties(); let names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); await rootClass.createPrimitiveProperty("P2", PrimitiveType.String); // this should use the cache and return old results props = await testClass.getProperties(); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); props = await testClass.getProperties(true); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult2); await testClass.createPrimitiveProperty("P3", PrimitiveType.String); // this should use the cache and return old results props = await testClass.getProperties(); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult2); props = await testClass.getProperties(true); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult3); }); it("sync iteration", () => { const schema = Schema.fromJsonSync(schemaJson, new SchemaContext()) as MutableSchema; const testClass = schema.getItemSync("TestClass") as MutableClass; const rootClass = schema.getItemSync("RootClass") as MutableClass; let props = testClass.getPropertiesSync(); let names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); rootClass.createPrimitivePropertySync("P2", PrimitiveType.String); // this should use the cache and return old results props = testClass.getPropertiesSync(); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); props = testClass.getPropertiesSync(true); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult2); testClass.createPrimitivePropertySync("P3", PrimitiveType.String); // this should use the cache and return old results props = testClass.getPropertiesSync(); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult2); props = testClass.getPropertiesSync(true); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult3); }); }); describe("Cache invalidation when things change with struct class", () => { // [RootClass:P1,P2] // | // [MiddleClass:P2,P1,P3] // | // [TestClass:P4,P3] const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "TestSchema", version: "01.00.00", alias: "ts", items: { RootClass: { schemaItemType: "StructClass", properties: [{ name: "P1", type: "PrimitiveProperty", typeName: "string" }], }, TestClass: { schemaItemType: "StructClass", baseClass: "TestSchema.RootClass" }, }, }; const expectedResult = ["P1(RootClass)"]; const expectedResult2 = ["P1(RootClass)", "P2(RootClass)"]; const expectedResult3 = ["P1(RootClass)", "P2(RootClass)", "P3(TestClass)"]; it("async iteration", async () => { const schema = (await Schema.fromJson(schemaJson, new SchemaContext())) as MutableSchema; const testClass = await schema.getItem("TestClass") as MutableClass; const rootClass = await schema.getItem("RootClass") as MutableClass; let props = await testClass.getProperties(); let names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); await rootClass.createPrimitiveProperty("P2", PrimitiveType.String); // this should use the cache and return old results props = await testClass.getProperties(); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); props = await testClass.getProperties(true); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult2); await testClass.createPrimitiveProperty("P3", PrimitiveType.String); // this should use the cache and return old results props = await testClass.getProperties(); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult2); props = await testClass.getProperties(true); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult3); }); it("sync iteration", () => { const schema = Schema.fromJsonSync(schemaJson, new SchemaContext()) as MutableSchema; const testClass = schema.getItemSync("TestClass") as MutableClass; const rootClass = schema.getItemSync("RootClass") as MutableClass; let props = testClass.getPropertiesSync(); let names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); rootClass.createPrimitivePropertySync("P2", PrimitiveType.String); // this should use the cache and return old results props = testClass.getPropertiesSync(); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult); props = testClass.getPropertiesSync(true); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult2); testClass.createPrimitivePropertySync("P3", PrimitiveType.String); // this should use the cache and return old results props = testClass.getPropertiesSync(); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult2); props = testClass.getPropertiesSync(true); names = props.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedResult3); }); }); describe("Entity with complex base and mixin hierarchy", () => { // This is the class hierarchy used in this test. The numbers indicate override priority, // i.e., the order that they should be returned by testClass.getAllBaseClasses(): // // [A:P1,P2] (B) (C:P3) (D:P4) [] := EntityClass // \ / / / () := Mixin // 2[ G:P1 ] (E) (F) // \ / / // [H:P2] // We are using the labels to tell the properties apart which have been overwritten const testSchemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "TestSchema", version: "01.00.00", alias: "ts", items: { A: { schemaItemType: "EntityClass", properties: [ { name: "P1", type: "PrimitiveProperty", typeName: "string" }, { name: "P2", type: "PrimitiveProperty", typeName: "string" }, ], }, B: { schemaItemType: "Mixin", appliesTo: "TestSchema.A" }, C: { schemaItemType: "Mixin", appliesTo: "TestSchema.A", properties: [ { name: "P3", type: "PrimitiveProperty", typeName: "string" }, ], }, D: { schemaItemType: "Mixin", appliesTo: "TestSchema.A", properties: [ { name: "P4", type: "PrimitiveProperty", typeName: "string" }, ], }, E: { schemaItemType: "Mixin", appliesTo: "TestSchema.A", baseClass: "TestSchema.C" }, F: { schemaItemType: "Mixin", appliesTo: "TestSchema.A", baseClass: "TestSchema.D" }, G: { schemaItemType: "EntityClass", baseClass: "TestSchema.A", mixins: ["TestSchema.B"], properties: [{ name: "P1", type: "PrimitiveProperty", typeName: "string" }], }, H: { schemaItemType: "EntityClass", baseClass: "TestSchema.G", mixins: ["TestSchema.E", "TestSchema.F"], properties: [{ name: "P2", type: "PrimitiveProperty", typeName: "string" }], }, }, }; const expectedOrder = ["P1(G)", "P2(H)", "P3(C)", "P4(D)"]; it("async iteration", async () => { const schema = await Schema.fromJson(testSchemaJson, new SchemaContext()); expect(schema).to.exist; const testClass = await schema.getItem<ECClass>("H"); expect(testClass).to.exist; const result = await testClass!.getProperties(); const names = result.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedOrder); }); it("sync iteration", () => { const schema = Schema.fromJsonSync(testSchemaJson, new SchemaContext()); expect(schema).to.exist; const testClass = schema.getItemSync<ECClass>("H"); expect(testClass).to.exist; const result = testClass!.getPropertiesSync(); const names = result.map((p) => `${p.name}(${p.class.name})`); assert.deepEqual(names, expectedOrder); }); }); });
the_stack
import { Scene } from "../scene/scene"; import { Group } from "../scene/group"; import { Series, SeriesNodeDatum } from "./series/series"; import { Padding } from "../util/padding"; import { Shape } from "../scene/shape/shape"; import { Node } from "../scene/node"; import { Rect } from "../scene/shape/rect"; import { Legend, LegendClickEvent, LegendDatum } from "./legend"; import { BBox } from "../scene/bbox"; import { find } from "../util/array"; import { SizeMonitor } from "../util/sizeMonitor"; import { Caption } from "../caption"; import { Observable, reactive, PropertyChangeEvent, SourceEvent } from "../util/observable"; import { ChartAxis, ChartAxisDirection } from "./chartAxis"; import { createId } from "../util/id"; import { PlacedLabel, placeLabels, PointLabelDatum } from "../util/labelPlacement"; const defaultTooltipCss = ` .ag-chart-tooltip { display: table; position: absolute; user-select: none; pointer-events: none; white-space: nowrap; z-index: 99999; font: 12px Verdana, sans-serif; color: black; background: rgb(244, 244, 244); border-radius: 5px; box-shadow: 0 0 1px rgba(3, 3, 3, 0.7), 0.5vh 0.5vh 1vh rgba(3, 3, 3, 0.25); } .ag-chart-tooltip-hidden { top: -10000px !important; } .ag-chart-tooltip-title { font-weight: bold; padding: 7px; border-top-left-radius: 5px; border-top-right-radius: 5px; color: white; background-color: #888888; border-top-left-radius: 5px; border-top-right-radius: 5px; } .ag-chart-tooltip-content { padding: 7px; line-height: 1.7em; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; overflow: hidden; } .ag-chart-tooltip-content:empty { padding: 0; height: 7px; } .ag-chart-tooltip-arrow::before { content: ""; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); border: 6px solid #989898; border-left-color: transparent; border-right-color: transparent; border-top-color: #989898; border-bottom-color: transparent; width: 0; height: 0; margin: 0 auto; } .ag-chart-tooltip-arrow::after { content: ""; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); border: 5px solid black; border-left-color: transparent; border-right-color: transparent; border-top-color: rgb(244, 244, 244); border-bottom-color: transparent; width: 0; height: 0; margin: 0 auto; } .ag-chart-wrapper { box-sizing: border-box; overflow: hidden; } `; export interface ChartClickEvent extends SourceEvent<Chart> { event: MouseEvent; } export interface TooltipMeta { pageX: number; pageY: number; } export interface TooltipRendererResult { content?: string; title?: string; color?: string; backgroundColor?: string; } export function toTooltipHtml(input: string | TooltipRendererResult, defaults?: TooltipRendererResult): string { if (typeof input === 'string') { return input; } defaults = defaults || {}; const { content = defaults.content || '', title = defaults.title || undefined, color = defaults.color || 'white', backgroundColor = defaults.backgroundColor || '#888' } = input; const titleHtml = title ? `<div class="${Chart.defaultTooltipClass}-title" style="color: ${color}; background-color: ${backgroundColor}">${title}</div>` : ''; return `${titleHtml}<div class="${Chart.defaultTooltipClass}-content">${content}</div>`; } export class ChartTooltip extends Observable { chart: Chart; element: HTMLDivElement; private observer?: IntersectionObserver; @reactive() enabled: boolean = true; @reactive() class: string = Chart.defaultTooltipClass; @reactive() delay: number = 0; /** * If `true`, the tooltip will be shown for the marker closest to the mouse cursor. * Only has effect on series with markers. */ @reactive() tracking: boolean = true; constructor(chart: Chart, document: Document) { super(); this.chart = chart; this.class = ''; const tooltipRoot = document.body; const element = document.createElement('div'); this.element = tooltipRoot.appendChild(element); // Detect when the chart becomes invisible and hide the tooltip as well. if (window.IntersectionObserver) { const target = this.chart.scene.canvas.element; const observer = new IntersectionObserver(entries => { for (const entry of entries) { if (entry.target === target && entry.intersectionRatio === 0) { this.toggle(false); } } }, { root: tooltipRoot }); observer.observe(target); this.observer = observer; } } destroy() { const { parentNode } = this.element; if (parentNode) { parentNode.removeChild(this.element); } if (this.observer) { this.observer.unobserve(this.chart.scene.canvas.element); } } isVisible(): boolean { const { element } = this; if (element.classList) { // if not IE11 return !element.classList.contains(Chart.defaultTooltipClass + '-hidden'); } // IE11 part. const classes = element.getAttribute('class'); if (classes) { return classes.split(' ').indexOf(Chart.defaultTooltipClass + '-hidden') < 0; } return false; } updateClass(visible?: boolean, constrained?: boolean) { const classList = [Chart.defaultTooltipClass, this.class]; if (visible !== true) { classList.push(`${Chart.defaultTooltipClass}-hidden`); } if (constrained !== true) { classList.push(`${Chart.defaultTooltipClass}-arrow`); } this.element.setAttribute('class', classList.join(' ')); } private showTimeout: number = 0; private constrained = false; /** * Shows tooltip at the given event's coordinates. * If the `html` parameter is missing, moves the existing tooltip to the new position. */ show(meta: TooltipMeta, html?: string, instantly = false) { const el = this.element; if (html !== undefined) { el.innerHTML = html; } else if (!el.innerHTML) { return; } let left = meta.pageX - el.clientWidth / 2; let top = meta.pageY - el.clientHeight - 8; this.constrained = false; if (this.chart.container) { const tooltipRect = el.getBoundingClientRect(); const minLeft = 0; const maxLeft = window.innerWidth - tooltipRect.width - 1; if (left < minLeft) { left = minLeft; this.updateClass(true, this.constrained = true); } else if (left > maxLeft) { left = maxLeft; this.updateClass(true, this.constrained = true); } if (top < window.pageYOffset) { top = meta.pageY + 20; this.updateClass(true, this.constrained = true); } } el.style.left = `${Math.round(left)}px`; el.style.top = `${Math.round(top)}px`; if (this.delay > 0 && !instantly) { this.toggle(false); this.showTimeout = window.setTimeout(() => { this.toggle(true); }, this.delay); return; } this.toggle(true); } toggle(visible?: boolean) { if (!visible) { window.clearTimeout(this.showTimeout); if (this.chart.lastPick && !this.delay) { this.chart.dehighlightDatum(); this.chart.lastPick = undefined; } } this.updateClass(visible, this.constrained); } } export abstract class Chart extends Observable { readonly id = createId(this); readonly scene: Scene; readonly background: Rect = new Rect(); readonly legend = new Legend(); protected legendAutoPadding = new Padding(); protected captionAutoPadding = 0; // top padding only static readonly defaultTooltipClass = 'ag-chart-tooltip'; private _container: HTMLElement | undefined | null = undefined; set container(value: HTMLElement | undefined | null) { if (this._container !== value) { const { parentNode } = this.element; if (parentNode != null) { parentNode.removeChild(this.element); } if (value) { value.appendChild(this.element); } this._container = value; } } get container(): HTMLElement | undefined | null { return this._container; } protected _data: any = []; set data(data: any) { this._data = data; this.series.forEach(series => series.data = data); } get data(): any { return this._data; } set width(value: number) { this.autoSize = false; if (this.width !== value) { this.scene.resize(value, this.height); this.fireEvent({ type: 'layoutChange' }); } } get width(): number { return this.scene.width; } set height(value: number) { this.autoSize = false; if (this.height !== value) { this.scene.resize(this.width, value); this.fireEvent({ type: 'layoutChange' }); } } get height(): number { return this.scene.height; } protected _autoSize = false; set autoSize(value: boolean) { if (this._autoSize !== value) { this._autoSize = value; const { style } = this.element; if (value) { const chart = this; // capture `this` for IE11 SizeMonitor.observe(this.element, size => { if (size.width !== chart.width || size.height !== chart.height) { chart.scene.resize(size.width, size.height); chart.fireEvent({ type: 'layoutChange' }); } }); style.display = 'block'; style.width = '100%'; style.height = '100%'; } else { SizeMonitor.unobserve(this.element); style.display = 'inline-block'; style.width = 'auto'; style.height = 'auto'; } } } get autoSize(): boolean { return this._autoSize; } readonly tooltip: ChartTooltip; download(fileName?: string) { this.scene.download(fileName); } padding = new Padding(20); @reactive('layoutChange') title?: Caption; @reactive('layoutChange') subtitle?: Caption; private static tooltipDocuments: Document[] = []; protected constructor(document = window.document) { super(); const root = new Group(); const background = this.background; background.fill = 'white'; root.appendChild(background); const element = this._element = document.createElement('div'); element.setAttribute('class', 'ag-chart-wrapper'); const scene = new Scene(document); this.scene = scene; scene.root = root; scene.container = element; this.autoSize = true; this.padding.addEventListener('layoutChange', this.scheduleLayout, this); const { legend } = this; legend.addEventListener('layoutChange', this.scheduleLayout, this); legend.item.label.addPropertyListener('formatter', this.updateLegend, this); legend.addPropertyListener('position', this.onLegendPositionChange, this); this.tooltip = new ChartTooltip(this, document); this.tooltip.addPropertyListener('class', () => this.tooltip.toggle()); if (Chart.tooltipDocuments.indexOf(document) < 0) { const styleElement = document.createElement('style'); styleElement.innerHTML = defaultTooltipCss; // Make sure the default tooltip style goes before other styles so it can be overridden. document.head.insertBefore(styleElement, document.head.querySelector('style')); Chart.tooltipDocuments.push(document); } this.setupDomListeners(scene.canvas.element); this.addPropertyListener('title', this.onCaptionChange); this.addPropertyListener('subtitle', this.onCaptionChange); this.addEventListener('layoutChange', this.scheduleLayout); } destroy() { this.tooltip.destroy(); SizeMonitor.unobserve(this.element); this.container = undefined; this.cleanupDomListeners(this.scene.canvas.element); this.scene.container = undefined; } private onLegendPositionChange() { this.legendAutoPadding.clear(); this.layoutPending = true; } private onCaptionChange(event: PropertyChangeEvent<this, Caption | undefined>) { const { value, oldValue } = event; if (oldValue) { oldValue.removeEventListener('change', this.scheduleLayout, this); this.scene.root!.removeChild(oldValue.node); } if (value) { value.addEventListener('change', this.scheduleLayout, this); this.scene.root!.appendChild(value.node); } } protected _element: HTMLElement; get element(): HTMLElement { return this._element; } abstract get seriesRoot(): Node; protected _axes: ChartAxis[] = []; set axes(values: ChartAxis[]) { this._axes.forEach(axis => this.detachAxis(axis)); // make linked axes go after the regular ones (simulates stable sort by `linkedTo` property) this._axes = values.filter(a => !a.linkedTo).concat(values.filter(a => a.linkedTo)); this._axes.forEach(axis => this.attachAxis(axis)); this.axesChanged = true; } get axes(): ChartAxis[] { return this._axes; } protected attachAxis(axis: ChartAxis) { this.scene.root!.insertBefore(axis.group, this.seriesRoot); } protected detachAxis(axis: ChartAxis) { this.scene.root!.removeChild(axis.group); } protected _series: Series[] = []; set series(values: Series[]) { this.removeAllSeries(); values.forEach(series => this.addSeries(series)); } get series(): Series[] { return this._series; } protected scheduleLayout() { this.layoutPending = true; } private scheduleData() { // To prevent the chart from thinking the cursor is over the same node // after a change to data (the nodes are reused on data changes). this.dehighlightDatum(); this.dataPending = true; } addSeries(series: Series, before?: Series): boolean { const { series: allSeries, seriesRoot } = this; const canAdd = allSeries.indexOf(series) < 0; if (canAdd) { const beforeIndex = before ? allSeries.indexOf(before) : -1; if (beforeIndex >= 0) { allSeries.splice(beforeIndex, 0, series); seriesRoot.insertBefore(series.group, before!.group); } else { allSeries.push(series); seriesRoot.append(series.group); } this.initSeries(series); this.seriesChanged = true; this.axesChanged = true; return true; } return false; } protected initSeries(series: Series) { series.chart = this; if (!series.data) { series.data = this.data; } series.addEventListener('layoutChange', this.scheduleLayout, this); series.addEventListener('dataChange', this.scheduleData, this); series.addEventListener('legendChange', this.updateLegend, this); series.addEventListener('nodeClick', this.onSeriesNodeClick, this); } protected freeSeries(series: Series) { series.chart = undefined; series.removeEventListener('layoutChange', this.scheduleLayout, this); series.removeEventListener('dataChange', this.scheduleData, this); series.removeEventListener('legendChange', this.updateLegend, this); series.removeEventListener('nodeClick', this.onSeriesNodeClick, this); } addSeriesAfter(series: Series, after?: Series): boolean { const { series: allSeries, seriesRoot } = this; const canAdd = allSeries.indexOf(series) < 0; if (canAdd) { const afterIndex = after ? this.series.indexOf(after) : -1; if (afterIndex >= 0) { if (afterIndex + 1 < allSeries.length) { seriesRoot.insertBefore(series.group, allSeries[afterIndex + 1].group); } else { seriesRoot.append(series.group); } this.initSeries(series); allSeries.splice(afterIndex + 1, 0, series); } else { if (allSeries.length > 0) { seriesRoot.insertBefore(series.group, allSeries[0].group); } else { seriesRoot.append(series.group); } this.initSeries(series); allSeries.unshift(series); } this.seriesChanged = true; this.axesChanged = true; } return false; } removeSeries(series: Series): boolean { const index = this.series.indexOf(series); if (index >= 0) { this.series.splice(index, 1); this.freeSeries(series); this.seriesRoot.removeChild(series.group); this.seriesChanged = true; return true; } return false; } removeAllSeries(): void { this.series.forEach(series => { this.freeSeries(series); this.seriesRoot.removeChild(series.group); }); this._series = []; // using `_series` instead of `series` to prevent infinite recursion this.seriesChanged = true; } protected assignSeriesToAxes() { this.axes.forEach(axis => { const axisName = axis.direction + 'Axis'; const boundSeries: Series[] = []; this.series.forEach(series => { if ((series as any)[axisName] === axis) { boundSeries.push(series); } }); axis.boundSeries = boundSeries; }); this.seriesChanged = false; } protected assignAxesToSeries(force: boolean = false) { // This method has to run before `assignSeriesToAxes`. const directionToAxesMap: { [key in ChartAxisDirection]?: ChartAxis[] } = {}; this.axes.forEach(axis => { const direction = axis.direction; const directionAxes = directionToAxesMap[direction] || (directionToAxesMap[direction] = []); directionAxes.push(axis); }); this.series.forEach(series => { series.directions.forEach(direction => { const axisName = direction + 'Axis'; if (!(series as any)[axisName] || force) { const directionAxes = directionToAxesMap[direction]; if (directionAxes) { const axis = this.findMatchingAxis(directionAxes, series.getKeys(direction)); if (axis) { (series as any)[axisName] = axis; } } } }); }); this.axesChanged = false; } private findMatchingAxis(directionAxes: ChartAxis[], directionKeys?: string[]): ChartAxis | undefined { for (let i = 0; i < directionAxes.length; i++) { const axis = directionAxes[i]; const axisKeys = axis.keys; if (!axisKeys.length) { return axis; } else if (directionKeys) { for (let j = 0; j < directionKeys.length; j++) { if (axisKeys.indexOf(directionKeys[j]) >= 0 ) { return axis; } } } } } protected _axesChanged = false; protected set axesChanged(value: boolean) { this._axesChanged = value; } protected get axesChanged(): boolean { return this._axesChanged; } protected _seriesChanged = false; protected set seriesChanged(value: boolean) { this._seriesChanged = value; if (value) { this.dataPending = true; } } protected get seriesChanged(): boolean { return this._seriesChanged; } protected layoutCallbackId: number = 0; set layoutPending(value: boolean) { if (value) { if (!(this.layoutCallbackId || this.dataPending)) { this.layoutCallbackId = requestAnimationFrame(this._performLayout); this.series.forEach(s => s.nodeDataPending = true); } } else if (this.layoutCallbackId) { cancelAnimationFrame(this.layoutCallbackId); this.layoutCallbackId = 0; } } /** * Only `true` while we are waiting for the layout to start. * This will be `false` if the layout has already started and is ongoing. */ get layoutPending(): boolean { return !!this.layoutCallbackId; } private readonly _performLayout = () => { this.layoutCallbackId = 0; this.background.width = this.width; this.background.height = this.height; this.performLayout(); if (!this.layoutPending) { this.fireEvent({ type: 'layoutDone' }); } } private dataCallbackId: number = 0; set dataPending(value: boolean) { if (this.dataCallbackId) { clearTimeout(this.dataCallbackId); this.dataCallbackId = 0; } if (value) { this.dataCallbackId = window.setTimeout(() => { this.dataPending = false; this.processData(); }, 0); } } get dataPending(): boolean { return !!this.dataCallbackId; } processData(): void { this.layoutPending = false; if (this.axesChanged) { this.assignAxesToSeries(true); this.assignSeriesToAxes(); } if (this.seriesChanged) { this.assignSeriesToAxes(); } this.series.forEach(s => s.processData()); this.updateLegend(); this.layoutPending = true; } private nodeData: Map<Series, readonly SeriesNodeDatum[]> = new Map(); createNodeData(): void { this.nodeData.clear(); this.series.forEach(s => { const data = s.visible ? s.createNodeData() : []; this.nodeData.set(s, data); }); } placeLabels(): Map<Series, PlacedLabel[]> { const series: Series[] = []; const data: (readonly PointLabelDatum[])[] = []; this.nodeData.forEach((d, s) => { if (s.visible && s.label.enabled) { series.push(s); data.push(s.getLabelData()); } }); const { seriesRect } = this; const labels: PlacedLabel[][] = seriesRect ? placeLabels(data, { x: 0, y: 0, width: seriesRect.width, height: seriesRect.height }) : []; return new Map(labels.map((l, i) => [series[i], l])); } private updateLegend() { const legendData: LegendDatum[] = []; this.series.filter(s => s.showInLegend).forEach(series => series.listSeriesItems(legendData)); const { formatter } = this.legend.item.label; if (formatter) { legendData.forEach(datum => datum.label.text = formatter({ id: datum.id, itemId: datum.itemId, value: datum.label.text })); } this.legend.data = legendData; } abstract performLayout(): void; private updateCallbackId: number = 0; set updatePending(value: boolean) { if (this.updateCallbackId) { clearTimeout(this.updateCallbackId); this.updateCallbackId = 0; } if (value && !this.layoutPending) { this.updateCallbackId = window.setTimeout(() => { this.update(); }, 0); } } get updatePending(): boolean { return !!this.updateCallbackId; } update() { this.updatePending = false; this.series.forEach(series => { if (series.updatePending) { series.update(); } }); } protected positionCaptions() { const { title, subtitle } = this; let titleVisible = false; let subtitleVisible = false; const spacing = 10; let paddingTop = spacing; if (title && title.enabled) { title.node.x = this.width / 2; title.node.y = paddingTop; titleVisible = true; const titleBBox = title.node.computeBBox(); // make sure to set node's x/y, then computeBBox if (titleBBox) { paddingTop = titleBBox.y + titleBBox.height; } if (subtitle && subtitle.enabled) { subtitle.node.x = this.width / 2; subtitle.node.y = paddingTop + spacing; subtitleVisible = true; const subtitleBBox = subtitle.node.computeBBox(); if (subtitleBBox) { paddingTop = subtitleBBox.y + subtitleBBox.height; } } } if (title) { title.node.visible = titleVisible; } if (subtitle) { subtitle.node.visible = subtitleVisible; } this.captionAutoPadding = Math.floor(paddingTop); } protected legendBBox: BBox = new BBox(0, 0, 0, 0); protected positionLegend() { if (!this.legend.enabled || !this.legend.data.length) { return; } const { legend, captionAutoPadding, legendAutoPadding } = this; const width = this.width; const height = this.height - captionAutoPadding; const legendGroup = legend.group; const legendSpacing = legend.spacing; let translationX = 0; let translationY = 0; let legendBBox: BBox; switch (legend.position) { case 'bottom': legend.performLayout(width - legendSpacing * 2, 0); legendBBox = legendGroup.computeBBox(); translationX = (width - legendBBox.width) / 2 - legendBBox.x; translationY = captionAutoPadding + height - legendBBox.height - legendBBox.y - legendSpacing; legendAutoPadding.bottom = legendBBox.height; break; case 'top': legend.performLayout(width - legendSpacing * 2, 0); legendBBox = legendGroup.computeBBox(); translationX = (width - legendBBox.width) / 2 - legendBBox.x; translationY = captionAutoPadding + legendSpacing - legendBBox.y; legendAutoPadding.top = legendBBox.height; break; case 'left': legend.performLayout(0, height - legendSpacing * 2); legendBBox = legendGroup.computeBBox(); translationX = legendSpacing - legendBBox.x; translationY = captionAutoPadding + (height - legendBBox.height) / 2 - legendBBox.y; legendAutoPadding.left = legendBBox.width; break; default: // case 'right': legend.performLayout(0, height - legendSpacing * 2); legendBBox = legendGroup.computeBBox(); translationX = width - legendBBox.width - legendBBox.x - legendSpacing; translationY = captionAutoPadding + (height - legendBBox.height) / 2 - legendBBox.y; legendAutoPadding.right = legendBBox.width; break; } // Round off for pixel grid alignment to work properly. legendGroup.translationX = Math.floor(translationX + legendGroup.translationX); legendGroup.translationY = Math.floor(translationY + legendGroup.translationY); this.legendBBox = legendGroup.computeBBox(); } private _onMouseDown = this.onMouseDown.bind(this); private _onMouseMove = this.onMouseMove.bind(this); private _onMouseUp = this.onMouseUp.bind(this); private _onMouseOut = this.onMouseOut.bind(this); private _onClick = this.onClick.bind(this); protected setupDomListeners(chartElement: HTMLCanvasElement) { chartElement.addEventListener('mousedown', this._onMouseDown); chartElement.addEventListener('mousemove', this._onMouseMove); chartElement.addEventListener('mouseup', this._onMouseUp); chartElement.addEventListener('mouseout', this._onMouseOut); chartElement.addEventListener('click', this._onClick); } protected cleanupDomListeners(chartElement: HTMLCanvasElement) { chartElement.removeEventListener('mousedown', this._onMouseDown); chartElement.removeEventListener('mousemove', this._onMouseMove); chartElement.removeEventListener('mouseup', this._onMouseUp); chartElement.removeEventListener('mouseout', this._onMouseOut); chartElement.removeEventListener('click', this._onClick); } // Should be available after the first layout. protected seriesRect?: BBox; getSeriesRect(): Readonly<BBox | undefined> { return this.seriesRect; } // x/y are local canvas coordinates in CSS pixels, not actual pixels private pickSeriesNode(x: number, y: number): { series: Series, node: Node } | undefined { if (!(this.seriesRect && this.seriesRect.containsPoint(x, y))) { return undefined; } const allSeries = this.series; let node: Node | undefined = undefined; for (let i = allSeries.length - 1; i >= 0; i--) { const series = allSeries[i]; if (!series.visible) { continue; } node = series.pickGroup.pickNode(x, y); if (node) { return { series, node }; } } } lastPick?: { datum: SeriesNodeDatum; node?: Shape; // We may not always have an associated node, for example // when line series are rendered without markers. event?: MouseEvent; }; // Provided x/y are in canvas coordinates. private pickClosestSeriesNodeDatum(x: number, y: number): SeriesNodeDatum | undefined { if (!this.seriesRect || !this.seriesRect.containsPoint(x, y)) { return undefined; } const allSeries = this.series; type Point = { x: number, y: number}; function getDistance(p1: Point, p2: Point): number { return Math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2); } let minDistance = Infinity; let closestDatum: SeriesNodeDatum | undefined; for (let i = allSeries.length - 1; i >= 0; i--) { const series = allSeries[i]; if (!series.visible) { continue; } const hitPoint = series.group.transformPoint(x, y); series.getNodeData().forEach(datum => { if (!datum.point) { return; } const distance = getDistance(hitPoint, datum.point); if (distance < minDistance) { minDistance = distance; closestDatum = datum; } }); } return closestDatum; } protected onMouseMove(event: MouseEvent): void { this.handleLegendMouseMove(event); if (this.tooltip.enabled) { if (this.tooltip.delay > 0) { this.tooltip.toggle(false); } this.handleTooltip(event); } } protected handleTooltip(event: MouseEvent) { const { lastPick, tooltip: { tracking: tooltipTracking } } = this; const { offsetX, offsetY } = event; const pick = this.pickSeriesNode(offsetX, offsetY); let nodeDatum: SeriesNodeDatum | undefined; if (pick && pick.node instanceof Shape) { const { node } = pick; nodeDatum = node.datum as SeriesNodeDatum; if (lastPick && lastPick.datum === nodeDatum) { lastPick.node = node; lastPick.event = event; } // Marker nodes will have the `point` info in their datums. // Highlight if not a marker node or, if not in the tracking mode, highlight markers too. if ((!node.datum.point || !tooltipTracking)) { if (!lastPick // cursor moved from empty space to a node || lastPick.node !== node) { // cursor moved from one node to another this.onSeriesDatumPick(event, node.datum, node, event); } else if (pick.series.tooltip.enabled) { // cursor moved within the same node this.tooltip.show(event); } // A non-marker node (takes precedence over marker nodes) was highlighted. // Or we are not in the tracking mode. // Either way, we are done at this point. return; } } let hideTooltip = false; // In tracking mode a tooltip is shown for the closest rendered datum. // This makes it easier to show tooltips when markers are small and/or plentiful // and also gives the ability to show tooltips even when the series were configured // to not render markers. if (tooltipTracking) { const closestDatum = this.pickClosestSeriesNodeDatum(offsetX, offsetY); if (closestDatum && closestDatum.point) { const { x, y } = closestDatum.point; const { canvas } = this.scene; const point = closestDatum.series.group.inverseTransformPoint(x, y); const canvasRect = canvas.element.getBoundingClientRect(); this.onSeriesDatumPick({ pageX: Math.round(canvasRect.left + window.pageXOffset + point.x), pageY: Math.round(canvasRect.top + window.pageYOffset + point.y) }, closestDatum, nodeDatum === closestDatum && pick ? pick.node as Shape : undefined, event); } else { hideTooltip = true; } } if (lastPick && (hideTooltip || !tooltipTracking)) { // Cursor moved from a non-marker node to empty space. this.dehighlightDatum(); this.tooltip.toggle(false); this.lastPick = undefined; } } protected onMouseDown(event: MouseEvent) {} protected onMouseUp(event: MouseEvent) {} protected onMouseOut(event: MouseEvent) { this.tooltip.toggle(false); } protected onClick(event: MouseEvent) { if (this.checkSeriesNodeClick()) { return; } if (this.checkLegendClick(event)) { return; } this.fireEvent<ChartClickEvent>({ type: 'click', event }); } private checkSeriesNodeClick(): boolean { const { lastPick } = this; if (lastPick && lastPick.event && lastPick.node) { const { event, datum } = lastPick; datum.series.fireNodeClickEvent(event, datum); return true; } return false; } private onSeriesNodeClick(event: SourceEvent<Series>) { this.fireEvent({ ...event, type: 'seriesNodeClick' }); } private checkLegendClick(event: MouseEvent): boolean { const datum = this.legend.getDatumForPoint(event.offsetX, event.offsetY); if (datum) { const { id, itemId, enabled } = datum; const series = find(this.series, series => series.id === id); if (series) { series.toggleSeriesItem(itemId, !enabled); if (enabled) { this.tooltip.toggle(false); } this.legend.fireEvent<LegendClickEvent>({ type: 'click', event, itemId, enabled: !enabled }); return true; } } return false; } private pointerInsideLegend = false; private handleLegendMouseMove(event: MouseEvent) { if (!this.legend.enabled) { return; } const { offsetX, offsetY } = event; const datum = this.legend.getDatumForPoint(offsetX, offsetY); const pointerInsideLegend = this.legendBBox.containsPoint(offsetX, offsetY); if (pointerInsideLegend) { if (!this.pointerInsideLegend) { this.pointerInsideLegend = true; } } else if (this.pointerInsideLegend) { this.pointerInsideLegend = false; // Dehighlight if the pointer was inside the legend and is now leaving it. if (this.highlightedDatum) { this.highlightedDatum = undefined; this.series.forEach(s => s.updatePending = true); } return; } const oldHighlightedDatum = this.highlightedDatum; if (datum) { const { id, itemId, enabled } = datum; if (enabled) { const series = find(this.series, series => series.id === id); if (series) { this.highlightedDatum = { series, itemId, datum: undefined }; } } } // Careful to only schedule updates when necessary. if ((this.highlightedDatum && !oldHighlightedDatum) || (this.highlightedDatum && oldHighlightedDatum && (this.highlightedDatum.series !== oldHighlightedDatum.series || this.highlightedDatum.itemId !== oldHighlightedDatum.itemId))) { this.series.forEach(s => s.updatePending = true); } } private onSeriesDatumPick(meta: TooltipMeta, datum: SeriesNodeDatum, node?: Shape, event?: MouseEvent) { const { lastPick } = this; if (lastPick) { if (lastPick.datum === datum) { return; } this.dehighlightDatum(); } this.lastPick = { datum, node, event }; this.highlightDatum(datum); const html = datum.series.tooltip.enabled && datum.series.getTooltipHtml(datum); if (html) { this.tooltip.show(meta, html); } } highlightedDatum?: SeriesNodeDatum; highlightDatum(datum: SeriesNodeDatum): void { this.scene.canvas.element.style.cursor = datum.series.cursor; this.highlightedDatum = datum; this.series.forEach(s => s.updatePending = true); } dehighlightDatum(): void { this.scene.canvas.element.style.cursor = 'default'; this.highlightedDatum = undefined; this.series.forEach(s => s.updatePending = true); } }
the_stack
import React, { useMemo, useEffect, useCallback, useContext } from "react"; import { TableContext } from "context/table"; import PropTypes from "prop-types"; import classnames from "classnames"; import { useTable, useSortBy, useRowSelect, Row, usePagination, useFilters, } from "react-table"; import { isString, kebabCase, noop } from "lodash"; import { useDebouncedCallback } from "use-debounce/lib"; import { useDeepEffect } from "utilities/hooks"; import sort from "utilities/sort"; import { AppContext } from "context/app"; import Button from "components/buttons/Button"; // @ts-ignore import FleetIcon from "components/icons/FleetIcon"; import Spinner from "components/Spinner"; import { ButtonVariant } from "components/buttons/Button/Button"; // @ts-ignore import ActionButton, { IActionButtonProps } from "./ActionButton"; const baseClass = "data-table-container"; interface IDataTableProps { columns: any; data: any; isLoading: boolean; manualSortBy?: boolean; sortHeader: any; sortDirection: any; onSort: any; // TODO: an event type disableMultiRowSelect: boolean; showMarkAllPages: boolean; isAllPagesSelected: boolean; // TODO: make dependent on showMarkAllPages toggleAllPagesSelected?: any; // TODO: an event type and make it dependent on showMarkAllPages resultsTitle: string; defaultPageSize: number; primarySelectActionButtonVariant?: ButtonVariant; primarySelectActionButtonIcon?: string; primarySelectActionButtonText?: string | ((targetIds: number[]) => string); onPrimarySelectActionClick: any; // figure out type secondarySelectActions?: IActionButtonProps[]; isClientSidePagination?: boolean; isClientSideFilter?: boolean; highlightOnHover?: boolean; searchQuery?: string; searchQueryColumn?: string; selectedDropdownFilter?: string; clearSelectionCount?: number; onSelectSingleRow?: (value: Row) => void; onResultsCountChange?: (value: number) => void; } const CLIENT_SIDE_DEFAULT_PAGE_SIZE = 20; // This data table uses react-table for implementation. The relevant documentation of the library // can be found here https://react-table.tanstack.com/docs/api/useTable const DataTable = ({ columns: tableColumns, data: tableData, isLoading, manualSortBy = false, sortHeader, sortDirection, onSort, disableMultiRowSelect, showMarkAllPages, isAllPagesSelected, toggleAllPagesSelected, resultsTitle, defaultPageSize, primarySelectActionButtonIcon, primarySelectActionButtonVariant, onPrimarySelectActionClick, primarySelectActionButtonText, secondarySelectActions, isClientSidePagination, isClientSideFilter, highlightOnHover, searchQuery, searchQueryColumn, selectedDropdownFilter, clearSelectionCount, onSelectSingleRow, onResultsCountChange, }: IDataTableProps): JSX.Element => { const { resetSelectedRows } = useContext(TableContext); const { isOnlyObserver } = useContext(AppContext); const columns = useMemo(() => { return tableColumns; }, [tableColumns]); // The table data needs to be ordered by the order we received from the API. const data = useMemo(() => { return tableData; }, [tableData]); const { headerGroups, rows, prepareRow, selectedFlatRows, toggleAllRowsSelected, isAllRowsSelected, state: tableState, page, // Instead of using 'rows', we'll use page, // which has only the rows for the active page // The rest of these things are super handy, too ;) canPreviousPage, canNextPage, // pageOptions, // pageCount, // gotoPage, nextPage, previousPage, setPageSize, setFilter, } = useTable( { columns, data, initialState: { sortBy: useMemo(() => { return [{ id: sortHeader, desc: sortDirection === "desc" }]; }, [sortHeader, sortDirection]), }, disableMultiSort: true, disableSortRemove: true, manualSortBy, // Initializes as false, but changes briefly to true on successful notification autoResetSelectedRows: resetSelectedRows, sortTypes: React.useMemo( () => ({ caseInsensitive: (a: any, b: any, id: any) => { let valueA = a.values[id]; let valueB = b.values[id]; valueA = isString(valueA) ? valueA.toLowerCase() : valueA; valueB = isString(valueB) ? valueB.toLowerCase() : valueB; if (valueB > valueA) { return -1; } if (valueB < valueA) { return 1; } return 0; }, dateStrings: (a: any, b: any, id: any) => sort.dateStringsAsc(a.values[id], b.values[id]), }), [] ), }, useFilters, useSortBy, usePagination, useRowSelect ); const { sortBy, selectedRowIds } = tableState; // Listen for changes to filters if clientSideFilter is enabled const setDebouncedClientFilter = useDebouncedCallback( (column: string, query: string) => { setFilter(column, query); }, 300 ); useEffect(() => { if (isClientSideFilter && onResultsCountChange) { onResultsCountChange(rows.length); } }, [isClientSideFilter, onResultsCountChange, rows.length]); useEffect(() => { if (isClientSideFilter && searchQueryColumn) { setDebouncedClientFilter(searchQueryColumn, searchQuery || ""); } }, [searchQuery, searchQueryColumn]); useEffect(() => { if (isClientSideFilter && selectedDropdownFilter) { selectedDropdownFilter === "all" ? setDebouncedClientFilter("platforms", "") : setDebouncedClientFilter("platforms", selectedDropdownFilter); } }, [selectedDropdownFilter]); useEffect(() => { toggleAllRowsSelected(false); }, [clearSelectionCount]); // This is used to listen for changes to sort. If there is a change // Then the sortHandler change is fired. useEffect(() => { const column = sortBy[0]; if (column !== undefined) { if ( column.id !== sortHeader || column.desc !== (sortDirection === "desc") ) { onSort(column.id, column.desc); } } else { onSort(undefined); } }, [sortBy, sortHeader, onSort, sortDirection]); useEffect(() => { if (isAllPagesSelected) { toggleAllRowsSelected(true); } }, [isAllPagesSelected, toggleAllRowsSelected]); useEffect(() => { setPageSize(CLIENT_SIDE_DEFAULT_PAGE_SIZE); }, [setPageSize]); useDeepEffect(() => { if ( Object.keys(selectedRowIds).length < rows.length && toggleAllPagesSelected ) { toggleAllPagesSelected(false); } }, [tableState.selectedRowIds, toggleAllPagesSelected]); const onToggleAllPagesClick = useCallback(() => { toggleAllPagesSelected(); }, [toggleAllPagesSelected]); const onClearSelectionClick = useCallback(() => { toggleAllRowsSelected(false); toggleAllPagesSelected(false); }, [toggleAllPagesSelected, toggleAllRowsSelected]); const onSingleRowClick = useCallback( (row) => { if (disableMultiRowSelect) { row.toggleRowSelected(); onSelectSingleRow && onSelectSingleRow(row); toggleAllRowsSelected(false); } }, [disableMultiRowSelect, onSelectSingleRow, toggleAllRowsSelected] ); const renderSelectedCount = (): JSX.Element => { return ( <p> <span> {selectedFlatRows.length} {isAllPagesSelected && "+"} </span>{" "} selected </p> ); }; const renderAreAllSelected = (): JSX.Element | null => { if (isAllPagesSelected) { return <p>All matching {resultsTitle} are selected</p>; } if (isAllRowsSelected) { return <p>All {resultsTitle} on this page are selected</p>; } return null; }; const renderActionButton = ( actionButtonProps: IActionButtonProps ): JSX.Element => { const { name, onActionButtonClick, buttonText, targetIds, variant, hideButton, icon, iconPosition, } = actionButtonProps; return ( <div className={`${baseClass}__${kebabCase(name)}`}> <ActionButton key={kebabCase(name)} name={name} buttonText={buttonText} onActionButtonClick={onActionButtonClick || noop} targetIds={targetIds} variant={variant} hideButton={hideButton} icon={icon} iconPosition={iconPosition} /> </div> ); }; const renderPrimarySelectAction = (): JSX.Element | null => { const targetIds = selectedFlatRows.map((row: any) => row.original.id); const buttonText = typeof primarySelectActionButtonText === "function" ? primarySelectActionButtonText(targetIds) : primarySelectActionButtonText; const name = buttonText ? kebabCase(buttonText) : "primary-select-action"; const actionProps = { name, buttonText: buttonText || "", onActionButtonClick: onPrimarySelectActionClick, targetIds, variant: primarySelectActionButtonVariant, icon: primarySelectActionButtonIcon, }; return !buttonText ? null : renderActionButton(actionProps); }; const renderSecondarySelectActions = (): JSX.Element[] | null => { if (secondarySelectActions) { const targetIds = selectedFlatRows.map((row: any) => row.original.id); const buttons = secondarySelectActions.map((actionProps) => { actionProps = { ...actionProps, targetIds }; return renderActionButton(actionProps); }); return buttons; } return null; }; const shouldRenderToggleAllPages = Object.keys(selectedRowIds).length >= defaultPageSize && showMarkAllPages && !isAllPagesSelected; const pageOrRows = isClientSidePagination ? page : rows; const previousButton = ( <> <FleetIcon name="chevronleft" /> Previous </> ); const nextButton = ( <> Next <FleetIcon name="chevronright" /> </> ); const tableStyles = classnames({ "data-table__table": true, "is-observer": isOnlyObserver, }); return ( <div className={baseClass}> {isLoading && ( <div className={"loading-overlay"}> <Spinner /> </div> )} <div className={"data-table data-table__wrapper"}> <table className={tableStyles}> {Object.keys(selectedRowIds).length !== 0 && ( <thead className={"active-selection"}> <tr {...headerGroups[0].getHeaderGroupProps()}> <th {...headerGroups[0].headers[0].getHeaderProps( headerGroups[0].headers[0].getSortByToggleProps() )} > {headerGroups[0].headers[0].render("Header")} </th> <th className={"active-selection__container"}> <div className={"active-selection__inner"}> {renderSelectedCount()} <div className={"active-selection__inner-left"}> {secondarySelectActions && renderSecondarySelectActions()} </div> <div className={"active-selection__inner-right"}> {primarySelectActionButtonText && renderPrimarySelectAction()} </div> {toggleAllPagesSelected && renderAreAllSelected()} {shouldRenderToggleAllPages && ( <Button onClick={onToggleAllPagesClick} variant={"text-link"} className={"light-text"} > <>Select all matching {resultsTitle}</> </Button> )} <Button onClick={onClearSelectionClick} variant={"text-link"} > Clear selection </Button> </div> </th> </tr> </thead> )} <thead> {headerGroups.map((headerGroup) => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map((column) => ( <th className={column.id ? `${column.id}__header` : ""} {...column.getHeaderProps(column.getSortByToggleProps())} > <div>{column.render("Header")}</div> </th> ))} </tr> ))} </thead> <tbody> {pageOrRows.map((row: any) => { prepareRow(row); const rowStyles = classnames({ "single-row": disableMultiRowSelect, "highlight-on-hover": highlightOnHover, }); return ( <tr className={rowStyles} {...row.getRowProps({ // @ts-ignore // TS complains about prop not existing onClick: () => { disableMultiRowSelect && onSingleRowClick(row); }, })} > {row.cells.map((cell: any) => { return ( <td className={ cell.column.id ? `${cell.column.id}__cell` : "" } {...cell.getCellProps()} > {cell.render("Cell")} </td> ); })} </tr> ); })} </tbody> </table> </div> {isClientSidePagination && ( <div className={`${baseClass}__pagination`}> <Button variant="unstyled" onClick={() => previousPage()} disabled={!canPreviousPage} > {previousButton} </Button> <Button variant="unstyled" onClick={() => nextPage()} disabled={!canNextPage} > {nextButton} </Button> </div> )} </div> ); }; DataTable.propTypes = { columns: PropTypes.arrayOf(PropTypes.object), // TODO: create proper interface for this data: PropTypes.arrayOf(PropTypes.object), // TODO: create proper interface for this isLoading: PropTypes.bool, sortHeader: PropTypes.string, sortDirection: PropTypes.string, onSort: PropTypes.func, onPrimarySelectActionClick: PropTypes.func, secondarySelectActions: PropTypes.arrayOf(PropTypes.object), }; export default DataTable;
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace appengine_v1alpha { export interface Options extends GlobalOptions { version: 'v1alpha'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * App Engine Admin API * * Provisions and manages developers&#39; App Engine applications. * * @example * ```js * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * ``` */ export class Appengine { context: APIRequestContext; apps: Resource$Apps; projects: Resource$Projects; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.apps = new Resource$Apps(this.context); this.projects = new Resource$Projects(this.context); } } /** * An SSL certificate that a user has been authorized to administer. A user is authorized to administer any certificate that applies to one of their authorized domains. */ export interface Schema$AuthorizedCertificate { /** * The SSL certificate serving the AuthorizedCertificate resource. This must be obtained independently from a certificate authority. */ certificateRawData?: Schema$CertificateRawData; /** * The user-specified display name of the certificate. This is not guaranteed to be unique. Example: My Certificate. */ displayName?: string | null; /** * Aggregate count of the domain mappings with this certificate mapped. This count includes domain mappings on applications for which the user does not have VIEWER permissions.Only returned by GET or LIST requests when specifically requested by the view=FULL_CERTIFICATE option.@OutputOnly */ domainMappingsCount?: number | null; /** * Topmost applicable domains of this certificate. This certificate applies to these domains and their subdomains. Example: example.com.@OutputOnly */ domainNames?: string[] | null; /** * The time when this certificate expires. To update the renewal time on this certificate, upload an SSL certificate with a different expiration time using AuthorizedCertificates.UpdateAuthorizedCertificate.@OutputOnly */ expireTime?: string | null; /** * Relative name of the certificate. This is a unique value autogenerated on AuthorizedCertificate resource creation. Example: 12345.@OutputOnly */ id?: string | null; /** * Only applicable if this certificate is managed by App Engine. Managed certificates are tied to the lifecycle of a DomainMapping and cannot be updated or deleted via the AuthorizedCertificates API. If this certificate is manually administered by the user, this field will be empty.@OutputOnly */ managedCertificate?: Schema$ManagedCertificate; /** * Full path to the AuthorizedCertificate resource in the API. Example: apps/myapp/authorizedCertificates/12345.@OutputOnly */ name?: string | null; /** * The full paths to user visible Domain Mapping resources that have this certificate mapped. Example: apps/myapp/domainMappings/example.com.This may not represent the full list of mapped domain mappings if the user does not have VIEWER permissions on all of the applications that have this certificate mapped. See domain_mappings_count for a complete count.Only returned by GET or LIST requests when specifically requested by the view=FULL_CERTIFICATE option.@OutputOnly */ visibleDomainMappings?: string[] | null; } /** * A domain that a user has been authorized to administer. To authorize use of a domain, verify ownership via Webmaster Central (https://www.google.com/webmasters/verification/home). */ export interface Schema$AuthorizedDomain { /** * Fully qualified domain name of the domain authorized for use. Example: example.com. */ id?: string | null; /** * Full path to the AuthorizedDomain resource in the API. Example: apps/myapp/authorizedDomains/example.com.@OutputOnly */ name?: string | null; } /** * An SSL certificate obtained from a certificate authority. */ export interface Schema$CertificateRawData { /** * Unencrypted PEM encoded RSA private key. This field is set once on certificate creation and then encrypted. The key size must be 2048 bits or fewer. Must include the header and footer. Example: -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- @InputOnly */ privateKey?: string | null; /** * PEM encoded x.509 public key certificate. This field is set once on certificate creation. Must include the header and footer. Example: -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- */ publicCertificate?: string | null; } /** * Metadata for the given google.longrunning.Operation during a google.appengine.v1.CreateVersionRequest. */ export interface Schema$CreateVersionMetadataV1 { /** * The Cloud Build ID if one was created as part of the version create. @OutputOnly */ cloudBuildId?: string | null; } /** * Metadata for the given google.longrunning.Operation during a google.appengine.v1alpha.CreateVersionRequest. */ export interface Schema$CreateVersionMetadataV1Alpha { /** * The Cloud Build ID if one was created as part of the version create. @OutputOnly */ cloudBuildId?: string | null; } /** * Metadata for the given google.longrunning.Operation during a google.appengine.v1beta.CreateVersionRequest. */ export interface Schema$CreateVersionMetadataV1Beta { /** * The Cloud Build ID if one was created as part of the version create. @OutputOnly */ cloudBuildId?: string | null; } /** * A domain serving an App Engine application. */ export interface Schema$DomainMapping { /** * Relative name of the domain serving the application. Example: example.com. */ id?: string | null; /** * Full path to the DomainMapping resource in the API. Example: apps/myapp/domainMapping/example.com.@OutputOnly */ name?: string | null; /** * The resource records required to configure this domain mapping. These records must be added to the domain's DNS configuration in order to serve the application via this domain mapping.@OutputOnly */ resourceRecords?: Schema$ResourceRecord[]; /** * SSL configuration for this domain. If unconfigured, this domain will not serve with SSL. */ sslSettings?: Schema$SslSettings; } /** * A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); \} */ export interface Schema$Empty {} /** * Metadata for the given google.cloud.location.Location. */ export interface Schema$GoogleAppengineV1betaLocationMetadata { /** * App Engine flexible environment is available in the given location.@OutputOnly */ flexibleEnvironmentAvailable?: boolean | null; /** * Output only. Search API (https://cloud.google.com/appengine/docs/standard/python/search) is available in the given location. */ searchApiAvailable?: boolean | null; /** * App Engine standard environment is available in the given location.@OutputOnly */ standardEnvironmentAvailable?: boolean | null; } /** * Response message for AuthorizedCertificates.ListAuthorizedCertificates. */ export interface Schema$ListAuthorizedCertificatesResponse { /** * The SSL certificates the user is authorized to administer. */ certificates?: Schema$AuthorizedCertificate[]; /** * Continuation token for fetching the next page of results. */ nextPageToken?: string | null; } /** * Response message for AuthorizedDomains.ListAuthorizedDomains. */ export interface Schema$ListAuthorizedDomainsResponse { /** * The authorized domains belonging to the user. */ domains?: Schema$AuthorizedDomain[]; /** * Continuation token for fetching the next page of results. */ nextPageToken?: string | null; } /** * Response message for DomainMappings.ListDomainMappings. */ export interface Schema$ListDomainMappingsResponse { /** * The domain mappings for the application. */ domainMappings?: Schema$DomainMapping[]; /** * Continuation token for fetching the next page of results. */ nextPageToken?: string | null; } /** * The response message for Locations.ListLocations. */ export interface Schema$ListLocationsResponse { /** * A list of locations that matches the specified filter in the request. */ locations?: Schema$Location[]; /** * The standard List next-page token. */ nextPageToken?: string | null; } /** * The response message for Operations.ListOperations. */ export interface Schema$ListOperationsResponse { /** * The standard List next-page token. */ nextPageToken?: string | null; /** * A list of operations that matches the specified filter in the request. */ operations?: Schema$Operation[]; } /** * A resource that represents Google Cloud Platform location. */ export interface Schema$Location { /** * The friendly name for this location, typically a nearby city name. For example, "Tokyo". */ displayName?: string | null; /** * Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"\} */ labels?: {[key: string]: string} | null; /** * The canonical id for this location. For example: "us-east1". */ locationId?: string | null; /** * Service-specific metadata. For example the available capacity at the given location. */ metadata?: {[key: string]: any} | null; /** * Resource name for the location, which may vary between implementations. For example: "projects/example-project/locations/us-east1" */ name?: string | null; } /** * Metadata for the given google.cloud.location.Location. */ export interface Schema$LocationMetadata { /** * App Engine flexible environment is available in the given location.@OutputOnly */ flexibleEnvironmentAvailable?: boolean | null; /** * Output only. Search API (https://cloud.google.com/appengine/docs/standard/python/search) is available in the given location. */ searchApiAvailable?: boolean | null; /** * App Engine standard environment is available in the given location.@OutputOnly */ standardEnvironmentAvailable?: boolean | null; } /** * A certificate managed by App Engine. */ export interface Schema$ManagedCertificate { /** * Time at which the certificate was last renewed. The renewal process is fully managed. Certificate renewal will automatically occur before the certificate expires. Renewal errors can be tracked via ManagementStatus.@OutputOnly */ lastRenewalTime?: string | null; /** * Status of certificate management. Refers to the most recent certificate acquisition or renewal attempt.@OutputOnly */ status?: string | null; } /** * This resource represents a long-running operation that is the result of a network API call. */ export interface Schema$Operation { /** * If the value is false, it means the operation is still in progress. If true, the operation is completed, and either error or response is available. */ done?: boolean | null; /** * The error result of the operation in case of failure or cancellation. */ error?: Schema$Status; /** * Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ metadata?: {[key: string]: any} | null; /** * The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the name should be a resource name ending with operations/{unique_id\}. */ name?: string | null; /** * The normal response of the operation in case of success. If the original method returns no data on success, such as Delete, the response is google.protobuf.Empty. If the original method is standard Get/Create/Update, the response should be the resource. For other methods, the response should have the type XxxResponse, where Xxx is the original method name. For example, if the original method name is TakeSnapshot(), the inferred response type is TakeSnapshotResponse. */ response?: {[key: string]: any} | null; } /** * Metadata for the given google.longrunning.Operation. */ export interface Schema$OperationMetadataV1 { createVersionMetadata?: Schema$CreateVersionMetadataV1; /** * Time that this operation completed.@OutputOnly */ endTime?: string | null; /** * Ephemeral message that may change every time the operation is polled. @OutputOnly */ ephemeralMessage?: string | null; /** * Time that this operation was created.@OutputOnly */ insertTime?: string | null; /** * API method that initiated this operation. Example: google.appengine.v1.Versions.CreateVersion.@OutputOnly */ method?: string | null; /** * Name of the resource that this operation is acting on. Example: apps/myapp/services/default.@OutputOnly */ target?: string | null; /** * User who requested this operation.@OutputOnly */ user?: string | null; /** * Durable messages that persist on every operation poll. @OutputOnly */ warning?: string[] | null; } /** * Metadata for the given google.longrunning.Operation. */ export interface Schema$OperationMetadataV1Alpha { createVersionMetadata?: Schema$CreateVersionMetadataV1Alpha; /** * Time that this operation completed.@OutputOnly */ endTime?: string | null; /** * Ephemeral message that may change every time the operation is polled. @OutputOnly */ ephemeralMessage?: string | null; /** * Time that this operation was created.@OutputOnly */ insertTime?: string | null; /** * API method that initiated this operation. Example: google.appengine.v1alpha.Versions.CreateVersion.@OutputOnly */ method?: string | null; /** * Name of the resource that this operation is acting on. Example: apps/myapp/services/default.@OutputOnly */ target?: string | null; /** * User who requested this operation.@OutputOnly */ user?: string | null; /** * Durable messages that persist on every operation poll. @OutputOnly */ warning?: string[] | null; } /** * Metadata for the given google.longrunning.Operation. */ export interface Schema$OperationMetadataV1Beta { createVersionMetadata?: Schema$CreateVersionMetadataV1Beta; /** * Time that this operation completed.@OutputOnly */ endTime?: string | null; /** * Ephemeral message that may change every time the operation is polled. @OutputOnly */ ephemeralMessage?: string | null; /** * Time that this operation was created.@OutputOnly */ insertTime?: string | null; /** * API method that initiated this operation. Example: google.appengine.v1beta.Versions.CreateVersion.@OutputOnly */ method?: string | null; /** * Name of the resource that this operation is acting on. Example: apps/myapp/services/default.@OutputOnly */ target?: string | null; /** * User who requested this operation.@OutputOnly */ user?: string | null; /** * Durable messages that persist on every operation poll. @OutputOnly */ warning?: string[] | null; } /** * A DNS resource record. */ export interface Schema$ResourceRecord { /** * Relative name of the object affected by this record. Only applicable for CNAME records. Example: 'www'. */ name?: string | null; /** * Data for this record. Values vary by record type, as defined in RFC 1035 (section 5) and RFC 1034 (section 3.6.1). */ rrdata?: string | null; /** * Resource record type. Example: AAAA. */ type?: string | null; } /** * SSL configuration for a DomainMapping resource. */ export interface Schema$SslSettings { /** * ID of the AuthorizedCertificate resource configuring SSL for the application. Clearing this field will remove SSL support.By default, a managed certificate is automatically created for every domain mapping. To omit SSL support or to configure SSL manually, specify no_managed_certificate on a CREATE or UPDATE request. You must be authorized to administer the AuthorizedCertificate resource to manually map it to a DomainMapping resource. Example: 12345. */ certificateId?: string | null; /** * Whether the mapped certificate is an App Engine managed certificate. Managed certificates are created by default with a domain mapping. To opt out, specify no_managed_certificate on a CREATE or UPDATE request.@OutputOnly */ isManagedCertificate?: boolean | null; } /** * The Status type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by gRPC (https://github.com/grpc). Each Status message contains three pieces of data: error code, error message, and error details.You can find out more about this error model and how to work with it in the API Design Guide (https://cloud.google.com/apis/design/errors). */ export interface Schema$Status { /** * The status code, which should be an enum value of google.rpc.Code. */ code?: number | null; /** * A list of messages that carry the error details. There is a common set of message types for APIs to use. */ details?: Array<{[key: string]: any}> | null; /** * A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ message?: string | null; } export class Resource$Apps { context: APIRequestContext; authorizedCertificates: Resource$Apps$Authorizedcertificates; authorizedDomains: Resource$Apps$Authorizeddomains; domainMappings: Resource$Apps$Domainmappings; locations: Resource$Apps$Locations; operations: Resource$Apps$Operations; constructor(context: APIRequestContext) { this.context = context; this.authorizedCertificates = new Resource$Apps$Authorizedcertificates( this.context ); this.authorizedDomains = new Resource$Apps$Authorizeddomains( this.context ); this.domainMappings = new Resource$Apps$Domainmappings(this.context); this.locations = new Resource$Apps$Locations(this.context); this.operations = new Resource$Apps$Operations(this.context); } } export class Resource$Apps$Authorizedcertificates { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Uploads the specified SSL certificate. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.authorizedCertificates.create({ * // Part of `parent`. Name of the parent Application resource. Example: apps/myapp. * appsId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "certificateRawData": {}, * // "displayName": "my_displayName", * // "domainMappingsCount": 0, * // "domainNames": [], * // "expireTime": "my_expireTime", * // "id": "my_id", * // "managedCertificate": {}, * // "name": "my_name", * // "visibleDomainMappings": [] * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "certificateRawData": {}, * // "displayName": "my_displayName", * // "domainMappingsCount": 0, * // "domainNames": [], * // "expireTime": "my_expireTime", * // "id": "my_id", * // "managedCertificate": {}, * // "name": "my_name", * // "visibleDomainMappings": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Apps$Authorizedcertificates$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Apps$Authorizedcertificates$Create, options?: MethodOptions ): GaxiosPromise<Schema$AuthorizedCertificate>; create( params: Params$Resource$Apps$Authorizedcertificates$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Apps$Authorizedcertificates$Create, options: | MethodOptions | BodyResponseCallback<Schema$AuthorizedCertificate>, callback: BodyResponseCallback<Schema$AuthorizedCertificate> ): void; create( params: Params$Resource$Apps$Authorizedcertificates$Create, callback: BodyResponseCallback<Schema$AuthorizedCertificate> ): void; create(callback: BodyResponseCallback<Schema$AuthorizedCertificate>): void; create( paramsOrCallback?: | Params$Resource$Apps$Authorizedcertificates$Create | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$AuthorizedCertificate> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Authorizedcertificates$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Authorizedcertificates$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/authorizedCertificates' ).replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['appsId'], pathParams: ['appsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$AuthorizedCertificate>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$AuthorizedCertificate>(parameters); } } /** * Deletes the specified SSL certificate. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.authorizedCertificates.delete({ * // Part of `name`. Name of the resource to delete. Example: apps/myapp/authorizedCertificates/12345. * appsId: 'placeholder-value', * // Part of `name`. See documentation of `appsId`. * authorizedCertificatesId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Apps$Authorizedcertificates$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Apps$Authorizedcertificates$Delete, options?: MethodOptions ): GaxiosPromise<Schema$Empty>; delete( params: Params$Resource$Apps$Authorizedcertificates$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Apps$Authorizedcertificates$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty> ): void; delete( params: Params$Resource$Apps$Authorizedcertificates$Delete, callback: BodyResponseCallback<Schema$Empty> ): void; delete(callback: BodyResponseCallback<Schema$Empty>): void; delete( paramsOrCallback?: | Params$Resource$Apps$Authorizedcertificates$Delete | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Empty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Authorizedcertificates$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Authorizedcertificates$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['appsId', 'authorizedCertificatesId'], pathParams: ['appsId', 'authorizedCertificatesId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Empty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Empty>(parameters); } } /** * Gets the specified SSL certificate. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.authorizedCertificates.get({ * // Part of `name`. Name of the resource requested. Example: apps/myapp/authorizedCertificates/12345. * appsId: 'placeholder-value', * // Part of `name`. See documentation of `appsId`. * authorizedCertificatesId: 'placeholder-value', * // Controls the set of fields returned in the GET response. * view: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "certificateRawData": {}, * // "displayName": "my_displayName", * // "domainMappingsCount": 0, * // "domainNames": [], * // "expireTime": "my_expireTime", * // "id": "my_id", * // "managedCertificate": {}, * // "name": "my_name", * // "visibleDomainMappings": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Apps$Authorizedcertificates$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Apps$Authorizedcertificates$Get, options?: MethodOptions ): GaxiosPromise<Schema$AuthorizedCertificate>; get( params: Params$Resource$Apps$Authorizedcertificates$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Apps$Authorizedcertificates$Get, options: | MethodOptions | BodyResponseCallback<Schema$AuthorizedCertificate>, callback: BodyResponseCallback<Schema$AuthorizedCertificate> ): void; get( params: Params$Resource$Apps$Authorizedcertificates$Get, callback: BodyResponseCallback<Schema$AuthorizedCertificate> ): void; get(callback: BodyResponseCallback<Schema$AuthorizedCertificate>): void; get( paramsOrCallback?: | Params$Resource$Apps$Authorizedcertificates$Get | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$AuthorizedCertificate> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Authorizedcertificates$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Authorizedcertificates$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['appsId', 'authorizedCertificatesId'], pathParams: ['appsId', 'authorizedCertificatesId'], context: this.context, }; if (callback) { createAPIRequest<Schema$AuthorizedCertificate>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$AuthorizedCertificate>(parameters); } } /** * Lists all SSL certificates the user is authorized to administer. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.authorizedCertificates.list({ * // Part of `parent`. Name of the parent Application resource. Example: apps/myapp. * appsId: 'placeholder-value', * // Maximum results to return per page. * pageSize: 'placeholder-value', * // Continuation token for fetching the next page of results. * pageToken: 'placeholder-value', * // Controls the set of fields returned in the LIST response. * view: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "certificates": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Apps$Authorizedcertificates$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Apps$Authorizedcertificates$List, options?: MethodOptions ): GaxiosPromise<Schema$ListAuthorizedCertificatesResponse>; list( params: Params$Resource$Apps$Authorizedcertificates$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Apps$Authorizedcertificates$List, options: | MethodOptions | BodyResponseCallback<Schema$ListAuthorizedCertificatesResponse>, callback: BodyResponseCallback<Schema$ListAuthorizedCertificatesResponse> ): void; list( params: Params$Resource$Apps$Authorizedcertificates$List, callback: BodyResponseCallback<Schema$ListAuthorizedCertificatesResponse> ): void; list( callback: BodyResponseCallback<Schema$ListAuthorizedCertificatesResponse> ): void; list( paramsOrCallback?: | Params$Resource$Apps$Authorizedcertificates$List | BodyResponseCallback<Schema$ListAuthorizedCertificatesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListAuthorizedCertificatesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListAuthorizedCertificatesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListAuthorizedCertificatesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Authorizedcertificates$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Authorizedcertificates$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/authorizedCertificates' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['appsId'], pathParams: ['appsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListAuthorizedCertificatesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListAuthorizedCertificatesResponse>( parameters ); } } /** * Updates the specified SSL certificate. To renew a certificate and maintain its existing domain mappings, update certificate_data with a new certificate. The new certificate must be applicable to the same domains as the original certificate. The certificate display_name may also be updated. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.authorizedCertificates.patch({ * // Part of `name`. Name of the resource to update. Example: apps/myapp/authorizedCertificates/12345. * appsId: 'placeholder-value', * // Part of `name`. See documentation of `appsId`. * authorizedCertificatesId: 'placeholder-value', * // Standard field mask for the set of fields to be updated. Updates are only supported on the certificate_raw_data and display_name fields. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "certificateRawData": {}, * // "displayName": "my_displayName", * // "domainMappingsCount": 0, * // "domainNames": [], * // "expireTime": "my_expireTime", * // "id": "my_id", * // "managedCertificate": {}, * // "name": "my_name", * // "visibleDomainMappings": [] * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "certificateRawData": {}, * // "displayName": "my_displayName", * // "domainMappingsCount": 0, * // "domainNames": [], * // "expireTime": "my_expireTime", * // "id": "my_id", * // "managedCertificate": {}, * // "name": "my_name", * // "visibleDomainMappings": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Apps$Authorizedcertificates$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Apps$Authorizedcertificates$Patch, options?: MethodOptions ): GaxiosPromise<Schema$AuthorizedCertificate>; patch( params: Params$Resource$Apps$Authorizedcertificates$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Apps$Authorizedcertificates$Patch, options: | MethodOptions | BodyResponseCallback<Schema$AuthorizedCertificate>, callback: BodyResponseCallback<Schema$AuthorizedCertificate> ): void; patch( params: Params$Resource$Apps$Authorizedcertificates$Patch, callback: BodyResponseCallback<Schema$AuthorizedCertificate> ): void; patch(callback: BodyResponseCallback<Schema$AuthorizedCertificate>): void; patch( paramsOrCallback?: | Params$Resource$Apps$Authorizedcertificates$Patch | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$AuthorizedCertificate> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$AuthorizedCertificate> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Authorizedcertificates$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Authorizedcertificates$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['appsId', 'authorizedCertificatesId'], pathParams: ['appsId', 'authorizedCertificatesId'], context: this.context, }; if (callback) { createAPIRequest<Schema$AuthorizedCertificate>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$AuthorizedCertificate>(parameters); } } } export interface Params$Resource$Apps$Authorizedcertificates$Create extends StandardParameters { /** * Part of `parent`. Name of the parent Application resource. Example: apps/myapp. */ appsId?: string; /** * Request body metadata */ requestBody?: Schema$AuthorizedCertificate; } export interface Params$Resource$Apps$Authorizedcertificates$Delete extends StandardParameters { /** * Part of `name`. Name of the resource to delete. Example: apps/myapp/authorizedCertificates/12345. */ appsId?: string; /** * Part of `name`. See documentation of `appsId`. */ authorizedCertificatesId?: string; } export interface Params$Resource$Apps$Authorizedcertificates$Get extends StandardParameters { /** * Part of `name`. Name of the resource requested. Example: apps/myapp/authorizedCertificates/12345. */ appsId?: string; /** * Part of `name`. See documentation of `appsId`. */ authorizedCertificatesId?: string; /** * Controls the set of fields returned in the GET response. */ view?: string; } export interface Params$Resource$Apps$Authorizedcertificates$List extends StandardParameters { /** * Part of `parent`. Name of the parent Application resource. Example: apps/myapp. */ appsId?: string; /** * Maximum results to return per page. */ pageSize?: number; /** * Continuation token for fetching the next page of results. */ pageToken?: string; /** * Controls the set of fields returned in the LIST response. */ view?: string; } export interface Params$Resource$Apps$Authorizedcertificates$Patch extends StandardParameters { /** * Part of `name`. Name of the resource to update. Example: apps/myapp/authorizedCertificates/12345. */ appsId?: string; /** * Part of `name`. See documentation of `appsId`. */ authorizedCertificatesId?: string; /** * Standard field mask for the set of fields to be updated. Updates are only supported on the certificate_raw_data and display_name fields. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$AuthorizedCertificate; } export class Resource$Apps$Authorizeddomains { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Lists all domains the user is authorized to administer. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.authorizedDomains.list({ * // Part of `parent`. Name of the parent Application resource. Example: apps/myapp. * appsId: 'placeholder-value', * // Maximum results to return per page. * pageSize: 'placeholder-value', * // Continuation token for fetching the next page of results. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "domains": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Apps$Authorizeddomains$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Apps$Authorizeddomains$List, options?: MethodOptions ): GaxiosPromise<Schema$ListAuthorizedDomainsResponse>; list( params: Params$Resource$Apps$Authorizeddomains$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Apps$Authorizeddomains$List, options: | MethodOptions | BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>, callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse> ): void; list( params: Params$Resource$Apps$Authorizeddomains$List, callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse> ): void; list( callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Apps$Authorizeddomains$List | BodyResponseCallback<Schema$ListAuthorizedDomainsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListAuthorizedDomainsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListAuthorizedDomainsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListAuthorizedDomainsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Authorizeddomains$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Authorizeddomains$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1alpha/apps/{appsId}/authorizedDomains').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['appsId'], pathParams: ['appsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListAuthorizedDomainsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListAuthorizedDomainsResponse>( parameters ); } } } export interface Params$Resource$Apps$Authorizeddomains$List extends StandardParameters { /** * Part of `parent`. Name of the parent Application resource. Example: apps/myapp. */ appsId?: string; /** * Maximum results to return per page. */ pageSize?: number; /** * Continuation token for fetching the next page of results. */ pageToken?: string; } export class Resource$Apps$Domainmappings { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Maps a domain to an application. A user must be authorized to administer a domain in order to map it to an application. For a list of available authorized domains, see AuthorizedDomains.ListAuthorizedDomains. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.domainMappings.create({ * // Part of `parent`. Name of the parent Application resource. Example: apps/myapp. * appsId: 'placeholder-value', * // Whether a managed certificate should be provided by App Engine. If true, a certificate ID must be manaually set in the DomainMapping resource to configure SSL for this domain. If false, a managed certificate will be provisioned and a certificate ID will be automatically populated. * noManagedCertificate: 'placeholder-value', * // Whether the domain creation should override any existing mappings for this domain. By default, overrides are rejected. * overrideStrategy: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "id": "my_id", * // "name": "my_name", * // "resourceRecords": [], * // "sslSettings": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Apps$Domainmappings$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Apps$Domainmappings$Create, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; create( params: Params$Resource$Apps$Domainmappings$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Apps$Domainmappings$Create, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; create( params: Params$Resource$Apps$Domainmappings$Create, callback: BodyResponseCallback<Schema$Operation> ): void; create(callback: BodyResponseCallback<Schema$Operation>): void; create( paramsOrCallback?: | Params$Resource$Apps$Domainmappings$Create | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Domainmappings$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Domainmappings$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1alpha/apps/{appsId}/domainMappings').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['appsId'], pathParams: ['appsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } /** * Deletes the specified domain mapping. A user must be authorized to administer the associated domain in order to delete a DomainMapping resource. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.domainMappings.delete({ * // Part of `name`. Name of the resource to delete. Example: apps/myapp/domainMappings/example.com. * appsId: 'placeholder-value', * // Part of `name`. See documentation of `appsId`. * domainMappingsId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Apps$Domainmappings$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Apps$Domainmappings$Delete, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; delete( params: Params$Resource$Apps$Domainmappings$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Apps$Domainmappings$Delete, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; delete( params: Params$Resource$Apps$Domainmappings$Delete, callback: BodyResponseCallback<Schema$Operation> ): void; delete(callback: BodyResponseCallback<Schema$Operation>): void; delete( paramsOrCallback?: | Params$Resource$Apps$Domainmappings$Delete | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Domainmappings$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Domainmappings$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/domainMappings/{domainMappingsId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['appsId', 'domainMappingsId'], pathParams: ['appsId', 'domainMappingsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } /** * Gets the specified domain mapping. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.domainMappings.get({ * // Part of `name`. Name of the resource requested. Example: apps/myapp/domainMappings/example.com. * appsId: 'placeholder-value', * // Part of `name`. See documentation of `appsId`. * domainMappingsId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "id": "my_id", * // "name": "my_name", * // "resourceRecords": [], * // "sslSettings": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Apps$Domainmappings$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Apps$Domainmappings$Get, options?: MethodOptions ): GaxiosPromise<Schema$DomainMapping>; get( params: Params$Resource$Apps$Domainmappings$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Apps$Domainmappings$Get, options: MethodOptions | BodyResponseCallback<Schema$DomainMapping>, callback: BodyResponseCallback<Schema$DomainMapping> ): void; get( params: Params$Resource$Apps$Domainmappings$Get, callback: BodyResponseCallback<Schema$DomainMapping> ): void; get(callback: BodyResponseCallback<Schema$DomainMapping>): void; get( paramsOrCallback?: | Params$Resource$Apps$Domainmappings$Get | BodyResponseCallback<Schema$DomainMapping> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$DomainMapping> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$DomainMapping> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$DomainMapping> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Domainmappings$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Domainmappings$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/domainMappings/{domainMappingsId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['appsId', 'domainMappingsId'], pathParams: ['appsId', 'domainMappingsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$DomainMapping>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$DomainMapping>(parameters); } } /** * Lists the domain mappings on an application. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.domainMappings.list({ * // Part of `parent`. Name of the parent Application resource. Example: apps/myapp. * appsId: 'placeholder-value', * // Maximum results to return per page. * pageSize: 'placeholder-value', * // Continuation token for fetching the next page of results. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "domainMappings": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Apps$Domainmappings$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Apps$Domainmappings$List, options?: MethodOptions ): GaxiosPromise<Schema$ListDomainMappingsResponse>; list( params: Params$Resource$Apps$Domainmappings$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Apps$Domainmappings$List, options: | MethodOptions | BodyResponseCallback<Schema$ListDomainMappingsResponse>, callback: BodyResponseCallback<Schema$ListDomainMappingsResponse> ): void; list( params: Params$Resource$Apps$Domainmappings$List, callback: BodyResponseCallback<Schema$ListDomainMappingsResponse> ): void; list( callback: BodyResponseCallback<Schema$ListDomainMappingsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Apps$Domainmappings$List | BodyResponseCallback<Schema$ListDomainMappingsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListDomainMappingsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListDomainMappingsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListDomainMappingsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Domainmappings$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Domainmappings$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1alpha/apps/{appsId}/domainMappings').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['appsId'], pathParams: ['appsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListDomainMappingsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListDomainMappingsResponse>(parameters); } } /** * Updates the specified domain mapping. To map an SSL certificate to a domain mapping, update certificate_id to point to an AuthorizedCertificate resource. A user must be authorized to administer the associated domain in order to update a DomainMapping resource. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.domainMappings.patch({ * // Part of `name`. Name of the resource to update. Example: apps/myapp/domainMappings/example.com. * appsId: 'placeholder-value', * // Part of `name`. See documentation of `appsId`. * domainMappingsId: 'placeholder-value', * // Whether a managed certificate should be provided by App Engine. If true, a certificate ID must be manually set in the DomainMapping resource to configure SSL for this domain. If false, a managed certificate will be provisioned and a certificate ID will be automatically populated. Only applicable if ssl_settings.certificate_id is specified in the update mask. * noManagedCertificate: 'placeholder-value', * // Required. Standard field mask for the set of fields to be updated. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "id": "my_id", * // "name": "my_name", * // "resourceRecords": [], * // "sslSettings": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Apps$Domainmappings$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Apps$Domainmappings$Patch, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; patch( params: Params$Resource$Apps$Domainmappings$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Apps$Domainmappings$Patch, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; patch( params: Params$Resource$Apps$Domainmappings$Patch, callback: BodyResponseCallback<Schema$Operation> ): void; patch(callback: BodyResponseCallback<Schema$Operation>): void; patch( paramsOrCallback?: | Params$Resource$Apps$Domainmappings$Patch | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Domainmappings$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Domainmappings$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/domainMappings/{domainMappingsId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['appsId', 'domainMappingsId'], pathParams: ['appsId', 'domainMappingsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } } export interface Params$Resource$Apps$Domainmappings$Create extends StandardParameters { /** * Part of `parent`. Name of the parent Application resource. Example: apps/myapp. */ appsId?: string; /** * Whether a managed certificate should be provided by App Engine. If true, a certificate ID must be manaually set in the DomainMapping resource to configure SSL for this domain. If false, a managed certificate will be provisioned and a certificate ID will be automatically populated. */ noManagedCertificate?: boolean; /** * Whether the domain creation should override any existing mappings for this domain. By default, overrides are rejected. */ overrideStrategy?: string; /** * Request body metadata */ requestBody?: Schema$DomainMapping; } export interface Params$Resource$Apps$Domainmappings$Delete extends StandardParameters { /** * Part of `name`. Name of the resource to delete. Example: apps/myapp/domainMappings/example.com. */ appsId?: string; /** * Part of `name`. See documentation of `appsId`. */ domainMappingsId?: string; } export interface Params$Resource$Apps$Domainmappings$Get extends StandardParameters { /** * Part of `name`. Name of the resource requested. Example: apps/myapp/domainMappings/example.com. */ appsId?: string; /** * Part of `name`. See documentation of `appsId`. */ domainMappingsId?: string; } export interface Params$Resource$Apps$Domainmappings$List extends StandardParameters { /** * Part of `parent`. Name of the parent Application resource. Example: apps/myapp. */ appsId?: string; /** * Maximum results to return per page. */ pageSize?: number; /** * Continuation token for fetching the next page of results. */ pageToken?: string; } export interface Params$Resource$Apps$Domainmappings$Patch extends StandardParameters { /** * Part of `name`. Name of the resource to update. Example: apps/myapp/domainMappings/example.com. */ appsId?: string; /** * Part of `name`. See documentation of `appsId`. */ domainMappingsId?: string; /** * Whether a managed certificate should be provided by App Engine. If true, a certificate ID must be manually set in the DomainMapping resource to configure SSL for this domain. If false, a managed certificate will be provisioned and a certificate ID will be automatically populated. Only applicable if ssl_settings.certificate_id is specified in the update mask. */ noManagedCertificate?: boolean; /** * Required. Standard field mask for the set of fields to be updated. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$DomainMapping; } export class Resource$Apps$Locations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets information about a location. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.locations.get({ * // Part of `name`. Resource name for the location. * appsId: 'placeholder-value', * // Part of `name`. See documentation of `appsId`. * locationsId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "displayName": "my_displayName", * // "labels": {}, * // "locationId": "my_locationId", * // "metadata": {}, * // "name": "my_name" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Apps$Locations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Apps$Locations$Get, options?: MethodOptions ): GaxiosPromise<Schema$Location>; get( params: Params$Resource$Apps$Locations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Apps$Locations$Get, options: MethodOptions | BodyResponseCallback<Schema$Location>, callback: BodyResponseCallback<Schema$Location> ): void; get( params: Params$Resource$Apps$Locations$Get, callback: BodyResponseCallback<Schema$Location> ): void; get(callback: BodyResponseCallback<Schema$Location>): void; get( paramsOrCallback?: | Params$Resource$Apps$Locations$Get | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Location> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Locations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Locations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/locations/{locationsId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['appsId', 'locationsId'], pathParams: ['appsId', 'locationsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Location>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Location>(parameters); } } /** * Lists information about the supported locations for this service. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.locations.list({ * // Part of `name`. The resource that owns the locations collection, if applicable. * appsId: 'placeholder-value', * // A filter to narrow down results to a preferred subset. The filtering language accepts strings like "displayName=tokyo", and is documented in more detail in AIP-160 (https://google.aip.dev/160). * filter: 'placeholder-value', * // The maximum number of results to return. If not set, the service selects a default. * pageSize: 'placeholder-value', * // A page token received from the next_page_token field in the response. Send that page token to receive the subsequent page. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "locations": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Apps$Locations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Apps$Locations$List, options?: MethodOptions ): GaxiosPromise<Schema$ListLocationsResponse>; list( params: Params$Resource$Apps$Locations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Apps$Locations$List, options: | MethodOptions | BodyResponseCallback<Schema$ListLocationsResponse>, callback: BodyResponseCallback<Schema$ListLocationsResponse> ): void; list( params: Params$Resource$Apps$Locations$List, callback: BodyResponseCallback<Schema$ListLocationsResponse> ): void; list(callback: BodyResponseCallback<Schema$ListLocationsResponse>): void; list( paramsOrCallback?: | Params$Resource$Apps$Locations$List | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListLocationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Locations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Locations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1alpha/apps/{appsId}/locations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['appsId'], pathParams: ['appsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListLocationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListLocationsResponse>(parameters); } } } export interface Params$Resource$Apps$Locations$Get extends StandardParameters { /** * Part of `name`. Resource name for the location. */ appsId?: string; /** * Part of `name`. See documentation of `appsId`. */ locationsId?: string; } export interface Params$Resource$Apps$Locations$List extends StandardParameters { /** * Part of `name`. The resource that owns the locations collection, if applicable. */ appsId?: string; /** * A filter to narrow down results to a preferred subset. The filtering language accepts strings like "displayName=tokyo", and is documented in more detail in AIP-160 (https://google.aip.dev/160). */ filter?: string; /** * The maximum number of results to return. If not set, the service selects a default. */ pageSize?: number; /** * A page token received from the next_page_token field in the response. Send that page token to receive the subsequent page. */ pageToken?: string; } export class Resource$Apps$Operations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.operations.get({ * // Part of `name`. The name of the operation resource. * appsId: 'placeholder-value', * // Part of `name`. See documentation of `appsId`. * operationsId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Apps$Operations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Apps$Operations$Get, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; get( params: Params$Resource$Apps$Operations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Apps$Operations$Get, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; get( params: Params$Resource$Apps$Operations$Get, callback: BodyResponseCallback<Schema$Operation> ): void; get(callback: BodyResponseCallback<Schema$Operation>): void; get( paramsOrCallback?: | Params$Resource$Apps$Operations$Get | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Operations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Operations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/apps/{appsId}/operations/{operationsId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['appsId', 'operationsId'], pathParams: ['appsId', 'operationsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } /** * Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns UNIMPLEMENTED.NOTE: the name binding allows API services to override the binding to use different resource name schemes, such as users/x/operations. To override the binding, API services can add a binding such as "/v1/{name=users/x\}/operations" to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.apps.operations.list({ * // Part of `name`. The name of the operation's parent resource. * appsId: 'placeholder-value', * // The standard list filter. * filter: 'placeholder-value', * // The standard list page size. * pageSize: 'placeholder-value', * // The standard list page token. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "operations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Apps$Operations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Apps$Operations$List, options?: MethodOptions ): GaxiosPromise<Schema$ListOperationsResponse>; list( params: Params$Resource$Apps$Operations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Apps$Operations$List, options: | MethodOptions | BodyResponseCallback<Schema$ListOperationsResponse>, callback: BodyResponseCallback<Schema$ListOperationsResponse> ): void; list( params: Params$Resource$Apps$Operations$List, callback: BodyResponseCallback<Schema$ListOperationsResponse> ): void; list(callback: BodyResponseCallback<Schema$ListOperationsResponse>): void; list( paramsOrCallback?: | Params$Resource$Apps$Operations$List | BodyResponseCallback<Schema$ListOperationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListOperationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListOperationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListOperationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Apps$Operations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Apps$Operations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1alpha/apps/{appsId}/operations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['appsId'], pathParams: ['appsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListOperationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListOperationsResponse>(parameters); } } } export interface Params$Resource$Apps$Operations$Get extends StandardParameters { /** * Part of `name`. The name of the operation resource. */ appsId?: string; /** * Part of `name`. See documentation of `appsId`. */ operationsId?: string; } export interface Params$Resource$Apps$Operations$List extends StandardParameters { /** * Part of `name`. The name of the operation's parent resource. */ appsId?: string; /** * The standard list filter. */ filter?: string; /** * The standard list page size. */ pageSize?: number; /** * The standard list page token. */ pageToken?: string; } export class Resource$Projects { context: APIRequestContext; locations: Resource$Projects$Locations; constructor(context: APIRequestContext) { this.context = context; this.locations = new Resource$Projects$Locations(this.context); } } export class Resource$Projects$Locations { context: APIRequestContext; operations: Resource$Projects$Locations$Operations; constructor(context: APIRequestContext) { this.context = context; this.operations = new Resource$Projects$Locations$Operations( this.context ); } /** * Gets information about a location. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.projects.locations.get({ * // Part of `name`. See documentation of `projectsId`. * locationsId: 'placeholder-value', * // Part of `name`. Resource name for the location. * projectsId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "displayName": "my_displayName", * // "labels": {}, * // "locationId": "my_locationId", * // "metadata": {}, * // "name": "my_name" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Get, options?: MethodOptions ): GaxiosPromise<Schema$Location>; get( params: Params$Resource$Projects$Locations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Get, options: MethodOptions | BodyResponseCallback<Schema$Location>, callback: BodyResponseCallback<Schema$Location> ): void; get( params: Params$Resource$Projects$Locations$Get, callback: BodyResponseCallback<Schema$Location> ): void; get(callback: BodyResponseCallback<Schema$Location>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Get | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Location> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/projects/{projectsId}/locations/{locationsId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['projectsId', 'locationsId'], pathParams: ['locationsId', 'projectsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Location>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Location>(parameters); } } /** * Lists information about the supported locations for this service. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.projects.locations.list({ * // A filter to narrow down results to a preferred subset. The filtering language accepts strings like "displayName=tokyo", and is documented in more detail in AIP-160 (https://google.aip.dev/160). * filter: 'placeholder-value', * // The maximum number of results to return. If not set, the service selects a default. * pageSize: 'placeholder-value', * // A page token received from the next_page_token field in the response. Send that page token to receive the subsequent page. * pageToken: 'placeholder-value', * // Part of `name`. The resource that owns the locations collection, if applicable. * projectsId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "locations": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$List, options?: MethodOptions ): GaxiosPromise<Schema$ListLocationsResponse>; list( params: Params$Resource$Projects$Locations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$List, options: | MethodOptions | BodyResponseCallback<Schema$ListLocationsResponse>, callback: BodyResponseCallback<Schema$ListLocationsResponse> ): void; list( params: Params$Resource$Projects$Locations$List, callback: BodyResponseCallback<Schema$ListLocationsResponse> ): void; list(callback: BodyResponseCallback<Schema$ListLocationsResponse>): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$List | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListLocationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1alpha/projects/{projectsId}/locations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['projectsId'], pathParams: ['projectsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListLocationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListLocationsResponse>(parameters); } } } export interface Params$Resource$Projects$Locations$Get extends StandardParameters { /** * Part of `name`. See documentation of `projectsId`. */ locationsId?: string; /** * Part of `name`. Resource name for the location. */ projectsId?: string; } export interface Params$Resource$Projects$Locations$List extends StandardParameters { /** * A filter to narrow down results to a preferred subset. The filtering language accepts strings like "displayName=tokyo", and is documented in more detail in AIP-160 (https://google.aip.dev/160). */ filter?: string; /** * The maximum number of results to return. If not set, the service selects a default. */ pageSize?: number; /** * A page token received from the next_page_token field in the response. Send that page token to receive the subsequent page. */ pageToken?: string; /** * Part of `name`. The resource that owns the locations collection, if applicable. */ projectsId?: string; } export class Resource$Projects$Locations$Operations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.projects.locations.operations.get({ * // Part of `name`. See documentation of `projectsId`. * locationsId: 'placeholder-value', * // Part of `name`. See documentation of `projectsId`. * operationsId: 'placeholder-value', * // Part of `name`. The name of the operation resource. * projectsId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Operations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Operations$Get, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; get( params: Params$Resource$Projects$Locations$Operations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Operations$Get, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; get( params: Params$Resource$Projects$Locations$Operations$Get, callback: BodyResponseCallback<Schema$Operation> ): void; get(callback: BodyResponseCallback<Schema$Operation>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Operations$Get | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Operations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Operations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['projectsId', 'locationsId', 'operationsId'], pathParams: ['locationsId', 'operationsId', 'projectsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } /** * Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns UNIMPLEMENTED.NOTE: the name binding allows API services to override the binding to use different resource name schemes, such as users/x/operations. To override the binding, API services can add a binding such as "/v1/{name=users/x\}/operations" to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/appengine.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const appengine = google.appengine('v1alpha'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/appengine.admin', * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await appengine.projects.locations.operations.list({ * // The standard list filter. * filter: 'placeholder-value', * // Part of `name`. See documentation of `projectsId`. * locationsId: 'placeholder-value', * // The standard list page size. * pageSize: 'placeholder-value', * // The standard list page token. * pageToken: 'placeholder-value', * // Part of `name`. The name of the operation's parent resource. * projectsId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "operations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Operations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Operations$List, options?: MethodOptions ): GaxiosPromise<Schema$ListOperationsResponse>; list( params: Params$Resource$Projects$Locations$Operations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Operations$List, options: | MethodOptions | BodyResponseCallback<Schema$ListOperationsResponse>, callback: BodyResponseCallback<Schema$ListOperationsResponse> ): void; list( params: Params$Resource$Projects$Locations$Operations$List, callback: BodyResponseCallback<Schema$ListOperationsResponse> ): void; list(callback: BodyResponseCallback<Schema$ListOperationsResponse>): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Operations$List | BodyResponseCallback<Schema$ListOperationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListOperationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListOperationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListOperationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Operations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Operations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://appengine.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1alpha/projects/{projectsId}/locations/{locationsId}/operations' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['projectsId', 'locationsId'], pathParams: ['locationsId', 'projectsId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListOperationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListOperationsResponse>(parameters); } } } export interface Params$Resource$Projects$Locations$Operations$Get extends StandardParameters { /** * Part of `name`. See documentation of `projectsId`. */ locationsId?: string; /** * Part of `name`. See documentation of `projectsId`. */ operationsId?: string; /** * Part of `name`. The name of the operation resource. */ projectsId?: string; } export interface Params$Resource$Projects$Locations$Operations$List extends StandardParameters { /** * The standard list filter. */ filter?: string; /** * Part of `name`. See documentation of `projectsId`. */ locationsId?: string; /** * The standard list page size. */ pageSize?: number; /** * The standard list page token. */ pageToken?: string; /** * Part of `name`. The name of the operation's parent resource. */ projectsId?: string; } }
the_stack
import './gr-related-change'; import '../../plugins/gr-endpoint-decorator/gr-endpoint-decorator'; import '../../plugins/gr-endpoint-param/gr-endpoint-param'; import '../../plugins/gr-endpoint-slot/gr-endpoint-slot'; import {classMap} from 'lit/directives/class-map'; import {LitElement, css, html, nothing, TemplateResult} from 'lit'; import {customElement, property, state} from 'lit/decorators'; import {sharedStyles} from '../../../styles/shared-styles'; import { SubmittedTogetherInfo, ChangeInfo, RelatedChangeAndCommitInfo, RelatedChangesInfo, PatchSetNum, CommitId, } from '../../../types/common'; import {getAppContext} from '../../../services/app-context'; import {ParsedChangeInfo} from '../../../types/types'; import {GerritNav} from '../../core/gr-navigation/gr-navigation'; import {truncatePath} from '../../../utils/path-list-util'; import {pluralize} from '../../../utils/string-util'; import { changeIsOpen, getRevisionKey, isChangeInfo, } from '../../../utils/change-util'; import {Interaction} from '../../../constants/reporting'; import {fontStyles} from '../../../styles/gr-font-styles'; /** What is the maximum number of shown changes in collapsed list? */ const DEFALT_NUM_CHANGES_WHEN_COLLAPSED = 3; export interface ChangeMarkersInList { showCurrentChangeArrow: boolean; showWhenCollapsed: boolean; showTopArrow: boolean; showBottomArrow: boolean; } export enum Section { RELATED_CHANGES = 'related changes', SUBMITTED_TOGETHER = 'submitted together', SAME_TOPIC = 'same topic', MERGE_CONFLICTS = 'merge conflicts', CHERRY_PICKS = 'cherry picks', } @customElement('gr-related-changes-list') export class GrRelatedChangesList extends LitElement { @property() change?: ParsedChangeInfo; @property({type: String}) patchNum?: PatchSetNum; @property() mergeable?: boolean; @state() submittedTogether?: SubmittedTogetherInfo = { changes: [], non_visible_changes: 0, }; @state() relatedChanges: RelatedChangeAndCommitInfo[] = []; @state() conflictingChanges: ChangeInfo[] = []; @state() cherryPickChanges: ChangeInfo[] = []; @state() sameTopicChanges: ChangeInfo[] = []; private readonly restApiService = getAppContext().restApiService; static override get styles() { return [ sharedStyles, css` .note { color: var(--error-text-color); margin-left: 1.2em; } section { margin-bottom: var(--spacing-l); } .relatedChangeLine { display: flex; visibility: visible; height: auto; } .marker.arrow { visibility: hidden; min-width: 20px; } .marker.arrowToCurrentChange { min-width: 20px; text-align: center; } .marker.space { height: 1px; min-width: 20px; } gr-related-collapse[collapsed] .marker.arrow { visibility: visible; min-width: auto; } gr-related-collapse[collapsed] .relatedChangeLine.show-when-collapsed { visibility: visible; height: auto; } /* keep width, so width of section and position of show all button * are set according to width of all (even hidden) elements */ gr-related-collapse[collapsed] .relatedChangeLine { visibility: hidden; height: 0px; } `, ]; } override render() { const sectionSize = this.sectionSizeFactory( this.relatedChanges.length, this.submittedTogether?.changes.length || 0, this.sameTopicChanges.length, this.conflictingChanges.length, this.cherryPickChanges.length ); const sectionRenderers = [ this.renderRelationChain, this.renderSubmittedTogether, this.renderSameTopic, this.renderMergeConflicts, this.renderCherryPicks, ]; let firstNonEmptySectionFound = false; const sections = []; for (const renderer of sectionRenderers) { const section: TemplateResult<1> | undefined = renderer.call( this, !firstNonEmptySectionFound, sectionSize ); firstNonEmptySectionFound = firstNonEmptySectionFound || !!section; sections.push(section); } return html`<gr-endpoint-decorator name="related-changes-section"> <gr-endpoint-param name="change" .value=${this.change} ></gr-endpoint-param> <gr-endpoint-slot name="top"></gr-endpoint-slot> ${sections} <gr-endpoint-slot name="bottom"></gr-endpoint-slot> </gr-endpoint-decorator>`; } private renderRelationChain( isFirst: boolean, sectionSize: (section: Section) => number ) { if (this.relatedChanges.length === 0) { return undefined; } const relatedChangesMarkersPredicate = this.markersPredicateFactory( this.relatedChanges.length, this.relatedChanges.findIndex(relatedChange => this._changesEqual(relatedChange, this.change) ), sectionSize(Section.RELATED_CHANGES) ); const connectedRevisions = this._computeConnectedRevisions( this.change, this.patchNum, this.relatedChanges ); return html`<section id="relatedChanges"> <gr-related-collapse title="Relation chain" class="${classMap({first: isFirst})}" .length=${this.relatedChanges.length} .numChangesWhenCollapsed=${sectionSize(Section.RELATED_CHANGES)} > ${this.relatedChanges.map( (change, index) => html`<div class="${classMap({ ['relatedChangeLine']: true, ['show-when-collapsed']: relatedChangesMarkersPredicate(index).showWhenCollapsed, })}" > ${this.renderMarkers( relatedChangesMarkersPredicate(index) )}<gr-related-change .change="${change}" .connectedRevisions="${connectedRevisions}" .href="${change?._change_number ? GerritNav.getUrlForChangeById( change._change_number, change.project, change._revision_number as PatchSetNum ) : ''}" .showChangeStatus=${true} >${change.commit.subject}</gr-related-change > </div>` )} </gr-related-collapse> </section>`; } private renderSubmittedTogether( isFirst: boolean, sectionSize: (section: Section) => number ) { const submittedTogetherChanges = this.submittedTogether?.changes ?? []; if ( !submittedTogetherChanges.length && !this.submittedTogether?.non_visible_changes ) { return undefined; } const countNonVisibleChanges = this.submittedTogether?.non_visible_changes ?? 0; const submittedTogetherMarkersPredicate = this.markersPredicateFactory( submittedTogetherChanges.length, submittedTogetherChanges.findIndex(relatedChange => this._changesEqual(relatedChange, this.change) ), sectionSize(Section.SUBMITTED_TOGETHER) ); return html`<section id="submittedTogether"> <gr-related-collapse title="Submitted together" class="${classMap({first: isFirst})}" .length=${submittedTogetherChanges.length} .numChangesWhenCollapsed=${sectionSize(Section.SUBMITTED_TOGETHER)} > ${submittedTogetherChanges.map( (change, index) => html`<div class="${classMap({ ['relatedChangeLine']: true, ['show-when-collapsed']: submittedTogetherMarkersPredicate(index).showWhenCollapsed, })}" > ${this.renderMarkers( submittedTogetherMarkersPredicate(index) )}<gr-related-change .label="${this.renderChangeTitle(change)}" .change="${change}" .href="${GerritNav.getUrlForChangeById( change._number, change.project )}" .showSubmittableCheck=${true} >${this.renderChangeLine(change)}</gr-related-change > </div>` )} </gr-related-collapse> <div class="note" ?hidden=${!countNonVisibleChanges}> (+ ${pluralize(countNonVisibleChanges, 'non-visible change')}) </div> </section>`; } private renderSameTopic( isFirst: boolean, sectionSize: (section: Section) => number ) { if (!this.sameTopicChanges?.length) { return undefined; } const sameTopicMarkersPredicate = this.markersPredicateFactory( this.sameTopicChanges.length, -1, sectionSize(Section.SAME_TOPIC) ); return html`<section id="sameTopic"> <gr-related-collapse title="Same topic" class="${classMap({first: isFirst})}" .length=${this.sameTopicChanges.length} .numChangesWhenCollapsed=${sectionSize(Section.SAME_TOPIC)} > ${this.sameTopicChanges.map( (change, index) => html`<div class="${classMap({ ['relatedChangeLine']: true, ['show-when-collapsed']: sameTopicMarkersPredicate(index).showWhenCollapsed, })}" > ${this.renderMarkers( sameTopicMarkersPredicate(index) )}<gr-related-change .change="${change}" .label="${this.renderChangeTitle(change)}" .href="${GerritNav.getUrlForChangeById( change._number, change.project )}" >${this.renderChangeLine(change)}</gr-related-change > </div>` )} </gr-related-collapse> </section>`; } private renderMergeConflicts( isFirst: boolean, sectionSize: (section: Section) => number ) { if (!this.conflictingChanges?.length) { return undefined; } const mergeConflictsMarkersPredicate = this.markersPredicateFactory( this.conflictingChanges.length, -1, sectionSize(Section.MERGE_CONFLICTS) ); return html`<section id="mergeConflicts"> <gr-related-collapse title="Merge conflicts" class="${classMap({first: isFirst})}" .length=${this.conflictingChanges.length} .numChangesWhenCollapsed=${sectionSize(Section.MERGE_CONFLICTS)} > ${this.conflictingChanges.map( (change, index) => html`<div class="${classMap({ ['relatedChangeLine']: true, ['show-when-collapsed']: mergeConflictsMarkersPredicate(index).showWhenCollapsed, })}" > ${this.renderMarkers( mergeConflictsMarkersPredicate(index) )}<gr-related-change .change="${change}" .href="${GerritNav.getUrlForChangeById( change._number, change.project )}" >${change.subject}</gr-related-change > </div>` )} </gr-related-collapse> </section>`; } private renderCherryPicks( isFirst: boolean, sectionSize: (section: Section) => number ) { if (!this.cherryPickChanges.length) { return undefined; } const cherryPicksMarkersPredicate = this.markersPredicateFactory( this.cherryPickChanges.length, -1, sectionSize(Section.CHERRY_PICKS) ); return html`<section id="cherryPicks"> <gr-related-collapse title="Cherry picks" class="${classMap({first: isFirst})}" .length=${this.cherryPickChanges.length} .numChangesWhenCollapsed=${sectionSize(Section.CHERRY_PICKS)} > ${this.cherryPickChanges.map( (change, index) => html`<div class="${classMap({ ['relatedChangeLine']: true, ['show-when-collapsed']: cherryPicksMarkersPredicate(index).showWhenCollapsed, })}" > ${this.renderMarkers( cherryPicksMarkersPredicate(index) )}<gr-related-change .change="${change}" .href="${GerritNav.getUrlForChangeById( change._number, change.project )}" >${change.branch}: ${change.subject}</gr-related-change > </div>` )} </gr-related-collapse> </section>`; } private renderChangeTitle(change: ChangeInfo) { return `${change.project}: ${change.branch}: ${change.subject}`; } private renderChangeLine(change: ChangeInfo) { const truncatedRepo = truncatePath(change.project, 2); return html`<span class="truncatedRepo" .title="${change.project}" >${truncatedRepo}</span >: ${change.branch}: ${change.subject}`; } sectionSizeFactory( relatedChangesLen: number, submittedTogetherLen: number, sameTopicLen: number, mergeConflictsLen: number, cherryPicksLen: number ) { const calcDefaultSize = (length: number) => Math.min(length, DEFALT_NUM_CHANGES_WHEN_COLLAPSED); const sectionSizes = [ { section: Section.RELATED_CHANGES, size: calcDefaultSize(relatedChangesLen), len: relatedChangesLen, }, { section: Section.SUBMITTED_TOGETHER, size: calcDefaultSize(submittedTogetherLen), len: submittedTogetherLen, }, { section: Section.SAME_TOPIC, size: calcDefaultSize(sameTopicLen), len: sameTopicLen, }, { section: Section.MERGE_CONFLICTS, size: calcDefaultSize(mergeConflictsLen), len: mergeConflictsLen, }, { section: Section.CHERRY_PICKS, size: calcDefaultSize(cherryPicksLen), len: cherryPicksLen, }, ]; const FILLER = 1; // space for header let totalSize = sectionSizes.reduce( (acc, val) => acc + val.size + (val.size !== 0 ? FILLER : 0), 0 ); const MAX_SIZE = 16; for (let i = 0; i < sectionSizes.length; i++) { if (totalSize >= MAX_SIZE) break; const sizeObj = sectionSizes[i]; if (sizeObj.size === sizeObj.len) continue; const newSize = Math.min( MAX_SIZE - totalSize + sizeObj.size, sizeObj.len ); totalSize += newSize - sizeObj.size; sizeObj.size = newSize; } return (section: Section) => { const sizeObj = sectionSizes.find(sizeObj => sizeObj.section === section); if (sizeObj) return sizeObj.size; return DEFALT_NUM_CHANGES_WHEN_COLLAPSED; }; } markersPredicateFactory( length: number, highlightIndex: number, numChangesShownWhenCollapsed = DEFALT_NUM_CHANGES_WHEN_COLLAPSED ): (index: number) => ChangeMarkersInList { const showWhenCollapsedPredicate = (index: number) => { if (highlightIndex === -1) return index < numChangesShownWhenCollapsed; if (highlightIndex === 0) return index <= numChangesShownWhenCollapsed - 1; if (highlightIndex === length - 1) return index >= length - numChangesShownWhenCollapsed; let numBeforeHighlight = Math.floor(numChangesShownWhenCollapsed / 2); let numAfterHighlight = Math.floor(numChangesShownWhenCollapsed / 2) - (numChangesShownWhenCollapsed % 2 ? 0 : 1); numBeforeHighlight += Math.max( highlightIndex + numAfterHighlight - length + 1, 0 ); numAfterHighlight -= Math.min(0, highlightIndex - numBeforeHighlight); return ( highlightIndex - numBeforeHighlight <= index && index <= highlightIndex + numAfterHighlight ); }; return (index: number) => { return { showCurrentChangeArrow: highlightIndex !== -1 && index === highlightIndex, showWhenCollapsed: showWhenCollapsedPredicate(index), showTopArrow: index >= 1 && index !== highlightIndex && showWhenCollapsedPredicate(index) && !showWhenCollapsedPredicate(index - 1), showBottomArrow: index <= length - 2 && index !== highlightIndex && showWhenCollapsedPredicate(index) && !showWhenCollapsedPredicate(index + 1), }; }; } renderMarkers(changeMarkers: ChangeMarkersInList) { if (changeMarkers.showCurrentChangeArrow) { return html`<span role="img" class="marker arrowToCurrentChange" aria-label="Arrow marking current change" >➔</span >`; } if (changeMarkers.showTopArrow) { return html`<span role="img" class="marker arrow" aria-label="Arrow marking change has collapsed ancestors" ><iron-icon icon="gr-icons:arrowDropUp"></iron-icon ></span> `; } if (changeMarkers.showBottomArrow) { return html`<span role="img" class="marker arrow" aria-label="Arrow marking change has collapsed descendants" ><iron-icon icon="gr-icons:arrowDropDown"></iron-icon ></span> `; } return html`<span class="marker space"></span>`; } reload(getRelatedChanges?: Promise<RelatedChangesInfo | undefined>) { const change = this.change; if (!change) return Promise.reject(new Error('change missing')); if (!this.patchNum) return Promise.reject(new Error('patchNum missing')); if (!getRelatedChanges) { getRelatedChanges = this.restApiService.getRelatedChanges( change._number, this.patchNum ); } const promises: Array<Promise<void>> = [ getRelatedChanges.then(response => { if (!response) { throw new Error('getRelatedChanges returned undefined response'); } this.relatedChanges = response?.changes ?? []; }), this.restApiService .getChangesSubmittedTogether(change._number) .then(response => { this.submittedTogether = response; }), this.restApiService .getChangeCherryPicks(change.project, change.change_id, change._number) .then(response => { this.cherryPickChanges = response || []; }), ]; // Get conflicts if change is open and is mergeable. // Mergeable is output of restApiServict.getMergeable from gr-change-view if (changeIsOpen(change) && this.mergeable) { promises.push( this.restApiService .getChangeConflicts(change._number) .then(response => { this.conflictingChanges = response ?? []; }) ); } if (change.topic) { const changeTopic = change.topic; promises.push( this.restApiService.getConfig().then(config => { if (config && !config.change.submit_whole_topic) { return this.restApiService .getChangesWithSameTopic(changeTopic, { openChangesOnly: true, changeToExclude: change._number, }) .then(response => { if (changeTopic === this.change?.topic) { this.sameTopicChanges = response ?? []; } }); } this.sameTopicChanges = []; return Promise.resolve(); }) ); } return Promise.all(promises); } /** * Do the given objects describe the same change? Compares the changes by * their numbers. */ _changesEqual( a?: ChangeInfo | RelatedChangeAndCommitInfo, b?: ChangeInfo | ParsedChangeInfo | RelatedChangeAndCommitInfo ) { const aNum = this._getChangeNumber(a); const bNum = this._getChangeNumber(b); return aNum === bNum; } /** * Get the change number from either a ChangeInfo (such as those included in * SubmittedTogetherInfo responses) or get the change number from a * RelatedChangeAndCommitInfo (such as those included in a * RelatedChangesInfo response). */ _getChangeNumber( change?: ChangeInfo | ParsedChangeInfo | RelatedChangeAndCommitInfo ) { // Default to 0 if change property is not defined. if (!change) return 0; if (isChangeInfo(change)) { return change._number; } return change._change_number; } /* * A list of commit ids connected to change to understand if other change * is direct or indirect ancestor / descendant. */ _computeConnectedRevisions( change?: ParsedChangeInfo, patchNum?: PatchSetNum, relatedChanges?: RelatedChangeAndCommitInfo[] ) { if (!patchNum || !relatedChanges || !change) { return []; } const connected: CommitId[] = []; const changeRevision = getRevisionKey(change, patchNum); const commits = relatedChanges.map(c => c.commit); let pos = commits.length - 1; while (pos >= 0) { const commit: CommitId = commits[pos].commit; connected.push(commit); // TODO(TS): Ensure that both (commit and changeRevision) are string and use === instead // eslint-disable-next-line eqeqeq if (commit == changeRevision) { break; } pos--; } while (pos >= 0) { for (let i = 0; i < commits[pos].parents.length; i++) { if (connected.includes(commits[pos].parents[i].commit)) { connected.push(commits[pos].commit); break; } } --pos; } return connected; } } @customElement('gr-related-collapse') export class GrRelatedCollapse extends LitElement { @property() override title = ''; @property({type: Boolean}) showAll = false; @property({type: Boolean, reflect: true}) collapsed = true; @property() length = 0; @property() numChangesWhenCollapsed = DEFALT_NUM_CHANGES_WHEN_COLLAPSED; private readonly reporting = getAppContext().reportingService; static override get styles() { return [ sharedStyles, fontStyles, css` .title { color: var(--deemphasized-text-color); display: flex; align-self: flex-end; margin-left: 20px; } gr-button { display: flex; } gr-button iron-icon { color: inherit; --iron-icon-height: 18px; --iron-icon-width: 18px; } .container { justify-content: space-between; display: flex; margin-bottom: var(--spacing-s); } :host(.first) .container { margin-bottom: var(--spacing-m); } `, ]; } override render() { const title = html`<h3 class="title heading-3">${this.title}</h3>`; const collapsible = this.length > this.numChangesWhenCollapsed; this.collapsed = !this.showAll && collapsible; let button: TemplateResult | typeof nothing = nothing; if (collapsible) { let buttonText = 'Show less'; let buttonIcon = 'expand-less'; if (!this.showAll) { buttonText = `Show all (${this.length})`; buttonIcon = 'expand-more'; } button = html`<gr-button link="" @click="${this.toggle}" >${buttonText}<iron-icon icon="gr-icons:${buttonIcon}"></iron-icon ></gr-button>`; } return html`<div class="container">${title}${button}</div> <div><slot></slot></div>`; } private toggle(e: MouseEvent) { e.stopPropagation(); this.showAll = !this.showAll; this.reporting.reportInteraction(Interaction.TOGGLE_SHOW_ALL_BUTTON, { sectionName: this.title, toState: this.showAll ? 'Show all' : 'Show less', }); } } declare global { interface HTMLElementTagNameMap { 'gr-related-changes-list': GrRelatedChangesList; 'gr-related-collapse': GrRelatedCollapse; } }
the_stack
import { Scene, Vector3, Ray, TransformNode, Mesh, Color3, Color4, UniversalCamera, Quaternion, AnimationGroup, ExecuteCodeAction, ActionManager, ParticleSystem, Texture, SphereParticleEmitter, Sound, Observable, ShadowGenerator } from "@babylonjs/core"; import { PlayerInput } from "./inputController"; export class Player extends TransformNode { public camera: UniversalCamera; public scene: Scene; private _input: PlayerInput; //Player public mesh: Mesh; //outer collisionbox of player //Camera private _camRoot: TransformNode; private _yTilt: TransformNode; //animations private _run: AnimationGroup; private _idle: AnimationGroup; private _jump: AnimationGroup; private _land: AnimationGroup; private _dash: AnimationGroup; // animation trackers private _currentAnim: AnimationGroup = null; private _prevAnim: AnimationGroup; private _isFalling: boolean = false; private _jumped: boolean = false; //const values private static readonly PLAYER_SPEED: number = 0.45; private static readonly JUMP_FORCE: number = 0.80; private static readonly GRAVITY: number = -2.8; private static readonly DASH_FACTOR: number = 2.5; private static readonly DASH_TIME: number = 10; //how many frames the dash lasts private static readonly DOWN_TILT: Vector3 = new Vector3(0.8290313946973066, 0, 0); private static readonly ORIGINAL_TILT: Vector3 = new Vector3(0.5934119456780721, 0, 0); public dashTime: number = 0; //player movement vars private _deltaTime: number = 0; private _h: number; private _v: number; private _moveDirection: Vector3 = new Vector3(); private _inputAmt: number; //dashing private _dashPressed: boolean; private _canDash: boolean = true; //gravity, ground detection, jumping private _gravity: Vector3 = new Vector3(); private _lastGroundPos: Vector3 = Vector3.Zero(); // keep track of the last grounded position private _grounded: boolean; private _jumpCount: number = 1; //player variables public lanternsLit: number = 1; //num lanterns lit public totalLanterns: number; public win: boolean = false; //whether the game is won //sparkler public sparkler: ParticleSystem; // sparkler particle system public sparkLit: boolean = true; public sparkReset: boolean = false; //moving platforms public _raisePlatform: boolean; //sfx public lightSfx: Sound; public sparkResetSfx: Sound; private _resetSfx: Sound; private _walkingSfx: Sound; private _jumpingSfx: Sound; private _dashingSfx: Sound; //observables public onRun = new Observable(); //tutorial public tutorial_move; public tutorial_dash; public tutorial_jump; constructor(assets, scene: Scene, shadowGenerator: ShadowGenerator, input?: PlayerInput) { super("player", scene); this.scene = scene; //set up sounds this._loadSounds(this.scene); //camera this._setupPlayerCamera(); this.mesh = assets.mesh; this.mesh.parent = this; this.scene.getLightByName("sparklight").parent = this.scene.getTransformNodeByName("Empty"); this._idle = assets.animationGroups[1]; this._jump = assets.animationGroups[2]; this._land = assets.animationGroups[3]; this._run = assets.animationGroups[4]; this._dash = assets.animationGroups[0]; //--COLLISIONS-- this.mesh.actionManager = new ActionManager(this.scene); this.mesh.actionManager.registerAction( new ExecuteCodeAction( { trigger: ActionManager.OnIntersectionEnterTrigger, parameter: this.scene.getMeshByName("destination") }, () => { if(this.lanternsLit == 22){ this.win = true; //tilt camera to look at where the fireworks will be displayed this._yTilt.rotation = new Vector3(5.689773361501514, 0.23736477827122882, 0); this._yTilt.position = new Vector3(0, 6, 0); this.camera.position.y = 17; } } ) ); //if player falls through "world", reset the position to the last safe grounded position this.mesh.actionManager.registerAction( new ExecuteCodeAction({ trigger: ActionManager.OnIntersectionEnterTrigger, parameter: this.scene.getMeshByName("ground") }, () => { this.mesh.position.copyFrom(this._lastGroundPos); // need to use copy or else they will be both pointing at the same thing & update together //--SOUNDS-- this._resetSfx.play(); } ) ); //--SOUNDS-- //observable for when to play the walking sfx this.onRun.add((play) => { if (play && !this._walkingSfx.isPlaying) { this._walkingSfx.play(); } else if (!play && this._walkingSfx.isPlaying) { this._walkingSfx.stop(); this._walkingSfx.isPlaying = false; // make sure that walkingsfx.stop is called only once } }) this._createSparkles(); //create the sparkler particle system this._setUpAnimations(); shadowGenerator.addShadowCaster(assets.mesh); this._input = input; } private _updateFromControls(): void { this._deltaTime = this.scene.getEngine().getDeltaTime() / 1000.0; this._moveDirection = Vector3.Zero(); this._h = this._input.horizontal; //right, x this._v = this._input.vertical; //fwd, z //tutorial, if the player moves for the first time if((this._h != 0 || this._v != 0) && !this.tutorial_move){ this.tutorial_move = true; } //--DASHING-- //limit dash to once per ground/platform touch //can only dash when in the air if (this._input.dashing && !this._dashPressed && this._canDash && !this._grounded) { this._canDash = false; this._dashPressed = true; //sfx and animations this._currentAnim = this._dash; this._dashingSfx.play(); //tutorial, if the player dashes for the first time if(!this.tutorial_dash){ this.tutorial_dash = true; } } let dashFactor = 1; //if you're dashing, scale movement if (this._dashPressed) { if (this.dashTime > Player.DASH_TIME) { this.dashTime = 0; this._dashPressed = false; } else { dashFactor = Player.DASH_FACTOR; } this.dashTime++; } //--MOVEMENTS BASED ON CAMERA (as it rotates)-- let fwd = this._camRoot.forward; let right = this._camRoot.right; let correctedVertical = fwd.scaleInPlace(this._v); let correctedHorizontal = right.scaleInPlace(this._h); //movement based off of camera's view let move = correctedHorizontal.addInPlace(correctedVertical); //clear y so that the character doesnt fly up, normalize for next step, taking into account whether we've DASHED or not this._moveDirection = new Vector3((move).normalize().x * dashFactor, 0, (move).normalize().z * dashFactor); //clamp the input value so that diagonal movement isn't twice as fast let inputMag = Math.abs(this._h) + Math.abs(this._v); if (inputMag < 0) { this._inputAmt = 0; } else if (inputMag > 1) { this._inputAmt = 1; } else { this._inputAmt = inputMag; } //final movement that takes into consideration the inputs this._moveDirection = this._moveDirection.scaleInPlace(this._inputAmt * Player.PLAYER_SPEED); //check if there is movement to determine if rotation is needed let input = new Vector3(this._input.horizontalAxis, 0, this._input.verticalAxis); //along which axis is the direction if (input.length() == 0) {//if there's no input detected, prevent rotation and keep player in same rotation return; } //rotation based on input & the camera angle let angle = Math.atan2(this._input.horizontalAxis, this._input.verticalAxis); angle += this._camRoot.rotation.y; let targ = Quaternion.FromEulerAngles(0, angle, 0); this.mesh.rotationQuaternion = Quaternion.Slerp(this.mesh.rotationQuaternion, targ, 10 * this._deltaTime); } private _setUpAnimations(): void { this.scene.stopAllAnimations(); this._run.loopAnimation = true; this._idle.loopAnimation = true; //initialize current and previous this._currentAnim = this._idle; this._prevAnim = this._land; } private _animatePlayer(): void { if (!this._dashPressed && !this._isFalling && !this._jumped && (this._input.inputMap["ArrowUp"] || this._input.mobileUp || this._input.inputMap["ArrowDown"] || this._input.mobileDown || this._input.inputMap["ArrowLeft"] || this._input.mobileLeft || this._input.inputMap["ArrowRight"] || this._input.mobileRight)) { this._currentAnim = this._run; this.onRun.notifyObservers(true); } else if (this._jumped && !this._isFalling && !this._dashPressed) { this._currentAnim = this._jump; } else if (!this._isFalling && this._grounded) { this._currentAnim = this._idle; //only notify observer if it's playing if(this.scene.getSoundByName("walking").isPlaying){ this.onRun.notifyObservers(false); } } else if (this._isFalling) { this._currentAnim = this._land; } //Animations if(this._currentAnim != null && this._prevAnim !== this._currentAnim){ this._prevAnim.stop(); this._currentAnim.play(this._currentAnim.loopAnimation); this._prevAnim = this._currentAnim; } } //--GROUND DETECTION-- //Send raycast to the floor to detect if there are any hits with meshes below the character private _floorRaycast(offsetx: number, offsetz: number, raycastlen: number): Vector3 { //position the raycast from bottom center of mesh let raycastFloorPos = new Vector3(this.mesh.position.x + offsetx, this.mesh.position.y + 0.5, this.mesh.position.z + offsetz); let ray = new Ray(raycastFloorPos, Vector3.Up().scale(-1), raycastlen); //defined which type of meshes should be pickable let predicate = function (mesh) { return mesh.isPickable && mesh.isEnabled(); } let pick = this.scene.pickWithRay(ray, predicate); if (pick.hit) { //grounded return pick.pickedPoint; } else { //not grounded return Vector3.Zero(); } } //raycast from the center of the player to check for whether player is grounded private _isGrounded(): boolean { if (this._floorRaycast(0, 0, .6).equals(Vector3.Zero())) { return false; } else { return true; } } //https://www.babylonjs-playground.com/#FUK3S#8 //https://www.html5gamedevs.com/topic/7709-scenepick-a-mesh-that-is-enabled-but-not-visible/ //check whether a mesh is sloping based on the normal private _checkSlope(): boolean { //only check meshes that are pickable and enabled (specific for collision meshes that are invisible) let predicate = function (mesh) { return mesh.isPickable && mesh.isEnabled(); } //4 raycasts outward from center let raycast = new Vector3(this.mesh.position.x, this.mesh.position.y + 0.5, this.mesh.position.z + .25); let ray = new Ray(raycast, Vector3.Up().scale(-1), 1.5); let pick = this.scene.pickWithRay(ray, predicate); let raycast2 = new Vector3(this.mesh.position.x, this.mesh.position.y + 0.5, this.mesh.position.z - .25); let ray2 = new Ray(raycast2, Vector3.Up().scale(-1), 1.5); let pick2 = this.scene.pickWithRay(ray2, predicate); let raycast3 = new Vector3(this.mesh.position.x + .25, this.mesh.position.y + 0.5, this.mesh.position.z); let ray3 = new Ray(raycast3, Vector3.Up().scale(-1), 1.5); let pick3 = this.scene.pickWithRay(ray3, predicate); let raycast4 = new Vector3(this.mesh.position.x - .25, this.mesh.position.y + 0.5, this.mesh.position.z); let ray4 = new Ray(raycast4, Vector3.Up().scale(-1), 1.5); let pick4 = this.scene.pickWithRay(ray4, predicate); if (pick.hit && !pick.getNormal().equals(Vector3.Up())) { if(pick.pickedMesh.name.includes("stair")) { return true; } } else if (pick2.hit && !pick2.getNormal().equals(Vector3.Up())) { if(pick2.pickedMesh.name.includes("stair")) { return true; } } else if (pick3.hit && !pick3.getNormal().equals(Vector3.Up())) { if(pick3.pickedMesh.name.includes("stair")) { return true; } } else if (pick4.hit && !pick4.getNormal().equals(Vector3.Up())) { if(pick4.pickedMesh.name.includes("stair")) { return true; } } return false; } private _updateGroundDetection(): void { this._deltaTime = this.scene.getEngine().getDeltaTime() / 1000.0; //if not grounded if (!this._isGrounded()) { //if the body isnt grounded, check if it's on a slope and was either falling or walking onto it if (this._checkSlope() && this._gravity.y <= 0) { console.log("slope") //if you are considered on a slope, you're able to jump and gravity wont affect you this._gravity.y = 0; this._jumpCount = 1; this._grounded = true; } else { //keep applying gravity this._gravity = this._gravity.addInPlace(Vector3.Up().scale(this._deltaTime * Player.GRAVITY)); this._grounded = false; } } //limit the speed of gravity to the negative of the jump power if (this._gravity.y < -Player.JUMP_FORCE) { this._gravity.y = -Player.JUMP_FORCE; } //cue falling animation once gravity starts pushing down if (this._gravity.y < 0 && this._jumped) { //todo: play a falling anim if not grounded BUT not on a slope this._isFalling = true; } //update our movement to account for jumping this.mesh.moveWithCollisions(this._moveDirection.addInPlace(this._gravity)); if (this._isGrounded()) { this._gravity.y = 0; this._grounded = true; //keep track of last known ground position this._lastGroundPos.copyFrom(this.mesh.position); this._jumpCount = 1; //dashing reset this._canDash = true; //reset sequence(needed if we collide with the ground BEFORE actually completing the dash duration) this.dashTime = 0; this._dashPressed = false; //jump & falling animation flags this._jumped = false; this._isFalling = false; } //Jump detection if (this._input.jumpKeyDown && this._jumpCount > 0) { this._gravity.y = Player.JUMP_FORCE; this._jumpCount--; //jumping and falling animation flags this._jumped = true; this._isFalling = false; this._jumpingSfx.play(); //tutorial, if the player jumps for the first time if(!this.tutorial_jump){ this.tutorial_jump = true; } } } //--GAME UPDATES-- private _beforeRenderUpdate(): void { this._updateFromControls(); this._updateGroundDetection(); this._animatePlayer(); } public activatePlayerCamera(): UniversalCamera { this.scene.registerBeforeRender(() => { this._beforeRenderUpdate(); this._updateCamera(); }) return this.camera; } //--CAMERA-- private _updateCamera(): void { //trigger areas for rotating camera view if (this.mesh.intersectsMesh(this.scene.getMeshByName("cornerTrigger"))) { if (this._input.horizontalAxis > 0) { //rotates to the right this._camRoot.rotation = Vector3.Lerp(this._camRoot.rotation, new Vector3(this._camRoot.rotation.x, Math.PI / 2, this._camRoot.rotation.z), 0.4); } else if (this._input.horizontalAxis < 0) { //rotates to the left this._camRoot.rotation = Vector3.Lerp(this._camRoot.rotation, new Vector3(this._camRoot.rotation.x, Math.PI, this._camRoot.rotation.z), 0.4); } } //rotates the camera to point down at the player when they enter the area, and returns it back to normal when they exit if (this.mesh.intersectsMesh(this.scene.getMeshByName("festivalTrigger"))) { if (this._input.verticalAxis > 0) { this._yTilt.rotation = Vector3.Lerp(this._yTilt.rotation, Player.DOWN_TILT, 0.4); } else if (this._input.verticalAxis < 0) { this._yTilt.rotation = Vector3.Lerp(this._yTilt.rotation, Player.ORIGINAL_TILT, 0.4); } } //once you've reached the destination area, return back to the original orientation, if they leave rotate it to the previous orientation if (this.mesh.intersectsMesh(this.scene.getMeshByName("destinationTrigger"))) { if (this._input.verticalAxis > 0) { this._yTilt.rotation = Vector3.Lerp(this._yTilt.rotation, Player.ORIGINAL_TILT, 0.4); } else if (this._input.verticalAxis < 0) { this._yTilt.rotation = Vector3.Lerp(this._yTilt.rotation, Player.DOWN_TILT, 0.4); } } //update camera postion up/down movement let centerPlayer = this.mesh.position.y + 2; this._camRoot.position = Vector3.Lerp(this._camRoot.position, new Vector3(this.mesh.position.x, centerPlayer, this.mesh.position.z), 0.4); } private _setupPlayerCamera(): UniversalCamera { //root camera parent that handles positioning of the camera to follow the player this._camRoot = new TransformNode("root"); this._camRoot.position = new Vector3(0, 0, 0); //initialized at (0,0,0) //to face the player from behind (180 degrees) this._camRoot.rotation = new Vector3(0, Math.PI, 0); //rotations along the x-axis (up/down tilting) let yTilt = new TransformNode("ytilt"); //adjustments to camera view to point down at our player yTilt.rotation = Player.ORIGINAL_TILT; this._yTilt = yTilt; yTilt.parent = this._camRoot; //our actual camera that's pointing at our root's position this.camera = new UniversalCamera("cam", new Vector3(0, 0, -30), this.scene); this.camera.lockedTarget = this._camRoot.position; this.camera.fov = 0.47350045992678597; this.camera.parent = yTilt; this.scene.activeCamera = this.camera; return this.camera; } private _createSparkles(): void { const sphere = Mesh.CreateSphere("sparkles", 4, 1, this.scene); sphere.position = new Vector3(0, 0, 0); sphere.parent = this.scene.getTransformNodeByName("Empty"); // place particle system at the tip of the sparkler on the player mesh sphere.isVisible = false; let particleSystem = new ParticleSystem("sparkles", 1000, this.scene); particleSystem.particleTexture = new Texture("textures/flwr.png", this.scene); particleSystem.emitter = sphere; particleSystem.particleEmitterType = new SphereParticleEmitter(0); particleSystem.updateSpeed = 0.014; particleSystem.minAngularSpeed = 0; particleSystem.maxAngularSpeed = 360; particleSystem.minEmitPower = 1; particleSystem.maxEmitPower = 3; particleSystem.minSize = 0.5; particleSystem.maxSize = 2; particleSystem.minScaleX = 0.5; particleSystem.minScaleY = 0.5; particleSystem.color1 = new Color4(0.8, 0.8549019607843137, 1, 1); particleSystem.color2 = new Color4(0.8509803921568627, 0.7647058823529411, 1, 1); particleSystem.addRampGradient(0, Color3.White()); particleSystem.addRampGradient(1, Color3.Black()); particleSystem.getRampGradients()[0].color = Color3.FromHexString("#BBC1FF"); particleSystem.getRampGradients()[1].color = Color3.FromHexString("#FFFFFF"); particleSystem.maxAngularSpeed = 0; particleSystem.maxInitialRotation = 360; particleSystem.minAngularSpeed = -10; particleSystem.maxAngularSpeed = 10; particleSystem.start(); this.sparkler = particleSystem; } private _loadSounds(scene: Scene): void { this.lightSfx = new Sound("light", "./sounds/Rise03.mp3", scene, function () { }); this.sparkResetSfx = new Sound("sparkReset", "./sounds/Rise04.mp3", scene, function () { }); this._jumpingSfx = new Sound("jumping", "./sounds/187024__lloydevans09__jump2.wav", scene, function () { }, { volume: 0.25 }); this._dashingSfx = new Sound("dashing", "./sounds/194081__potentjello__woosh-noise-1.wav", scene, function () { }); this._walkingSfx = new Sound("walking", "./sounds/Concrete 2.wav", scene, function () { }, { loop: true, volume: 0.20, playbackRate: 0.6 }); this._resetSfx = new Sound("reset", "./sounds/Retro Magic Protection 25.wav", scene, function () { }, { volume: 0.25 }); } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class IVS extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: IVS.Types.ClientConfiguration) config: Config & IVS.Types.ClientConfiguration; /** * Performs GetChannel on multiple ARNs simultaneously. */ batchGetChannel(params: IVS.Types.BatchGetChannelRequest, callback?: (err: AWSError, data: IVS.Types.BatchGetChannelResponse) => void): Request<IVS.Types.BatchGetChannelResponse, AWSError>; /** * Performs GetChannel on multiple ARNs simultaneously. */ batchGetChannel(callback?: (err: AWSError, data: IVS.Types.BatchGetChannelResponse) => void): Request<IVS.Types.BatchGetChannelResponse, AWSError>; /** * Performs GetStreamKey on multiple ARNs simultaneously. */ batchGetStreamKey(params: IVS.Types.BatchGetStreamKeyRequest, callback?: (err: AWSError, data: IVS.Types.BatchGetStreamKeyResponse) => void): Request<IVS.Types.BatchGetStreamKeyResponse, AWSError>; /** * Performs GetStreamKey on multiple ARNs simultaneously. */ batchGetStreamKey(callback?: (err: AWSError, data: IVS.Types.BatchGetStreamKeyResponse) => void): Request<IVS.Types.BatchGetStreamKeyResponse, AWSError>; /** * Creates a new channel and an associated stream key to start streaming. */ createChannel(params: IVS.Types.CreateChannelRequest, callback?: (err: AWSError, data: IVS.Types.CreateChannelResponse) => void): Request<IVS.Types.CreateChannelResponse, AWSError>; /** * Creates a new channel and an associated stream key to start streaming. */ createChannel(callback?: (err: AWSError, data: IVS.Types.CreateChannelResponse) => void): Request<IVS.Types.CreateChannelResponse, AWSError>; /** * Creates a new recording configuration, used to enable recording to Amazon S3. Known issue: In the us-east-1 region, if you use the AWS CLI to create a recording configuration, it returns success even if the S3 bucket is in a different region. In this case, the state of the recording configuration is CREATE_FAILED (instead of ACTIVE). (In other regions, the CLI correctly returns failure if the bucket is in a different region.) Workaround: Ensure that your S3 bucket is in the same region as the recording configuration. If you create a recording configuration in a different region as your S3 bucket, delete that recording configuration and create a new one with an S3 bucket from the correct region. */ createRecordingConfiguration(params: IVS.Types.CreateRecordingConfigurationRequest, callback?: (err: AWSError, data: IVS.Types.CreateRecordingConfigurationResponse) => void): Request<IVS.Types.CreateRecordingConfigurationResponse, AWSError>; /** * Creates a new recording configuration, used to enable recording to Amazon S3. Known issue: In the us-east-1 region, if you use the AWS CLI to create a recording configuration, it returns success even if the S3 bucket is in a different region. In this case, the state of the recording configuration is CREATE_FAILED (instead of ACTIVE). (In other regions, the CLI correctly returns failure if the bucket is in a different region.) Workaround: Ensure that your S3 bucket is in the same region as the recording configuration. If you create a recording configuration in a different region as your S3 bucket, delete that recording configuration and create a new one with an S3 bucket from the correct region. */ createRecordingConfiguration(callback?: (err: AWSError, data: IVS.Types.CreateRecordingConfigurationResponse) => void): Request<IVS.Types.CreateRecordingConfigurationResponse, AWSError>; /** * Creates a stream key, used to initiate a stream, for the specified channel ARN. Note that CreateChannel creates a stream key. If you subsequently use CreateStreamKey on the same channel, it will fail because a stream key already exists and there is a limit of 1 stream key per channel. To reset the stream key on a channel, use DeleteStreamKey and then CreateStreamKey. */ createStreamKey(params: IVS.Types.CreateStreamKeyRequest, callback?: (err: AWSError, data: IVS.Types.CreateStreamKeyResponse) => void): Request<IVS.Types.CreateStreamKeyResponse, AWSError>; /** * Creates a stream key, used to initiate a stream, for the specified channel ARN. Note that CreateChannel creates a stream key. If you subsequently use CreateStreamKey on the same channel, it will fail because a stream key already exists and there is a limit of 1 stream key per channel. To reset the stream key on a channel, use DeleteStreamKey and then CreateStreamKey. */ createStreamKey(callback?: (err: AWSError, data: IVS.Types.CreateStreamKeyResponse) => void): Request<IVS.Types.CreateStreamKeyResponse, AWSError>; /** * Deletes the specified channel and its associated stream keys. If you try to delete a live channel, you will get an error (409 ConflictException). To delete a channel that is live, call StopStream, wait for the Amazon EventBridge "Stream End" event (to verify that the stream's state was changed from Live to Offline), then call DeleteChannel. (See Using EventBridge with Amazon IVS.) */ deleteChannel(params: IVS.Types.DeleteChannelRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified channel and its associated stream keys. If you try to delete a live channel, you will get an error (409 ConflictException). To delete a channel that is live, call StopStream, wait for the Amazon EventBridge "Stream End" event (to verify that the stream's state was changed from Live to Offline), then call DeleteChannel. (See Using EventBridge with Amazon IVS.) */ deleteChannel(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a specified authorization key pair. This invalidates future viewer tokens generated using the key pair’s privateKey. For more information, see Setting Up Private Channels in the Amazon IVS User Guide. */ deletePlaybackKeyPair(params: IVS.Types.DeletePlaybackKeyPairRequest, callback?: (err: AWSError, data: IVS.Types.DeletePlaybackKeyPairResponse) => void): Request<IVS.Types.DeletePlaybackKeyPairResponse, AWSError>; /** * Deletes a specified authorization key pair. This invalidates future viewer tokens generated using the key pair’s privateKey. For more information, see Setting Up Private Channels in the Amazon IVS User Guide. */ deletePlaybackKeyPair(callback?: (err: AWSError, data: IVS.Types.DeletePlaybackKeyPairResponse) => void): Request<IVS.Types.DeletePlaybackKeyPairResponse, AWSError>; /** * Deletes the recording configuration for the specified ARN. If you try to delete a recording configuration that is associated with a channel, you will get an error (409 ConflictException). To avoid this, for all channels that reference the recording configuration, first use UpdateChannel to set the recordingConfigurationArn field to an empty string, then use DeleteRecordingConfiguration. */ deleteRecordingConfiguration(params: IVS.Types.DeleteRecordingConfigurationRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the recording configuration for the specified ARN. If you try to delete a recording configuration that is associated with a channel, you will get an error (409 ConflictException). To avoid this, for all channels that reference the recording configuration, first use UpdateChannel to set the recordingConfigurationArn field to an empty string, then use DeleteRecordingConfiguration. */ deleteRecordingConfiguration(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the stream key for the specified ARN, so it can no longer be used to stream. */ deleteStreamKey(params: IVS.Types.DeleteStreamKeyRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the stream key for the specified ARN, so it can no longer be used to stream. */ deleteStreamKey(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Gets the channel configuration for the specified channel ARN. See also BatchGetChannel. */ getChannel(params: IVS.Types.GetChannelRequest, callback?: (err: AWSError, data: IVS.Types.GetChannelResponse) => void): Request<IVS.Types.GetChannelResponse, AWSError>; /** * Gets the channel configuration for the specified channel ARN. See also BatchGetChannel. */ getChannel(callback?: (err: AWSError, data: IVS.Types.GetChannelResponse) => void): Request<IVS.Types.GetChannelResponse, AWSError>; /** * Gets a specified playback authorization key pair and returns the arn and fingerprint. The privateKey held by the caller can be used to generate viewer authorization tokens, to grant viewers access to private channels. For more information, see Setting Up Private Channels in the Amazon IVS User Guide. */ getPlaybackKeyPair(params: IVS.Types.GetPlaybackKeyPairRequest, callback?: (err: AWSError, data: IVS.Types.GetPlaybackKeyPairResponse) => void): Request<IVS.Types.GetPlaybackKeyPairResponse, AWSError>; /** * Gets a specified playback authorization key pair and returns the arn and fingerprint. The privateKey held by the caller can be used to generate viewer authorization tokens, to grant viewers access to private channels. For more information, see Setting Up Private Channels in the Amazon IVS User Guide. */ getPlaybackKeyPair(callback?: (err: AWSError, data: IVS.Types.GetPlaybackKeyPairResponse) => void): Request<IVS.Types.GetPlaybackKeyPairResponse, AWSError>; /** * Gets the recording configuration for the specified ARN. */ getRecordingConfiguration(params: IVS.Types.GetRecordingConfigurationRequest, callback?: (err: AWSError, data: IVS.Types.GetRecordingConfigurationResponse) => void): Request<IVS.Types.GetRecordingConfigurationResponse, AWSError>; /** * Gets the recording configuration for the specified ARN. */ getRecordingConfiguration(callback?: (err: AWSError, data: IVS.Types.GetRecordingConfigurationResponse) => void): Request<IVS.Types.GetRecordingConfigurationResponse, AWSError>; /** * Gets information about the active (live) stream on a specified channel. */ getStream(params: IVS.Types.GetStreamRequest, callback?: (err: AWSError, data: IVS.Types.GetStreamResponse) => void): Request<IVS.Types.GetStreamResponse, AWSError>; /** * Gets information about the active (live) stream on a specified channel. */ getStream(callback?: (err: AWSError, data: IVS.Types.GetStreamResponse) => void): Request<IVS.Types.GetStreamResponse, AWSError>; /** * Gets stream-key information for a specified ARN. */ getStreamKey(params: IVS.Types.GetStreamKeyRequest, callback?: (err: AWSError, data: IVS.Types.GetStreamKeyResponse) => void): Request<IVS.Types.GetStreamKeyResponse, AWSError>; /** * Gets stream-key information for a specified ARN. */ getStreamKey(callback?: (err: AWSError, data: IVS.Types.GetStreamKeyResponse) => void): Request<IVS.Types.GetStreamKeyResponse, AWSError>; /** * Imports the public portion of a new key pair and returns its arn and fingerprint. The privateKey can then be used to generate viewer authorization tokens, to grant viewers access to private channels. For more information, see Setting Up Private Channels in the Amazon IVS User Guide. */ importPlaybackKeyPair(params: IVS.Types.ImportPlaybackKeyPairRequest, callback?: (err: AWSError, data: IVS.Types.ImportPlaybackKeyPairResponse) => void): Request<IVS.Types.ImportPlaybackKeyPairResponse, AWSError>; /** * Imports the public portion of a new key pair and returns its arn and fingerprint. The privateKey can then be used to generate viewer authorization tokens, to grant viewers access to private channels. For more information, see Setting Up Private Channels in the Amazon IVS User Guide. */ importPlaybackKeyPair(callback?: (err: AWSError, data: IVS.Types.ImportPlaybackKeyPairResponse) => void): Request<IVS.Types.ImportPlaybackKeyPairResponse, AWSError>; /** * Gets summary information about all channels in your account, in the AWS region where the API request is processed. This list can be filtered to match a specified name or recording-configuration ARN. Filters are mutually exclusive and cannot be used together. If you try to use both filters, you will get an error (409 ConflictException). */ listChannels(params: IVS.Types.ListChannelsRequest, callback?: (err: AWSError, data: IVS.Types.ListChannelsResponse) => void): Request<IVS.Types.ListChannelsResponse, AWSError>; /** * Gets summary information about all channels in your account, in the AWS region where the API request is processed. This list can be filtered to match a specified name or recording-configuration ARN. Filters are mutually exclusive and cannot be used together. If you try to use both filters, you will get an error (409 ConflictException). */ listChannels(callback?: (err: AWSError, data: IVS.Types.ListChannelsResponse) => void): Request<IVS.Types.ListChannelsResponse, AWSError>; /** * Gets summary information about playback key pairs. For more information, see Setting Up Private Channels in the Amazon IVS User Guide. */ listPlaybackKeyPairs(params: IVS.Types.ListPlaybackKeyPairsRequest, callback?: (err: AWSError, data: IVS.Types.ListPlaybackKeyPairsResponse) => void): Request<IVS.Types.ListPlaybackKeyPairsResponse, AWSError>; /** * Gets summary information about playback key pairs. For more information, see Setting Up Private Channels in the Amazon IVS User Guide. */ listPlaybackKeyPairs(callback?: (err: AWSError, data: IVS.Types.ListPlaybackKeyPairsResponse) => void): Request<IVS.Types.ListPlaybackKeyPairsResponse, AWSError>; /** * Gets summary information about all recording configurations in your account, in the AWS region where the API request is processed. */ listRecordingConfigurations(params: IVS.Types.ListRecordingConfigurationsRequest, callback?: (err: AWSError, data: IVS.Types.ListRecordingConfigurationsResponse) => void): Request<IVS.Types.ListRecordingConfigurationsResponse, AWSError>; /** * Gets summary information about all recording configurations in your account, in the AWS region where the API request is processed. */ listRecordingConfigurations(callback?: (err: AWSError, data: IVS.Types.ListRecordingConfigurationsResponse) => void): Request<IVS.Types.ListRecordingConfigurationsResponse, AWSError>; /** * Gets summary information about stream keys for the specified channel. */ listStreamKeys(params: IVS.Types.ListStreamKeysRequest, callback?: (err: AWSError, data: IVS.Types.ListStreamKeysResponse) => void): Request<IVS.Types.ListStreamKeysResponse, AWSError>; /** * Gets summary information about stream keys for the specified channel. */ listStreamKeys(callback?: (err: AWSError, data: IVS.Types.ListStreamKeysResponse) => void): Request<IVS.Types.ListStreamKeysResponse, AWSError>; /** * Gets summary information about live streams in your account, in the AWS region where the API request is processed. */ listStreams(params: IVS.Types.ListStreamsRequest, callback?: (err: AWSError, data: IVS.Types.ListStreamsResponse) => void): Request<IVS.Types.ListStreamsResponse, AWSError>; /** * Gets summary information about live streams in your account, in the AWS region where the API request is processed. */ listStreams(callback?: (err: AWSError, data: IVS.Types.ListStreamsResponse) => void): Request<IVS.Types.ListStreamsResponse, AWSError>; /** * Gets information about AWS tags for the specified ARN. */ listTagsForResource(params: IVS.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: IVS.Types.ListTagsForResourceResponse) => void): Request<IVS.Types.ListTagsForResourceResponse, AWSError>; /** * Gets information about AWS tags for the specified ARN. */ listTagsForResource(callback?: (err: AWSError, data: IVS.Types.ListTagsForResourceResponse) => void): Request<IVS.Types.ListTagsForResourceResponse, AWSError>; /** * Inserts metadata into the active stream of the specified channel. A maximum of 5 requests per second per channel is allowed, each with a maximum 1 KB payload. (If 5 TPS is not sufficient for your needs, we recommend batching your data into a single PutMetadata call.) Also see Embedding Metadata within a Video Stream in the Amazon IVS User Guide. */ putMetadata(params: IVS.Types.PutMetadataRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Inserts metadata into the active stream of the specified channel. A maximum of 5 requests per second per channel is allowed, each with a maximum 1 KB payload. (If 5 TPS is not sufficient for your needs, we recommend batching your data into a single PutMetadata call.) Also see Embedding Metadata within a Video Stream in the Amazon IVS User Guide. */ putMetadata(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Disconnects the incoming RTMPS stream for the specified channel. Can be used in conjunction with DeleteStreamKey to prevent further streaming to a channel. Many streaming client-software libraries automatically reconnect a dropped RTMPS session, so to stop the stream permanently, you may want to first revoke the streamKey attached to the channel. */ stopStream(params: IVS.Types.StopStreamRequest, callback?: (err: AWSError, data: IVS.Types.StopStreamResponse) => void): Request<IVS.Types.StopStreamResponse, AWSError>; /** * Disconnects the incoming RTMPS stream for the specified channel. Can be used in conjunction with DeleteStreamKey to prevent further streaming to a channel. Many streaming client-software libraries automatically reconnect a dropped RTMPS session, so to stop the stream permanently, you may want to first revoke the streamKey attached to the channel. */ stopStream(callback?: (err: AWSError, data: IVS.Types.StopStreamResponse) => void): Request<IVS.Types.StopStreamResponse, AWSError>; /** * Adds or updates tags for the AWS resource with the specified ARN. */ tagResource(params: IVS.Types.TagResourceRequest, callback?: (err: AWSError, data: IVS.Types.TagResourceResponse) => void): Request<IVS.Types.TagResourceResponse, AWSError>; /** * Adds or updates tags for the AWS resource with the specified ARN. */ tagResource(callback?: (err: AWSError, data: IVS.Types.TagResourceResponse) => void): Request<IVS.Types.TagResourceResponse, AWSError>; /** * Removes tags from the resource with the specified ARN. */ untagResource(params: IVS.Types.UntagResourceRequest, callback?: (err: AWSError, data: IVS.Types.UntagResourceResponse) => void): Request<IVS.Types.UntagResourceResponse, AWSError>; /** * Removes tags from the resource with the specified ARN. */ untagResource(callback?: (err: AWSError, data: IVS.Types.UntagResourceResponse) => void): Request<IVS.Types.UntagResourceResponse, AWSError>; /** * Updates a channel's configuration. This does not affect an ongoing stream of this channel. You must stop and restart the stream for the changes to take effect. */ updateChannel(params: IVS.Types.UpdateChannelRequest, callback?: (err: AWSError, data: IVS.Types.UpdateChannelResponse) => void): Request<IVS.Types.UpdateChannelResponse, AWSError>; /** * Updates a channel's configuration. This does not affect an ongoing stream of this channel. You must stop and restart the stream for the changes to take effect. */ updateChannel(callback?: (err: AWSError, data: IVS.Types.UpdateChannelResponse) => void): Request<IVS.Types.UpdateChannelResponse, AWSError>; } declare namespace IVS { export interface BatchError { /** * Channel ARN. */ arn?: ResourceArn; /** * Error code. */ code?: errorCode; /** * Error message, determined by the application. */ message?: errorMessage; } export type BatchErrors = BatchError[]; export interface BatchGetChannelRequest { /** * Array of ARNs, one per channel. */ arns: ChannelArnList; } export interface BatchGetChannelResponse { channels?: Channels; /** * Each error object is related to a specific ARN in the request. */ errors?: BatchErrors; } export interface BatchGetStreamKeyRequest { /** * Array of ARNs, one per channel. */ arns: StreamKeyArnList; } export interface BatchGetStreamKeyResponse { streamKeys?: StreamKeys; errors?: BatchErrors; } export type Boolean = boolean; export interface Channel { /** * Channel ARN. */ arn?: ChannelArn; /** * Channel name. */ name?: ChannelName; /** * Channel latency mode. Use NORMAL to broadcast and deliver live video up to Full HD. Use LOW for near-real-time interaction with viewers. Default: LOW. (Note: In the Amazon IVS console, LOW and NORMAL correspond to Ultra-low and Standard, respectively.) */ latencyMode?: ChannelLatencyMode; /** * Channel type, which determines the allowable resolution and bitrate. If you exceed the allowable resolution or bitrate, the stream probably will disconnect immediately. Default: STANDARD. Valid values: STANDARD: Multiple qualities are generated from the original input, to automatically give viewers the best experience for their devices and network conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5 Mbps. BASIC: Amazon IVS delivers the original input to viewers. The viewer’s video-quality choice is limited to the original input. Vertical resolution can be up to 480 and bitrate can be up to 1.5 Mbps. */ type?: ChannelType; /** * Recording-configuration ARN. A value other than an empty string indicates that recording is enabled. Default: "" (empty string, recording is disabled). */ recordingConfigurationArn?: ChannelRecordingConfigurationArn; /** * Channel ingest endpoint, part of the definition of an ingest server, used when you set up streaming software. */ ingestEndpoint?: IngestEndpoint; /** * Channel playback URL. */ playbackUrl?: PlaybackURL; /** * Whether the channel is private (enabled for playback authorization). Default: false. */ authorized?: IsAuthorized; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type ChannelArn = string; export type ChannelArnList = ChannelArn[]; export type ChannelLatencyMode = "NORMAL"|"LOW"|string; export type ChannelList = ChannelSummary[]; export type ChannelName = string; export type ChannelRecordingConfigurationArn = string; export interface ChannelSummary { /** * Channel ARN. */ arn?: ChannelArn; /** * Channel name. */ name?: ChannelName; /** * Channel latency mode. Use NORMAL to broadcast and deliver live video up to Full HD. Use LOW for near-real-time interaction with viewers. Default: LOW. (Note: In the Amazon IVS console, LOW and NORMAL correspond to Ultra-low and Standard, respectively.) */ latencyMode?: ChannelLatencyMode; /** * Whether the channel is private (enabled for playback authorization). Default: false. */ authorized?: IsAuthorized; /** * Recording-configuration ARN. A value other than an empty string indicates that recording is enabled. Default: "" (empty string, recording is disabled). */ recordingConfigurationArn?: ChannelRecordingConfigurationArn; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type ChannelType = "BASIC"|"STANDARD"|string; export type Channels = Channel[]; export interface CreateChannelRequest { /** * Channel name. */ name?: ChannelName; /** * Channel latency mode. Use NORMAL to broadcast and deliver live video up to Full HD. Use LOW for near-real-time interaction with viewers. (Note: In the Amazon IVS console, LOW and NORMAL correspond to Ultra-low and Standard, respectively.) Default: LOW. */ latencyMode?: ChannelLatencyMode; /** * Channel type, which determines the allowable resolution and bitrate. If you exceed the allowable resolution or bitrate, the stream probably will disconnect immediately. Default: STANDARD. Valid values: STANDARD: Multiple qualities are generated from the original input, to automatically give viewers the best experience for their devices and network conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5 Mbps. BASIC: Amazon IVS delivers the original input to viewers. The viewer’s video-quality choice is limited to the original input. Vertical resolution can be up to 480 and bitrate can be up to 1.5 Mbps. */ type?: ChannelType; /** * Whether the channel is private (enabled for playback authorization). Default: false. */ authorized?: Boolean; /** * Recording-configuration ARN. Default: "" (empty string, recording is disabled). */ recordingConfigurationArn?: ChannelRecordingConfigurationArn; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export interface CreateChannelResponse { channel?: Channel; streamKey?: StreamKey; } export interface CreateRecordingConfigurationRequest { /** * An arbitrary string (a nickname) that helps the customer identify that resource. The value does not need to be unique. */ name?: RecordingConfigurationName; /** * A complex type that contains a destination configuration for where recorded video will be stored. */ destinationConfiguration: DestinationConfiguration; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export interface CreateRecordingConfigurationResponse { recordingConfiguration?: RecordingConfiguration; } export interface CreateStreamKeyRequest { /** * ARN of the channel for which to create the stream key. */ channelArn: ChannelArn; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export interface CreateStreamKeyResponse { /** * Stream key used to authenticate an RTMPS stream for ingestion. */ streamKey?: StreamKey; } export interface DeleteChannelRequest { /** * ARN of the channel to be deleted. */ arn: ChannelArn; } export interface DeletePlaybackKeyPairRequest { /** * ARN of the key pair to be deleted. */ arn: PlaybackKeyPairArn; } export interface DeletePlaybackKeyPairResponse { } export interface DeleteRecordingConfigurationRequest { /** * ARN of the recording configuration to be deleted. */ arn: RecordingConfigurationArn; } export interface DeleteStreamKeyRequest { /** * ARN of the stream key to be deleted. */ arn: StreamKeyArn; } export interface DestinationConfiguration { /** * An S3 destination configuration where recorded videos will be stored. */ s3?: S3DestinationConfiguration; } export interface GetChannelRequest { /** * ARN of the channel for which the configuration is to be retrieved. */ arn: ChannelArn; } export interface GetChannelResponse { channel?: Channel; } export interface GetPlaybackKeyPairRequest { /** * ARN of the key pair to be returned. */ arn: PlaybackKeyPairArn; } export interface GetPlaybackKeyPairResponse { keyPair?: PlaybackKeyPair; } export interface GetRecordingConfigurationRequest { /** * ARN of the recording configuration to be retrieved. */ arn: RecordingConfigurationArn; } export interface GetRecordingConfigurationResponse { recordingConfiguration?: RecordingConfiguration; } export interface GetStreamKeyRequest { /** * ARN for the stream key to be retrieved. */ arn: StreamKeyArn; } export interface GetStreamKeyResponse { streamKey?: StreamKey; } export interface GetStreamRequest { /** * Channel ARN for stream to be accessed. */ channelArn: ChannelArn; } export interface GetStreamResponse { stream?: Stream; } export interface ImportPlaybackKeyPairRequest { /** * The public portion of a customer-generated key pair. */ publicKeyMaterial: PlaybackPublicKeyMaterial; /** * An arbitrary string (a nickname) assigned to a playback key pair that helps the customer identify that resource. The value does not need to be unique. */ name?: PlaybackKeyPairName; /** * Any tags provided with the request are added to the playback key pair tags. */ tags?: Tags; } export interface ImportPlaybackKeyPairResponse { keyPair?: PlaybackKeyPair; } export type IngestEndpoint = string; export type IsAuthorized = boolean; export interface ListChannelsRequest { /** * Filters the channel list to match the specified name. */ filterByName?: ChannelName; /** * Filters the channel list to match the specified recording-configuration ARN. */ filterByRecordingConfigurationArn?: ChannelRecordingConfigurationArn; /** * The first channel to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: PaginationToken; /** * Maximum number of channels to return. Default: 50. */ maxResults?: MaxChannelResults; } export interface ListChannelsResponse { /** * List of the matching channels. */ channels: ChannelList; /** * If there are more channels than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListPlaybackKeyPairsRequest { /** * Maximum number of key pairs to return. */ nextToken?: PaginationToken; /** * The first key pair to retrieve. This is used for pagination; see the nextToken response field. Default: 50. */ maxResults?: MaxPlaybackKeyPairResults; } export interface ListPlaybackKeyPairsResponse { /** * List of key pairs. */ keyPairs: PlaybackKeyPairList; /** * If there are more key pairs than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListRecordingConfigurationsRequest { /** * The first recording configuration to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: PaginationToken; /** * Maximum number of recording configurations to return. Default: 50. */ maxResults?: MaxRecordingConfigurationResults; } export interface ListRecordingConfigurationsResponse { /** * List of the matching recording configurations. */ recordingConfigurations: RecordingConfigurationList; /** * If there are more recording configurations than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListStreamKeysRequest { /** * Channel ARN used to filter the list. */ channelArn: ChannelArn; /** * The first stream key to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: PaginationToken; /** * Maximum number of streamKeys to return. Default: 50. */ maxResults?: MaxStreamKeyResults; } export interface ListStreamKeysResponse { /** * List of stream keys. */ streamKeys: StreamKeyList; /** * If there are more stream keys than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListStreamsRequest { /** * The first stream to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: PaginationToken; /** * Maximum number of streams to return. Default: 50. */ maxResults?: MaxStreamResults; } export interface ListStreamsResponse { /** * List of streams. */ streams: StreamList; /** * If there are more streams than maxResults, use nextToken in the request to get the next set. */ nextToken?: PaginationToken; } export interface ListTagsForResourceRequest { /** * The ARN of the resource to be retrieved. */ resourceArn: ResourceArn; /** * The first tag to retrieve. This is used for pagination; see the nextToken response field. */ nextToken?: String; /** * Maximum number of tags to return. Default: 50. */ maxResults?: MaxTagResults; } export interface ListTagsForResourceResponse { tags: Tags; /** * If there are more tags than maxResults, use nextToken in the request to get the next set. */ nextToken?: String; } export type MaxChannelResults = number; export type MaxPlaybackKeyPairResults = number; export type MaxRecordingConfigurationResults = number; export type MaxStreamKeyResults = number; export type MaxStreamResults = number; export type MaxTagResults = number; export type PaginationToken = string; export interface PlaybackKeyPair { /** * Key-pair ARN. */ arn?: PlaybackKeyPairArn; /** * An arbitrary string (a nickname) assigned to a playback key pair that helps the customer identify that resource. The value does not need to be unique. */ name?: PlaybackKeyPairName; /** * Key-pair identifier. */ fingerprint?: PlaybackKeyPairFingerprint; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type PlaybackKeyPairArn = string; export type PlaybackKeyPairFingerprint = string; export type PlaybackKeyPairList = PlaybackKeyPairSummary[]; export type PlaybackKeyPairName = string; export interface PlaybackKeyPairSummary { /** * Key-pair ARN. */ arn?: PlaybackKeyPairArn; /** * An arbitrary string (a nickname) assigned to a playback key pair that helps the customer identify that resource. The value does not need to be unique. */ name?: PlaybackKeyPairName; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type PlaybackPublicKeyMaterial = string; export type PlaybackURL = string; export interface PutMetadataRequest { /** * ARN of the channel into which metadata is inserted. This channel must have an active stream. */ channelArn: ChannelArn; /** * Metadata to insert into the stream. Maximum: 1 KB per request. */ metadata: StreamMetadata; } export interface RecordingConfiguration { /** * Recording-configuration ARN. */ arn: RecordingConfigurationArn; /** * An arbitrary string (a nickname) assigned to a recording configuration that helps the customer identify that resource. The value does not need to be unique. */ name?: RecordingConfigurationName; /** * A complex type that contains information about where recorded video will be stored. */ destinationConfiguration: DestinationConfiguration; /** * Indicates the current state of the recording configuration. When the state is ACTIVE, the configuration is ready for recording a channel stream. */ state: RecordingConfigurationState; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type RecordingConfigurationArn = string; export type RecordingConfigurationList = RecordingConfigurationSummary[]; export type RecordingConfigurationName = string; export type RecordingConfigurationState = "CREATING"|"CREATE_FAILED"|"ACTIVE"|string; export interface RecordingConfigurationSummary { /** * Recording-configuration ARN. */ arn: RecordingConfigurationArn; /** * An arbitrary string (a nickname) assigned to a recording configuration that helps the customer identify that resource. The value does not need to be unique. */ name?: RecordingConfigurationName; /** * A complex type that contains information about where recorded video will be stored. */ destinationConfiguration: DestinationConfiguration; /** * Indicates the current state of the recording configuration. When the state is ACTIVE, the configuration is ready for recording a channel stream. */ state: RecordingConfigurationState; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type ResourceArn = string; export type S3DestinationBucketName = string; export interface S3DestinationConfiguration { /** * Location (S3 bucket name) where recorded videos will be stored. */ bucketName: S3DestinationBucketName; } export interface StopStreamRequest { /** * ARN of the channel for which the stream is to be stopped. */ channelArn: ChannelArn; } export interface StopStreamResponse { } export interface Stream { /** * Channel ARN for the stream. */ channelArn?: ChannelArn; /** * URL of the master playlist, required by the video player to play the HLS stream. */ playbackUrl?: PlaybackURL; /** * ISO-8601 formatted timestamp of the stream’s start. */ startTime?: StreamStartTime; /** * The stream’s state. */ state?: StreamState; /** * The stream’s health. */ health?: StreamHealth; /** * Number of current viewers of the stream. A value of -1 indicates that the request timed out; in this case, retry. */ viewerCount?: StreamViewerCount; } export type StreamHealth = "HEALTHY"|"STARVING"|"UNKNOWN"|string; export interface StreamKey { /** * Stream-key ARN. */ arn?: StreamKeyArn; /** * Stream-key value. */ value?: StreamKeyValue; /** * Channel ARN for the stream. */ channelArn?: ChannelArn; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type StreamKeyArn = string; export type StreamKeyArnList = StreamKeyArn[]; export type StreamKeyList = StreamKeySummary[]; export interface StreamKeySummary { /** * Stream-key ARN. */ arn?: StreamKeyArn; /** * Channel ARN for the stream. */ channelArn?: ChannelArn; /** * Array of 1-50 maps, each of the form string:string (key:value). */ tags?: Tags; } export type StreamKeyValue = string; export type StreamKeys = StreamKey[]; export type StreamList = StreamSummary[]; export type StreamMetadata = string; export type StreamStartTime = Date; export type StreamState = "LIVE"|"OFFLINE"|string; export interface StreamSummary { /** * Channel ARN for the stream. */ channelArn?: ChannelArn; /** * The stream’s state. */ state?: StreamState; /** * The stream’s health. */ health?: StreamHealth; /** * Number of current viewers of the stream. A value of -1 indicates that the request timed out; in this case, retry. */ viewerCount?: StreamViewerCount; /** * ISO-8601 formatted timestamp of the stream’s start. */ startTime?: StreamStartTime; } export type StreamViewerCount = number; export type String = string; export type TagKey = string; export type TagKeyList = TagKey[]; export interface TagResourceRequest { /** * ARN of the resource for which tags are to be added or updated. */ resourceArn: ResourceArn; /** * Array of tags to be added or updated. */ tags: Tags; } export interface TagResourceResponse { } export type TagValue = string; export type Tags = {[key: string]: TagValue}; export interface UntagResourceRequest { /** * ARN of the resource for which tags are to be removed. */ resourceArn: ResourceArn; /** * Array of tags to be removed. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateChannelRequest { /** * ARN of the channel to be updated. */ arn: ChannelArn; /** * Channel name. */ name?: ChannelName; /** * Channel latency mode. Use NORMAL to broadcast and deliver live video up to Full HD. Use LOW for near-real-time interaction with viewers. (Note: In the Amazon IVS console, LOW and NORMAL correspond to Ultra-low and Standard, respectively.) */ latencyMode?: ChannelLatencyMode; /** * Channel type, which determines the allowable resolution and bitrate. If you exceed the allowable resolution or bitrate, the stream probably will disconnect immediately. Valid values: STANDARD: Multiple qualities are generated from the original input, to automatically give viewers the best experience for their devices and network conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5 Mbps. BASIC: Amazon IVS delivers the original input to viewers. The viewer’s video-quality choice is limited to the original input. Vertical resolution can be up to 480 and bitrate can be up to 1.5 Mbps. */ type?: ChannelType; /** * Whether the channel is private (enabled for playback authorization). */ authorized?: Boolean; /** * Recording-configuration ARN. If this is set to an empty string, recording is disabled. A value other than an empty string indicates that recording is enabled */ recordingConfigurationArn?: ChannelRecordingConfigurationArn; } export interface UpdateChannelResponse { channel?: Channel; } export type errorCode = string; export type errorMessage = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-07-14"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the IVS client. */ export import Types = IVS; } export = IVS;
the_stack
import { NotFound } from '@curveball/http-errors'; import * as crypto from 'crypto'; import db from '../database'; import { getSetting } from '../server-settings'; import * as principalService from '../principal/service'; import { User, App } from '../principal/types'; import { InvalidGrant, InvalidRequest, UnauthorizedClient } from './errors'; import { CodeChallengeMethod, OAuth2Code, OAuth2Token } from './types'; import { OAuth2Client } from '../oauth2-client/types'; import { generateSecretToken } from '../crypto'; import { generateJWTAccessToken } from './jwt'; export async function getRedirectUris(client: OAuth2Client): Promise<string[]> { const query = 'SELECT uri FROM oauth2_redirect_uris WHERE oauth2_client_id = ?'; const result = await db.query(query, [client.id]); return result[0].map((record: {uri:string}) => record.uri); } export async function validateRedirectUri(client: OAuth2Client, redirectUri: string): Promise<boolean> { const uris = await getRedirectUris(client); return uris.includes(redirectUri); } /** * Checks if a redirect_uri is permitted for the client. * * If not, it will emit an InvalidGrant error */ export async function requireRedirectUri(client: OAuth2Client, redirectUrl: string): Promise<void> { const uris = await getRedirectUris(client); if (uris.length===0) { throw new InvalidGrant('No valid redirect_uri was setup for this OAuth2 client_id'); } if (!uris.includes(redirectUrl)) { throw new InvalidGrant(`Invalid value for redirect_uri. The redirect_uri you passed (${redirectUrl}) was not in the allowed list of redirect_uris`); } } export async function addRedirectUris(client: OAuth2Client, redirectUris: string[]): Promise<void> { const query = 'INSERT INTO oauth2_redirect_uris SET oauth2_client_id = ?, uri = ?'; for(const uri of redirectUris) { await db.query(query, [client.id, uri]); } } export async function getActiveTokens(user: App | User): Promise<OAuth2Token[]> { const query = ` SELECT oauth2_client_id, access_token, refresh_token, user_id, access_token_expires, refresh_token_expires, browser_session_id FROM oauth2_tokens WHERE user_id = ? AND refresh_token_expires > UNIX_TIMESTAMP() `; const result = await db.query(query, [user.id]); return result[0].map((row: OAuth2TokenRecord):OAuth2Token => { return { accessToken: row.access_token, refreshToken: row.refresh_token, accessTokenExpires: row.access_token_expires, refreshTokenExpires: row.refresh_token_expires, tokenType: 'bearer', user, clientId: row.oauth2_client_id, }; }); } /** * This function is used for the implicit grant oauth2 flow. * * This function creates an access token for a specific user. */ export async function generateTokenForUser(client: OAuth2Client, user: App | User, browserSessionId?: string): Promise<OAuth2Token> { if (!user.active) { throw new Error ('Cannot generate token for inactive user'); } const expirySettings = getTokenExpiry(); const accessTokenExpires = Math.floor(Date.now() / 1000) + expirySettings.accessToken; const refreshTokenExpires = Math.floor(Date.now() / 1000) + expirySettings.refreshToken; let accessToken: string; if (getSetting('jwt.privateKey')!==null) { accessToken = await generateJWTAccessToken( user, client, expirySettings.accessToken, [] ); } else { accessToken = await generateSecretToken(); } const refreshToken = await generateSecretToken(); const query = 'INSERT INTO oauth2_tokens SET created = UNIX_TIMESTAMP(), ?'; await db.query(query, { oauth2_client_id: client.id, access_token: accessToken, refresh_token: refreshToken, user_id: user.id, access_token_expires: accessTokenExpires, refresh_token_expires: refreshTokenExpires, browser_session_id: browserSessionId, }); return { accessToken, refreshToken, accessTokenExpires, refreshTokenExpires, tokenType: 'bearer', user, clientId: client.id, }; } /** * This function is used to create arbitrary access tokens, by the currently logged in user. * * There is no specific OAuth2 flow for this. */ export async function generateTokenForUserNoClient(user: User): Promise<Omit<OAuth2Token, 'clientId'>> { if (!user.active) { throw new Error ('Cannot generate token for inactive user'); } const accessToken = await generateSecretToken(); const refreshToken = await generateSecretToken(); const query = 'INSERT INTO oauth2_tokens SET created = UNIX_TIMESTAMP(), ?'; const expirySettings = getTokenExpiry(); const accessTokenExpires = Math.floor(Date.now() / 1000) + expirySettings.accessToken; const refreshTokenExpires = Math.floor(Date.now() / 1000) + expirySettings.refreshToken; await db.query(query, { oauth2_client_id: 0, access_token: accessToken, refresh_token: refreshToken, user_id: user.id, access_token_expires: accessTokenExpires, refresh_token_expires: refreshTokenExpires, browser_session_id: null, }); return { accessToken, refreshToken, accessTokenExpires, refreshTokenExpires, tokenType: 'bearer', user, }; } /** * This function is used for the client_credentials oauth2 flow. * * In this flow there is not a 3rd party (resource owner). There is simply 2 * clients talk to each other. * * The client acts on behalf of itself, not someone else. */ export async function generateTokenForClient(client: OAuth2Client): Promise<OAuth2Token> { const accessToken = await generateSecretToken(); const refreshToken = await generateSecretToken(); const query = 'INSERT INTO oauth2_tokens SET created = UNIX_TIMESTAMP(), ?'; const expirySettings = getTokenExpiry(); const accessTokenExpires = Math.floor(Date.now() / 1000) + expirySettings.accessToken; const refreshTokenExpires = Math.floor(Date.now() / 1000) + expirySettings.refreshToken; await db.query(query, { oauth2_client_id: client.id, access_token: accessToken, refresh_token: refreshToken, user_id: client.app.id, access_token_expires: accessTokenExpires, refresh_token_expires: refreshTokenExpires, }); return { accessToken, refreshToken, accessTokenExpires, refreshTokenExpires, tokenType: 'bearer', user: client.app, clientId: client.id, }; } /** * This function is used for the authorization_code oauth2 flow. * * In this flow a user first authenticates itself and grants permisssion to * the client. After gaining permission the user gets redirected back to the * resource owner with a one-time code. * * The resource owner then exchanges that code for an access and refresh token. */ export async function generateTokenFromCode(client: OAuth2Client, code: string, codeVerifier: string|undefined): Promise<OAuth2Token> { const query = 'SELECT * FROM oauth2_codes WHERE code = ?'; const codeResult = await db.query(query, [code]); if (!codeResult[0].length) { throw new InvalidRequest('The supplied code was not recognized'); } const codeRecord: OAuth2CodeRecord = codeResult[0][0]; const expirySettings = getTokenExpiry(); // Delete immediately. await db.query('DELETE FROM oauth2_codes WHERE id = ?', [codeRecord.id]); validatePKCE(codeVerifier, codeRecord.code_challenge, codeRecord.code_challenge_method); if (codeRecord.created + expirySettings.code < Math.floor(Date.now() / 1000)) { throw new InvalidRequest('The supplied code has expired'); } if (codeRecord.client_id !== client.id) { throw new UnauthorizedClient('The client_id associated with the token did not match with the authenticated client credentials'); } const user = await principalService.findById(codeRecord.user_id) as User; return generateTokenForUser(client, user, codeRecord.browser_session_id || undefined); } export function validatePKCE(codeVerifier: string|undefined, codeChallenge: string|undefined, codeChallengeMethod: CodeChallengeMethod): void { if (!codeVerifier) { if (!codeChallenge) { // This request was not initiated with PKCE support, so ignore the validation return; } else { // The authorization request started with PKCE, but the token request did not follow through throw new InvalidRequest('The code verifier was not supplied'); } } // For the plain method, the derived code and the code verifier are the same let derivedCodeChallenge = codeVerifier; if (codeChallengeMethod === 'S256') { derivedCodeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64') .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); } if (codeChallenge !== derivedCodeChallenge) { throw new InvalidGrant('The code verifier does not match the code challenge'); } } /** * This function is used for the 'refresh_token' grant. * * By specifying a refresh token, a new access/refresh token pair gets * returned. This also expires the old token. */ export async function generateTokenFromRefreshToken(client: OAuth2Client, refreshToken: string): Promise<OAuth2Token> { let oldToken: OAuth2Token; try { oldToken = await getTokenByRefreshToken(refreshToken); } catch (err) { if (err instanceof NotFound) { throw new InvalidGrant('The refresh token was not recognized'); } else { throw err; } } if (oldToken.clientId !== client.id) { throw new UnauthorizedClient('The client_id associated with the refresh did not match with the authenticated client credentials'); } await revokeToken(oldToken); return generateTokenForUser(client, oldToken.user, oldToken.browserSessionId); } export async function revokeByAccessRefreshToken(client: OAuth2Client, token: string): Promise<void> { let oauth2Token: OAuth2Token|null = null; try { oauth2Token = await getTokenByAccessToken(token); } catch (err) { if (err instanceof NotFound) { // Swallow since it's okay if the token has been revoked previously or is invalid (Section 2.2 of RFC7009) } else { throw err; } } if (!oauth2Token) { try { oauth2Token = await getTokenByRefreshToken(token); } catch (err) { if (err instanceof NotFound) { // Swallow since it's okay if the token has been revoked previously or is invalid (Section 2.2 of RFC7009) } else { throw err; } } } if (!oauth2Token) { return; } if (oauth2Token.clientId !== client.id) { // Treat this as an invalid token and don't do anything return; } await revokeToken(oauth2Token); } /** * Removes a token. * * This function will not throw an error if the token was deleted before. */ export async function revokeToken(token: OAuth2Token): Promise<void> { const query = 'DELETE FROM oauth2_tokens WHERE access_token = ?'; await db.query(query, [token.accessToken]); } /** * This function is used for the authorization_code grant flow. * * This function creates an code for a user. The code is later exchanged for * a oauth2 access token. */ export async function generateCodeForUser( client: OAuth2Client, user: User, codeChallenge: string|undefined, codeChallengeMethod: string|undefined, browserSessionId: string, ): Promise<OAuth2Code> { const code = await generateSecretToken(); const query = 'INSERT INTO oauth2_codes SET created = UNIX_TIMESTAMP(), ?'; await db.query(query, { client_id: client.id, user_id: user.id, code: code, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod, browser_session_id: browserSessionId, }); return { code: code }; } type OAuth2TokenRecord = { oauth2_client_id: number; access_token: string; refresh_token: string; user_id: number; access_token_expires: number; refresh_token_expires: number; browser_session_id: string | null; }; type OAuth2CodeRecord = { id: number; client_id: number; code: string; user_id: number; code_challenge: string|undefined; code_challenge_method: CodeChallengeMethod; created: number; browser_session_id: string | null; }; /** * Returns Token information for an existing Access Token. * * This effectively gives you all information of an access token if you have * just the bearer, and allows you to validate if a bearer token is valid. * * This function will throw NotFound if the token was not recognized. */ export async function getTokenByAccessToken(accessToken: string): Promise<OAuth2Token> { const query = ` SELECT oauth2_client_id, access_token, refresh_token, user_id, access_token_expires, refresh_token_expires, browser_session_id FROM oauth2_tokens WHERE access_token = ? AND access_token_expires > UNIX_TIMESTAMP() `; const result = await db.query(query, [accessToken]); if (!result[0].length) { throw new NotFound('Access token not recognized'); } const row: OAuth2TokenRecord = result[0][0]; const user = await principalService.findActiveById(row.user_id); return { accessToken: row.access_token, refreshToken: row.refresh_token, accessTokenExpires: row.access_token_expires, refreshTokenExpires: row.refresh_token_expires, tokenType: 'bearer', user: user as App | User, clientId: row.oauth2_client_id, browserSessionId: row.browser_session_id || undefined, }; } /** * Returns Token information for an existing Refresh Token. * * This function will throw NotFound if the token was not recognized. */ export async function getTokenByRefreshToken(refreshToken: string): Promise<OAuth2Token> { const query = ` SELECT oauth2_client_id, access_token, refresh_token, user_id, access_token_expires, refresh_token_expires, browser_session_id FROM oauth2_tokens WHERE refresh_token = ? AND refresh_token_expires > UNIX_TIMESTAMP() `; const result = await db.query(query, [refreshToken]); if (!result[0].length) { throw new NotFound('Refresh token not recognized'); } const row: OAuth2TokenRecord = result[0][0]; const user = await principalService.findActiveById(row.user_id); return { accessToken: row.access_token, refreshToken: row.refresh_token, accessTokenExpires: row.access_token_expires, refreshTokenExpires: row.refresh_token_expires, tokenType: 'bearer', user: user as App | User, clientId: row.oauth2_client_id, browserSessionId: row.browser_session_id || undefined, }; } /** * Removes all tokens that relate to a specific browser session id. * * This will cause all access tokens and refresh tokens to be invalidated. Generally * used when a user logs out. * * This doesn't remove all tokens for all sessions, but should remove the tokens that * relate to the device the user used to log out. */ export async function invalidateTokensByBrowserSessionId(browserSessionId: string) { await db.query('DELETE FROM oauth2_codes WHERE browser_session_id = ?', browserSessionId); await db.query('DELETE FROM oauth2_tokens WHERE browser_session_id = ?', browserSessionId); } type TokenExpiry = { accessToken: number; refreshToken: number; code: number; }; function getTokenExpiry(): TokenExpiry { return { accessToken: getSetting('oauth2.accessToken.expiry'), refreshToken: getSetting('oauth2.refreshToken.expiry'), code: getSetting('oauth2.code.expiry'), }; }
the_stack
import * as crypto from 'crypto'; import { URL } from 'url'; import { HintContext, ReportOptions } from 'hint/dist/src/lib/hint-context'; import { IHint, FetchEnd, ElementFound, NetworkData, Request, Response } from 'hint/dist/src/lib/types'; import { debug as d } from '@hint/utils-debug'; import { normalizeString } from '@hint/utils-string'; import { requestAsync } from '@hint/utils-network'; import { Severity } from '@hint/utils-types'; import { Algorithms, OriginCriteria, ErrorData, URLs } from './types'; import meta from './meta'; import { getMessage } from './i18n.import'; const debug: debug.IDebugger = d(__filename); /* * ------------------------------------------------------------------------------ * Public * ------------------------------------------------------------------------------ */ export default class SRIHint implements IHint { public static readonly meta = meta; private context: HintContext; private origin: string = ''; private finalUrl: string = ''; private baseline: keyof typeof Algorithms = 'sha384'; private originCriteria: keyof typeof OriginCriteria = 'crossOrigin'; private cache: Map<string, ErrorData[]> = new Map(); /** Contains the keys cache keys for the element already reported. */ private reportedKeys: Set<string> = new Set(); /** * Returns the hash of the content for the given `sha` strengh in a format * valid with SRI: * * base64 * * `sha384-hash` */ private calculateHash(content: string, sha: string): string { const hash = crypto .createHash(sha) .update(content) .digest('base64'); return hash; } /** * Checks if the element that originated the request/response is a * `script` or a `stylesheet`. There could be other downloads from * a `link` element that are not stylesheets and should be ignored. */ private isScriptOrLink(evt: FetchEnd) { debug('Is <script> or <link>?'); const { element } = evt; /* * We subscribe to `fetch::end::script|css`, so element should * always exist. "that should never happen" is the fastest way * to make it happen so better be safe. */ /* istanbul ignore if */ if (!element) { return false; } const nodeName = normalizeString(element.nodeName); /* * The element is not one that we care about (could be an img, * video, etc.). No need to report anything, but we can stop * processing things right away. */ if (nodeName === 'script') { return !!element.getAttribute('src'); } if (nodeName === 'link') { const relValues = (normalizeString(element.getAttribute('rel'), ''))!.split(' '); // normalizeString won't return null as a default was passed. return relValues.includes('stylesheet'); } return false; } private report(resource: string, message: string, options: ReportOptions, evt: FetchEnd) { const errorData: ErrorData = { message, options, resource }; const cacheKey = this.getCacheKey(evt); const cacheErrors = this.getCache(evt); cacheErrors.push(errorData); this.reportedKeys.add(cacheKey); this.context.report(errorData.resource, errorData.message, errorData.options); } /** * Verifies if the response is eligible for integrity validation. I.E.: * * * `same-origin` * * `cross-origin` on a CORS-enabled request * * More info in https://w3c.github.io/webappsec-subresource-integrity/#is-response-eligible */ private isEligibleForIntegrityValidation(evt: FetchEnd, urls: URLs) { debug('Is eligible for integrity validation?'); const { element, resource } = evt; const resourceOrigin: string = new URL(resource).origin; if (urls.origin === resourceOrigin) { return true; } // cross-origin scripts need to be loaded with a valid "crossorigin" attribute (ie.: anonymous or use-credentials) const crossorigin = normalizeString(element && element.getAttribute('crossorigin')); if (!crossorigin) { const message = getMessage('crossoriginNeeded', this.context.language); this.report(urls.final, message, { element, severity: Severity.error }, evt); return false; } const validCrossorigin = crossorigin === 'anonymous' || crossorigin === 'use-credentials'; if (!validCrossorigin) { const message = getMessage('crossoriginInvalid', this.context.language); this.report(urls.final, message, { element, severity: Severity.error }, evt); } return validCrossorigin; } /** * Checks if the element that triggered the download has the `integrity` * attribute if required based on the selected origin criteria. */ private hasIntegrityAttribute(evt: FetchEnd, urls: URLs) { debug('has integrity attribute?'); const { element, resource } = evt; const integrity = element && element.getAttribute('integrity'); const resourceOrigin: string = new URL(resource).origin; const integrityRequired = OriginCriteria[this.originCriteria] === OriginCriteria.all || urls.origin !== resourceOrigin; if (integrityRequired && !integrity) { const message = getMessage('noIntegrity', this.context.language); this.report(urls.final, message, { element, severity: Severity.warning }, evt); } return !!integrity; } /** * Checks if the format of the `integrity` attribute is valid and if the used hash meets * the baseline (by default sha-384). In the case of multiple algorithms used, the * one with the highest priority is the used one to validate. E.g.: * * * `<script src="https://example.com/example-framework.js" * integrity="sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7" * crossorigin="anonymous"></script>` * * `<script src="https://example.com/example-framework.js" * integrity="sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7 * sha384-+/M6kredJcxdsqkczBUjMLvqyHb1K/JThDXWsBVxMEeZHEaMKEOEct339VItX1zB" * crossorigin="anonymous"></script>` * * https://w3c.github.io/webappsec-subresource-integrity/#agility */ private isIntegrityFormatValid(evt: FetchEnd, urls: URLs) { debug('Is integrity attribute valid?'); const { element } = evt; const integrity = element && element.getAttribute('integrity'); const integrityRegExp = /^sha(256|384|512)-/; const integrityValues = integrity ? integrity.split(/\s+/) : []; let highestAlgorithmPriority = 0; const that = this; const areFormatsValid = integrityValues.every((integrityValue: string) => { const results = integrityRegExp.exec(integrityValue); const isValid = Array.isArray(results); if (!isValid) { // integrity must exist since we're iterating over integrityValues const message = getMessage('invalidIntegrity', this.context.language); that.report(urls.final, message, { element, severity: Severity.error }, evt); return false; } // results won't be null since isValid must be true to get here. const algorithm = `sha${results![1]}` as keyof typeof Algorithms; const algorithmPriority = Algorithms[algorithm]; highestAlgorithmPriority = Math.max(algorithmPriority, highestAlgorithmPriority); return true; }); if (!areFormatsValid) { return false; } const baseline = Algorithms[this.baseline]; const meetsBaseline = highestAlgorithmPriority >= baseline; if (!meetsBaseline) { const message = getMessage('algorithmNotMeetBaseline', this.context.language, [Algorithms[highestAlgorithmPriority], this.baseline]); this.report(urls.final, message, { element, severity: Severity.warning }, evt); } return meetsBaseline; } /** * Checks if the resources is being delivered via HTTPS. * * More info: https://w3c.github.io/webappsec-subresource-integrity/#non-secure-contexts */ private isSecureContext(evt: FetchEnd, urls: URLs) { debug('Is delivered on a secure context?'); const { element, resource } = evt; const protocol = new URL(resource).protocol; const isSecure = protocol === 'https:'; if (!isSecure) { const message = getMessage('resourceNotSecure', this.context.language); this.report(urls.final, message, { element, severity: Severity.error }, evt); } return isSecure; } /** * Calculates if the hash is the right one for the downloaded resource. * * An `integrity` attribute can have multiple hashes for the same algorithm and it will * pass as long as one validates. * * More info: https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist */ private hasRightHash(evt: FetchEnd, urls: URLs) { debug('Does it have the right hash?'); const { element, response } = evt; const integrity = element && element.getAttribute('integrity'); const integrities = integrity ? integrity.split(/\s+/) : []; const calculatedHashes: Map<string, string> = new Map(); const isOK = integrities.some((integrityValue) => { const integrityRegExp = /^sha(256|384|512)-(.*)$/; const [, bits = '', hash = ''] = integrityRegExp.exec(integrityValue) || []; const calculatedHash = calculatedHashes.has(bits) ? calculatedHashes.get(bits)! : this.calculateHash(response.body.content, `sha${bits}`); calculatedHashes.set(bits, calculatedHash); return hash === calculatedHash; }); if (!isOK) { const hashes: string[] = []; calculatedHashes.forEach((value, key) => { hashes.push(`sha${key}-${value}`); }); const message = getMessage('hashDoesNotMatch', this.context.language); this.report(urls.final, message, { element, severity: Severity.error }, evt); } return isOK; } private getCache(evt: FetchEnd): ErrorData[] { const key = this.getCacheKey(evt); if (!this.cache.has(key)) { this.cache.set(key, []); } return this.cache.get(key)!; } private getCacheKey(evt: FetchEnd): string { const { element, resource } = evt; /* istanbul ignore if */ if (!element) { return ''; } const integrity = element.getAttribute('integrity'); return `${resource}${integrity}`; } private addToCache(evt: FetchEnd) { const { element, resource } = evt; /* istanbul ignore if */ if (!element) { return false; } const integrity = element.getAttribute('integrity'); const key = `${resource}${integrity}`; if (!this.cache.has(key)) { this.cache.set(key, []); } return true; } /** * If the resource is a local file, ignore the analysis. * The sri usually is added on the building process before publish, * so is going to be very common that the sri doesn't exists * for local files. */ private isNotLocalResource(evt: FetchEnd) { const { resource } = evt; if (resource.startsWith('file://')) { debug(`Ignoring local resource: ${resource}`); return false; } return true; } /** * The item is cached. For the VSCode extension and the * local connector with option 'watch' activated we * should report what we have in the cache after the * first 'scan::end'. */ private isInCache(evt: FetchEnd) { const cacheKey = this.getCacheKey(evt); const isInCache = this.cache.has(cacheKey); if (isInCache && !this.reportedKeys.has(cacheKey)) { this.getCache(evt).forEach((error) => { this.context.report(error.resource, error.message, error.options); }); this.reportedKeys.add(cacheKey); return false; } return !isInCache; } /** * `requestAsync` is not included in webpack bundle for `extension-browser`. * This is ok because the browser will have already requested this via `fetch::end` * events. * * Note: We are not using `Requester` because it depends on `iltorb` and it can * cause problems with the vscode-extension because `iltorb` depends on the * node version for which it was compiled. * * We can probably use Requester once https://github.com/webhintio/hint/issues/1604 is done, * and vscode use the node version that support it. * * When using crossorigin="use-credentials" and the response contains * the header `Access-Control-Allow-Origin` with value `*` Chrome blocks the access * to the resource by CORS policy, so we will reach this point * through the traverse of the dom and response.body.content will be ''. In this case, * we have to prevent the download of the resource. */ private async downloadContent(evt: FetchEnd, urls: URLs) { const { resource, response, element } = evt; if (!requestAsync && !response.body.content) { // Stop the validations. return false; } if (!requestAsync) { return true; } /* If the content already exists, we don't need to download it. */ if (response.body.content) { return true; } try { response.body.content = await requestAsync({ gzip: true, method: 'GET', rejectUnauthorized: false, url: resource }); return true; } catch (e) { debug(`Error accessing ${resource}. ${JSON.stringify(e)}`); this.context.report( urls.final, getMessage('canNotGetResource', this.context.language), { element, severity: Severity.error } ); return false; } } private isNotIgnored(evt: FetchEnd) { return !this.context.isUrlIgnored(evt.resource); } /** Validation entry point. */ private async validateResource(evt: FetchEnd, urls: URLs) { const validations = [ this.isNotIgnored, this.isInCache, this.addToCache, this.isScriptOrLink, this.isNotLocalResource, this.isEligibleForIntegrityValidation, this.hasIntegrityAttribute, this.isIntegrityFormatValid, this.isSecureContext, this.downloadContent, this.hasRightHash ].map((fn) => { return fn.bind(this); }); debug(`Validating integrity of: ${evt.resource}`); for (const validation of validations) { const valid = await validation(evt, urls); if (!valid) { break; } } } /** * Validation entry point for event element::script * or element::link */ private async validateElement(evt: ElementFound) { const isScriptOrLink = await this.isScriptOrLink(evt as FetchEnd); if (!isScriptOrLink) { return; } const finalUrl = evt.resource; const origin = new URL(evt.resource).origin; /* * 'this.isScriptOrLink' has already checked * that the src or href attribute exists, so it is safe to use !. */ const elementUrl = evt.element.getAttribute('src')! || evt.element.getAttribute('href')!; evt.resource = evt.element.resolveUrl(elementUrl); const content: NetworkData = { request: {} as Request, response: { body: { content: '' } } as Response }; await this.validateResource({ ...evt, request: content.request, response: content.response }, { final: finalUrl, origin }); } /** Sets the `origin` property using the initial request. */ private setOrigin(evt: FetchEnd): void { const { resource } = evt; this.origin = new URL(resource).origin; // Our @types/node doesn't have it this.finalUrl = resource; } private onScanEnd(): void { this.reportedKeys.clear(); } public constructor(context: HintContext) { this.context = context; if (context.hintOptions) { this.baseline = context.hintOptions.baseline || this.baseline; this.originCriteria = context.hintOptions.originCriteria || this.originCriteria; } context.on('fetch::end::script', (evt: FetchEnd) => { this.validateResource(evt, { final: this.finalUrl, origin: this.origin }); }); context.on('fetch::end::css', (evt: FetchEnd) => { this.validateResource(evt, { final: this.finalUrl, origin: this.origin }); }); context.on('element::script', this.validateElement.bind(this)); context.on('element::link', this.validateElement.bind(this)); context.on('fetch::end::html', this.setOrigin.bind(this)); context.on('scan::end', this.onScanEnd.bind(this)); } }
the_stack
import _ = require("../index"); declare module "../index" { // castArray interface LoDashStatic { /** * Casts value as an array if it’s not one. * * @param value The value to inspect. * @return Returns the cast array. */ castArray<T>(value?: Many<T>): T[]; } interface LoDashImplicitWrapper<TValue> { /** * @see _.castArray */ castArray<T>(this: LoDashImplicitWrapper<Many<T>>): LoDashImplicitWrapper<T[]>; } interface LoDashExplicitWrapper<TValue> { /** * @see _.castArray */ castArray<T>(this: LoDashExplicitWrapper<Many<T>>): LoDashExplicitWrapper<T[]>; } // clone interface LoDashStatic { /** * Creates a shallow clone of value. * * Note: This method is loosely based on the structured clone algorithm and supports cloning arrays, * array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, * and typed arrays. The own enumerable properties of arguments objects are cloned as plain objects. An empty * object is returned for uncloneable values such as error objects, functions, DOM nodes, and WeakMaps. * * @param value The value to clone. * @return Returns the cloned value. */ clone<T>(value: T): T; } interface LoDashImplicitWrapper<TValue> { /** * @see _.clone */ clone(): TValue; } interface LoDashExplicitWrapper<TValue> { /** * @see _.clone */ clone(): this; } // cloneDeep interface LoDashStatic { /** * This method is like _.clone except that it recursively clones value. * * @param value The value to recursively clone. * @return Returns the deep cloned value. */ cloneDeep<T>(value: T): T; } interface LoDashImplicitWrapper<TValue> { /** * @see _.cloneDeep */ cloneDeep(): TValue; } interface LoDashExplicitWrapper<TValue> { /** * @see _.cloneDeep */ cloneDeep(): this; } // cloneDeepWith type CloneDeepWithCustomizer<TObject> = (value: any, key: number | string | undefined, object: TObject | undefined, stack: any) => any; interface LoDashStatic { /** * This method is like _.cloneWith except that it recursively clones value. * * @param value The value to recursively clone. * @param customizer The function to customize cloning. * @return Returns the deep cloned value. */ cloneDeepWith<T>( value: T, customizer: CloneDeepWithCustomizer<T> ): any; /** * @see _.cloneDeepWith */ cloneDeepWith<T>(value: T): T; } interface LoDashImplicitWrapper<TValue> { /** * @see _.cloneDeepWith */ cloneDeepWith( customizer: CloneDeepWithCustomizer<TValue> ): any; /** * @see _.cloneDeepWith */ cloneDeepWith(): TValue; } interface LoDashExplicitWrapper<TValue> { /** * @see _.cloneDeepWith */ cloneDeepWith( customizer: CloneDeepWithCustomizer<TValue> ): LoDashExplicitWrapper<any>; /** * @see _.cloneDeepWith */ cloneDeepWith(): this; } // cloneWith type CloneWithCustomizer<TValue, TResult> = (value: TValue, key: number | string | undefined, object: any, stack: any) => TResult; interface LoDashStatic { /** * This method is like _.clone except that it accepts customizer which is invoked to produce the cloned value. * If customizer returns undefined cloning is handled by the method instead. * * @param value The value to clone. * @param customizer The function to customize cloning. * @return Returns the cloned value. */ cloneWith<T, TResult extends object | string | number | boolean | null>( value: T, customizer: CloneWithCustomizer<T, TResult> ): TResult; /** * @see _.cloneWith */ cloneWith<T, TResult>( value: T, customizer: CloneWithCustomizer<T, TResult | undefined> ): TResult | T; /** * @see _.cloneWith */ cloneWith<T>(value: T): T; } interface LoDashImplicitWrapper<TValue> { /** * @see _.cloneWith */ cloneWith<TResult extends object | string | number | boolean | null>( customizer: CloneWithCustomizer<TValue, TResult> ): TResult; /** * @see _.cloneWith */ cloneWith<TResult>( customizer: CloneWithCustomizer<TValue, TResult | undefined> ): TResult | TValue; /** * @see _.cloneWith */ cloneWith(): TValue; } interface LoDashExplicitWrapper<TValue> { /** * @see _.cloneWith */ cloneWith<TResult extends object | string | number | boolean | null>( customizer: CloneWithCustomizer<TValue, TResult> ): LoDashExplicitWrapper<TResult>; /** * @see _.cloneWith */ cloneWith<TResult>( customizer: CloneWithCustomizer<TValue, TResult | undefined> ): LoDashExplicitWrapper<TResult | TValue>; /** * @see _.cloneWith */ cloneWith(): this; } // conformsTo interface LoDashStatic { /** * Checks if object conforms to source by invoking the predicate properties of source with the * corresponding property values of object. * * Note: This method is equivalent to _.conforms when source is partially applied. */ conformsTo<T>(object: T, source: ConformsPredicateObject<T>): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.conformsTo */ conformsTo<T>(this: LoDashImplicitWrapper<T>, source: ConformsPredicateObject<T>): boolean; // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } interface LoDashExplicitWrapper<TValue> { /** * @see _.conformsTo */ conformsTo<T>(this: LoDashExplicitWrapper<T>, source: ConformsPredicateObject<T>): LoDashExplicitWrapper<boolean>; // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } type CondPair<T, R> = [(val: T) => boolean, (val: T) => R]; // eq interface LoDashStatic { /** * Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @category Lang * @param value The value to compare. * @param other The other value to compare. * @returns Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ eq( value: any, other: any ): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.eq */ eq( other: any ): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.eq */ eq( other: any ): LoDashExplicitWrapper<boolean>; } // gt interface LoDashStatic { /** * Checks if value is greater than other. * * @param value The value to compare. * @param other The other value to compare. * @return Returns true if value is greater than other, else false. */ gt( value: any, other: any ): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.gt */ gt(other: any): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.gt */ gt(other: any): LoDashExplicitWrapper<boolean>; } // gte interface LoDashStatic { /** * Checks if value is greater than or equal to other. * * @param value The value to compare. * @param other The other value to compare. * @return Returns true if value is greater than or equal to other, else false. */ gte( value: any, other: any ): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.gte */ gte(other: any): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.gte */ gte(other: any): LoDashExplicitWrapper<boolean>; } // isArguments interface LoDashStatic { /** * Checks if value is classified as an arguments object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isArguments(value?: any): value is IArguments; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isArguments */ isArguments(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isArguments */ isArguments(): LoDashExplicitWrapper<boolean>; } // isArray interface LoDashStatic { /** * Checks if value is classified as an Array object. * @param value The value to check. * * @return Returns true if value is correctly classified, else false. */ isArray(value?: any): value is any[]; /** * DEPRECATED */ isArray<T>(value?: any): value is any[]; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isArray */ isArray(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isArray */ isArray(): LoDashExplicitWrapper<boolean>; } // isArrayBuffer interface LoDashStatic { /** * Checks if value is classified as an ArrayBuffer object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isArrayBuffer(value?: any): value is ArrayBuffer; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isArrayBuffer */ isArrayBuffer(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isArrayBuffer */ isArrayBuffer(): LoDashExplicitWrapper<boolean>; } // isArrayLike interface LoDashStatic { /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @category Lang * @param value The value to check. * @returns Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ isArrayLike<T>(value: T & string & number): boolean; // should only match if T = any /** * @see _.isArrayLike */ isArrayLike(value: ((...args: any[]) => any) | null | undefined): value is never; /** * @see _.isArrayLike */ isArrayLike(value: any): value is { length: number }; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isArrayLike */ isArrayLike(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isArrayLike */ isArrayLike(): LoDashExplicitWrapper<boolean>; } // isArrayLikeObject interface LoDashStatic { /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @category Lang * @param value The value to check. * @returns Returns `true` if `value` is an array-like object, else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ isArrayLikeObject<T>(value: T & string & number): boolean; // should only match if T = any /** * @see _.isArrayLike */ // tslint:disable-next-line:ban-types (type guard doesn't seem to work correctly without the Function type) isArrayLikeObject(value: ((...args: any[]) => any) | Function | string | boolean | number | null | undefined): value is never; /** * @see _.isArrayLike */ // tslint:disable-next-line:ban-types (type guard doesn't seem to work correctly without the Function type) isArrayLikeObject<T extends object>(value: T | ((...args: any[]) => any) | Function | string | boolean | number | null | undefined): value is T & { length: number }; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isArrayLikeObject */ isArrayLikeObject(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isArrayLikeObject */ isArrayLikeObject(): LoDashExplicitWrapper<boolean>; } // isBoolean interface LoDashStatic { /** * Checks if value is classified as a boolean primitive or object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isBoolean(value?: any): value is boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isBoolean */ isBoolean(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isBoolean */ isBoolean(): LoDashExplicitWrapper<boolean>; } // isBuffer interface LoDashStatic { /** * Checks if value is a buffer. * * @param value The value to check. * @return Returns true if value is a buffer, else false. */ isBuffer(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isBuffer */ isBuffer(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isBuffer */ isBuffer(): LoDashExplicitWrapper<boolean>; } // isDate interface LoDashStatic { /** * Checks if value is classified as a Date object. * @param value The value to check. * * @return Returns true if value is correctly classified, else false. */ isDate(value?: any): value is Date; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isDate */ isDate(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isDate */ isDate(): LoDashExplicitWrapper<boolean>; } // isElement interface LoDashStatic { /** * Checks if value is a DOM element. * * @param value The value to check. * @return Returns true if value is a DOM element, else false. */ isElement(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isElement */ isElement(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isElement */ isElement(): LoDashExplicitWrapper<boolean>; } // isEmpty interface LoDashStatic { /** * Checks if value is empty. A value is considered empty unless it’s an arguments object, array, string, or * jQuery-like collection with a length greater than 0 or an object with own enumerable properties. * * @param value The value to inspect. * @return Returns true if value is empty, else false. */ isEmpty(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isEmpty */ isEmpty(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isEmpty */ isEmpty(): LoDashExplicitWrapper<boolean>; } // isEqual interface LoDashStatic { /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are **not** supported. * * @category Lang * @param value The value to compare. * @param other The other value to compare. * @returns Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ isEqual( value: any, other: any ): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isEqual */ isEqual( other: any ): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isEqual */ isEqual( other: any ): LoDashExplicitWrapper<boolean>; } // isEqualWith type IsEqualCustomizer = (value: any, other: any, indexOrKey: PropertyName | undefined, parent: any, otherParent: any, stack: any) => boolean|undefined; interface LoDashStatic { /** * This method is like `_.isEqual` except that it accepts `customizer` which is * invoked to compare values. If `customizer` returns `undefined` comparisons are * handled by the method instead. The `customizer` is invoked with up to seven arguments: * (objValue, othValue [, index|key, object, other, stack]). * * @category Lang * @param value The value to compare. * @param other The other value to compare. * @param [customizer] The function to customize comparisons. * @returns Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ isEqualWith( value: any, other: any, customizer?: IsEqualCustomizer ): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isEqualWith */ isEqualWith( other: any, customizer?: IsEqualCustomizer ): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isEqualWith */ isEqualWith( other: any, customizer?: IsEqualCustomizer ): LoDashExplicitWrapper<boolean>; } // isError interface LoDashStatic { /** * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError * object. * * @param value The value to check. * @return Returns true if value is an error object, else false. */ isError(value: any): value is Error; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isError */ isError(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isError */ isError(): LoDashExplicitWrapper<boolean>; } // isFinite interface LoDashStatic { /** * Checks if value is a finite primitive number. * * Note: This method is based on Number.isFinite. * * @param value The value to check. * @return Returns true if value is a finite number, else false. */ isFinite(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isFinite */ isFinite(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isFinite */ isFinite(): LoDashExplicitWrapper<boolean>; } // isFunction interface LoDashStatic { /** * Checks if value is a callable function. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isFunction(value: any): value is (...args: any[]) => any; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isFunction */ isFunction(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isFunction */ isFunction(): LoDashExplicitWrapper<boolean>; } // isInteger interface LoDashStatic { /** * Checks if `value` is an integer. * * **Note:** This method is based on [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @category Lang * @param value The value to check. * @returns Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ isInteger(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isInteger */ isInteger(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isInteger */ isInteger(): LoDashExplicitWrapper<boolean>; } // isLength interface LoDashStatic { /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @category Lang * @param value The value to check. * @returns Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ isLength(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isLength */ isLength(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isLength */ isLength(): LoDashExplicitWrapper<boolean>; } // isMap interface LoDashStatic { /** * Checks if value is classified as a Map object. * * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ isMap(value?: any): value is Map<any, any>; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isMap */ isMap(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isMap */ isMap(): LoDashExplicitWrapper<boolean>; } // isMatch type isMatchCustomizer = (value: any, other: any, indexOrKey?: PropertyName) => boolean; interface LoDashStatic { /** * Performs a deep comparison between `object` and `source` to determine if * `object` contains equivalent property values. * * **Note:** This method supports comparing the same values as `_.isEqual`. * * @category Lang * @param object The object to inspect. * @param source The object of property values to match. * @returns Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.isMatch(object, { 'age': 40 }); * // => true * * _.isMatch(object, { 'age': 36 }); * // => false */ isMatch(object: object, source: object): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isMatch */ isMatch(source: object): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isMatch */ isMatch(source: object): LoDashExplicitWrapper<boolean>; } // isMatchWith type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName, object: object, source: object) => boolean | undefined; interface LoDashStatic { /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined` comparisons * are handled by the method instead. The `customizer` is invoked with three * arguments: (objValue, srcValue, index|key, object, source). * * @category Lang * @param object The object to inspect. * @param source The object of property values to match. * @param [customizer] The function to customize comparisons. * @returns Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ isMatchWith(object: object, source: object, customizer: isMatchWithCustomizer): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isMatchWith */ isMatchWith(source: object, customizer: isMatchWithCustomizer): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isMatchWith */ isMatchWith(source: object, customizer: isMatchWithCustomizer): LoDashExplicitWrapper<boolean>; } // isNaN interface LoDashStatic { /** * Checks if value is NaN. * * Note: This method is not the same as isNaN which returns true for undefined and other non-numeric values. * * @param value The value to check. * @return Returns true if value is NaN, else false. */ isNaN(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isNaN */ isNaN(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isNaN */ isNaN(): LoDashExplicitWrapper<boolean>; } // isNative interface LoDashStatic { /** * Checks if value is a native function. * @param value The value to check. * * @retrun Returns true if value is a native function, else false. */ isNative(value: any): value is (...args: any[]) => any; } interface LoDashImplicitWrapper<TValue> { /** * see _.isNative */ isNative(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isNative */ isNative(): LoDashExplicitWrapper<boolean>; } // isNil interface LoDashStatic { /** * Checks if `value` is `null` or `undefined`. * * @category Lang * @param value The value to check. * @returns Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ isNil(value: any): value is null | undefined; } interface LoDashImplicitWrapper<TValue> { /** * see _.isNil */ isNil(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isNil */ isNil(): LoDashExplicitWrapper<boolean>; } // isNull interface LoDashStatic { /** * Checks if value is null. * * @param value The value to check. * @return Returns true if value is null, else false. */ isNull(value: any): value is null; } interface LoDashImplicitWrapper<TValue> { /** * see _.isNull */ isNull(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isNull */ isNull(): LoDashExplicitWrapper<boolean>; } // isNumber interface LoDashStatic { /** * Checks if value is classified as a Number primitive or object. * * Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isNumber(value?: any): value is number; } interface LoDashImplicitWrapper<TValue> { /** * see _.isNumber */ isNumber(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isNumber */ isNumber(): LoDashExplicitWrapper<boolean>; } // isObject interface LoDashStatic { /** * Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), * and new String('')) * * @param value The value to check. * @return Returns true if value is an object, else false. */ isObject(value?: any): value is object; } interface LoDashImplicitWrapper<TValue> { /** * see _.isObject */ isObject(): this is LoDashImplicitWrapper<object>; } interface LoDashExplicitWrapper<TValue> { /** * see _.isObject */ isObject(): LoDashExplicitWrapper<boolean>; } // isObjectLike interface LoDashStatic { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @category Lang * @param value The value to check. * @returns Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ isObjectLike(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * see _.isObjectLike */ isObjectLike(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isObjectLike */ isObjectLike(): LoDashExplicitWrapper<boolean>; } // isPlainObject interface LoDashStatic { /** * Checks if value is a plain object, that is, an object created by the Object constructor or one with a * [[Prototype]] of null. * * Note: This method assumes objects created by the Object constructor have no inherited enumerable properties. * * @param value The value to check. * @return Returns true if value is a plain object, else false. */ isPlainObject(value?: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * see _.isPlainObject */ isPlainObject(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isPlainObject */ isPlainObject(): LoDashExplicitWrapper<boolean>; } // isRegExp interface LoDashStatic { /** * Checks if value is classified as a RegExp object. * @param value The value to check. * * @return Returns true if value is correctly classified, else false. */ isRegExp(value?: any): value is RegExp; } interface LoDashImplicitWrapper<TValue> { /** * see _.isRegExp */ isRegExp(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isRegExp */ isRegExp(): LoDashExplicitWrapper<boolean>; } // isSafeInteger interface LoDashStatic { /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @category Lang * @param value The value to check. * @returns Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ isSafeInteger(value: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * see _.isSafeInteger */ isSafeInteger(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isSafeInteger */ isSafeInteger(): LoDashExplicitWrapper<boolean>; } // isSet interface LoDashStatic { /** * Checks if value is classified as a Set object. * * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ isSet(value?: any): value is Set<any>; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isSet */ isSet(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isSet */ isSet(): LoDashExplicitWrapper<boolean>; } // isString interface LoDashStatic { /** * Checks if value is classified as a String primitive or object. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isString(value?: any): value is string; } interface LoDashImplicitWrapper<TValue> { /** * see _.isString */ isString(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isString */ isString(): LoDashExplicitWrapper<boolean>; } // isSymbol interface LoDashStatic { /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @category Lang * @param value The value to check. * @returns Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ isSymbol(value: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * see _.isSymbol */ isSymbol(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isSymbol */ isSymbol(): LoDashExplicitWrapper<boolean>; } // isTypedArray interface LoDashStatic { /** * Checks if value is classified as a typed array. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ isTypedArray(value: any): boolean; } interface LoDashImplicitWrapper<TValue> { /** * see _.isTypedArray */ isTypedArray(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isTypedArray */ isTypedArray(): LoDashExplicitWrapper<boolean>; } // isUndefined interface LoDashStatic { /** * Checks if value is undefined. * * @param value The value to check. * @return Returns true if value is undefined, else false. */ isUndefined(value: any): value is undefined; } interface LoDashImplicitWrapper<TValue> { /** * see _.isUndefined */ isUndefined(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * see _.isUndefined */ isUndefined(): LoDashExplicitWrapper<boolean>; } // isWeakMap interface LoDashStatic { /** * Checks if value is classified as a WeakMap object. * * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ isWeakMap(value?: any): value is WeakMap<object, any>; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isSet */ isWeakMap(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isSet */ isWeakMap(): LoDashExplicitWrapper<boolean>; } // isWeakSet interface LoDashStatic { /** * Checks if value is classified as a WeakSet object. * * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ isWeakSet(value?: any): value is WeakSet<object>; } interface LoDashImplicitWrapper<TValue> { /** * @see _.isWeakSet */ isWeakSet(): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.isWeakSet */ isWeakSet(): LoDashExplicitWrapper<boolean>; } // lt interface LoDashStatic { /** * Checks if value is less than other. * * @param value The value to compare. * @param other The other value to compare. * @return Returns true if value is less than other, else false. */ lt( value: any, other: any ): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.lt */ lt(other: any): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.lt */ lt(other: any): LoDashExplicitWrapper<boolean>; } // lte interface LoDashStatic { /** * Checks if value is less than or equal to other. * * @param value The value to compare. * @param other The other value to compare. * @return Returns true if value is less than or equal to other, else false. */ lte( value: any, other: any ): boolean; } interface LoDashImplicitWrapper<TValue> { /** * @see _.lte */ lte(other: any): boolean; } interface LoDashExplicitWrapper<TValue> { /** * @see _.lte */ lte(other: any): LoDashExplicitWrapper<boolean>; } // toArray interface LoDashStatic { /** * Converts value to an array. * * @param value The value to convert. * @return Returns the converted array. */ toArray<T>(value: List<T> | Dictionary<T> | NumericDictionary<T> | null | undefined): T[]; /** * @see _.toArray */ toArray<T>(value: T): Array<T[keyof T]>; /** * @see _.toArray */ toArray(): any[]; } interface LoDashImplicitWrapper<TValue> { /** * @see _.toArray */ toArray<T>(this: LoDashImplicitWrapper<List<T> | Dictionary<T> | NumericDictionary<T> | null | undefined>): LoDashImplicitWrapper<T[]>; /** * @see _.toArray */ toArray<T extends object>(this: LoDashImplicitWrapper<T>): LoDashImplicitWrapper<Array<T[keyof T]>>; } interface LoDashExplicitWrapper<TValue> { /** * @see _.toArray */ toArray<T>(this: LoDashExplicitWrapper<List<T> | Dictionary<T> | NumericDictionary<T> | null | undefined>): LoDashExplicitWrapper<T[]>; /** * @see _.toArray */ toArray<T extends object>(this: LoDashImplicitWrapper<T>): LoDashExplicitWrapper<Array<T[keyof T]>>; } // toFinite interface LoDashStatic { /** * Converts `value` to a finite number. * * @since 4.12.0 * @category Lang * @param value The value to convert. * @returns Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ toFinite(value: any): number; } interface LoDashImplicitWrapper<TValue> { /** * @see _.toFinite */ toFinite(): number; } interface LoDashExplicitWrapper<TValue> { /** * @see _.toFinite */ toFinite(): LoDashExplicitWrapper<number>; } // toInteger interface LoDashStatic { /** * Converts `value` to an integer. * * **Note:** This function is loosely based on [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger). * * @category Lang * @param value The value to convert. * @returns Returns the converted integer. * @example * * _.toInteger(3); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3'); * // => 3 */ toInteger(value: any): number; } interface LoDashImplicitWrapper<TValue> { /** * @see _.toInteger */ toInteger(): number; } interface LoDashExplicitWrapper<TValue> { /** * @see _.toInteger */ toInteger(): LoDashExplicitWrapper<number>; } // toLength interface LoDashStatic { /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @category Lang * @param value The value to convert. * @return Returns the converted integer. * @example * * _.toLength(3); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3'); * // => 3 */ toLength(value: any): number; } interface LoDashImplicitWrapper<TValue> { /** * @see _.toLength */ toLength(): number; } interface LoDashExplicitWrapper<TValue> { /** * @see _.toLength */ toLength(): LoDashExplicitWrapper<number>; } // toNumber interface LoDashStatic { /** * Converts `value` to a number. * * @category Lang * @param value The value to process. * @returns Returns the number. * @example * * _.toNumber(3); * // => 3 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3'); * // => 3 */ toNumber(value: any): number; } interface LoDashImplicitWrapper<TValue> { /** * @see _.toNumber */ toNumber(): number; } interface LoDashExplicitWrapper<TValue> { /** * @see _.toNumber */ toNumber(): LoDashExplicitWrapper<number>; } // toPlainObject interface LoDashStatic { /** * Converts value to a plain object flattening inherited enumerable properties of value to own properties * of the plain object. * * @param value The value to convert. * @return Returns the converted plain object. */ toPlainObject(value?: any): any; } interface LoDashImplicitWrapper<TValue> { /** * @see _.toPlainObject */ toPlainObject(): LoDashImplicitWrapper<any>; } interface LoDashExplicitWrapper<TValue> { /** * @see _.toPlainObject */ toPlainObject(): LoDashExplicitWrapper<any>; } // toSafeInteger interface LoDashStatic { /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @category Lang * @param value The value to convert. * @returns Returns the converted integer. * @example * * _.toSafeInteger(3); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3'); * // => 3 */ toSafeInteger(value: any): number; } interface LoDashImplicitWrapper<TValue> { /** * @see _.toSafeInteger */ toSafeInteger(): number; } interface LoDashExplicitWrapper<TValue> { /** * @see _.toSafeInteger */ toSafeInteger(): LoDashExplicitWrapper<number>; } // toString interface LoDashStatic { /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` and `undefined` values. The sign of `-0` is preserved. * * @category Lang * @param value The value to process. * @returns Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ toString(value: any): string; } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Namespaces } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { NotificationHubsManagementClient } from "../notificationHubsManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { NamespaceResource, NamespacesListNextOptionalParams, NamespacesListOptionalParams, NamespacesListAllNextOptionalParams, NamespacesListAllOptionalParams, SharedAccessAuthorizationRuleResource, NamespacesListAuthorizationRulesNextOptionalParams, NamespacesListAuthorizationRulesOptionalParams, CheckAvailabilityParameters, NamespacesCheckAvailabilityOptionalParams, NamespacesCheckAvailabilityResponse, NamespaceCreateOrUpdateParameters, NamespacesCreateOrUpdateOptionalParams, NamespacesCreateOrUpdateResponse, NamespacePatchParameters, NamespacesPatchOptionalParams, NamespacesPatchResponse, NamespacesDeleteOptionalParams, NamespacesGetOptionalParams, NamespacesGetResponse, SharedAccessAuthorizationRuleCreateOrUpdateParameters, NamespacesCreateOrUpdateAuthorizationRuleOptionalParams, NamespacesCreateOrUpdateAuthorizationRuleResponse, NamespacesDeleteAuthorizationRuleOptionalParams, NamespacesGetAuthorizationRuleOptionalParams, NamespacesGetAuthorizationRuleResponse, NamespacesListResponse, NamespacesListAllResponse, NamespacesListAuthorizationRulesResponse, NamespacesListKeysOptionalParams, NamespacesListKeysResponse, PolicykeyResource, NamespacesRegenerateKeysOptionalParams, NamespacesRegenerateKeysResponse, NamespacesListNextResponse, NamespacesListAllNextResponse, NamespacesListAuthorizationRulesNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Namespaces operations. */ export class NamespacesImpl implements Namespaces { private readonly client: NotificationHubsManagementClient; /** * Initialize a new instance of the class Namespaces class. * @param client Reference to the service client */ constructor(client: NotificationHubsManagementClient) { this.client = client; } /** * Lists the available namespaces within a resourceGroup. * @param resourceGroupName The name of the resource group. If resourceGroupName value is null the * method lists all the namespaces within subscription * @param options The options parameters. */ public list( resourceGroupName: string, options?: NamespacesListOptionalParams ): PagedAsyncIterableIterator<NamespaceResource> { const iter = this.listPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, options); } }; } private async *listPagingPage( resourceGroupName: string, options?: NamespacesListOptionalParams ): AsyncIterableIterator<NamespaceResource[]> { let result = await this._list(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, options?: NamespacesListOptionalParams ): AsyncIterableIterator<NamespaceResource> { for await (const page of this.listPagingPage(resourceGroupName, options)) { yield* page; } } /** * Lists all the available namespaces within the subscription irrespective of the resourceGroups. * @param options The options parameters. */ public listAll( options?: NamespacesListAllOptionalParams ): PagedAsyncIterableIterator<NamespaceResource> { const iter = this.listAllPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAllPagingPage(options); } }; } private async *listAllPagingPage( options?: NamespacesListAllOptionalParams ): AsyncIterableIterator<NamespaceResource[]> { let result = await this._listAll(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAllNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listAllPagingAll( options?: NamespacesListAllOptionalParams ): AsyncIterableIterator<NamespaceResource> { for await (const page of this.listAllPagingPage(options)) { yield* page; } } /** * Gets the authorization rules for a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name * @param options The options parameters. */ public listAuthorizationRules( resourceGroupName: string, namespaceName: string, options?: NamespacesListAuthorizationRulesOptionalParams ): PagedAsyncIterableIterator<SharedAccessAuthorizationRuleResource> { const iter = this.listAuthorizationRulesPagingAll( resourceGroupName, namespaceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, options ); } }; } private async *listAuthorizationRulesPagingPage( resourceGroupName: string, namespaceName: string, options?: NamespacesListAuthorizationRulesOptionalParams ): AsyncIterableIterator<SharedAccessAuthorizationRuleResource[]> { let result = await this._listAuthorizationRules( resourceGroupName, namespaceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAuthorizationRulesNext( resourceGroupName, namespaceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAuthorizationRulesPagingAll( resourceGroupName: string, namespaceName: string, options?: NamespacesListAuthorizationRulesOptionalParams ): AsyncIterableIterator<SharedAccessAuthorizationRuleResource> { for await (const page of this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, options )) { yield* page; } } /** * Checks the availability of the given service namespace across all Azure subscriptions. This is * useful because the domain name is created based on the service namespace name. * @param parameters The namespace name. * @param options The options parameters. */ checkAvailability( parameters: CheckAvailabilityParameters, options?: NamespacesCheckAvailabilityOptionalParams ): Promise<NamespacesCheckAvailabilityResponse> { return this.client.sendOperationRequest( { parameters, options }, checkAvailabilityOperationSpec ); } /** * Creates/Updates a service namespace. Once created, this namespace's resource manifest is immutable. * This operation is idempotent. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param parameters Parameters supplied to create a Namespace Resource. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, namespaceName: string, parameters: NamespaceCreateOrUpdateParameters, options?: NamespacesCreateOrUpdateOptionalParams ): Promise<NamespacesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, parameters, options }, createOrUpdateOperationSpec ); } /** * Patches the existing namespace * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param parameters Parameters supplied to patch a Namespace Resource. * @param options The options parameters. */ patch( resourceGroupName: string, namespaceName: string, parameters: NamespacePatchParameters, options?: NamespacesPatchOptionalParams ): Promise<NamespacesPatchResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, parameters, options }, patchOperationSpec ); } /** * Deletes an existing namespace. This operation also removes all associated notificationHubs under the * namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, namespaceName: string, options?: NamespacesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, namespaceName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Deletes an existing namespace. This operation also removes all associated notificationHubs under the * namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, namespaceName: string, options?: NamespacesDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, namespaceName, options ); return poller.pollUntilDone(); } /** * Returns the description for the specified namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param options The options parameters. */ get( resourceGroupName: string, namespaceName: string, options?: NamespacesGetOptionalParams ): Promise<NamespacesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, options }, getOperationSpec ); } /** * Creates an authorization rule for a namespace * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param authorizationRuleName Authorization Rule Name. * @param parameters The shared access authorization rule. * @param options The options parameters. */ createOrUpdateAuthorizationRule( resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: SharedAccessAuthorizationRuleCreateOrUpdateParameters, options?: NamespacesCreateOrUpdateAuthorizationRuleOptionalParams ): Promise<NamespacesCreateOrUpdateAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, authorizationRuleName, parameters, options }, createOrUpdateAuthorizationRuleOperationSpec ); } /** * Deletes a namespace authorization rule * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param authorizationRuleName Authorization Rule Name. * @param options The options parameters. */ deleteAuthorizationRule( resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: NamespacesDeleteAuthorizationRuleOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, authorizationRuleName, options }, deleteAuthorizationRuleOperationSpec ); } /** * Gets an authorization rule for a namespace by name. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name * @param authorizationRuleName Authorization rule name. * @param options The options parameters. */ getAuthorizationRule( resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: NamespacesGetAuthorizationRuleOptionalParams ): Promise<NamespacesGetAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, authorizationRuleName, options }, getAuthorizationRuleOperationSpec ); } /** * Lists the available namespaces within a resourceGroup. * @param resourceGroupName The name of the resource group. If resourceGroupName value is null the * method lists all the namespaces within subscription * @param options The options parameters. */ private _list( resourceGroupName: string, options?: NamespacesListOptionalParams ): Promise<NamespacesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listOperationSpec ); } /** * Lists all the available namespaces within the subscription irrespective of the resourceGroups. * @param options The options parameters. */ private _listAll( options?: NamespacesListAllOptionalParams ): Promise<NamespacesListAllResponse> { return this.client.sendOperationRequest({ options }, listAllOperationSpec); } /** * Gets the authorization rules for a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name * @param options The options parameters. */ private _listAuthorizationRules( resourceGroupName: string, namespaceName: string, options?: NamespacesListAuthorizationRulesOptionalParams ): Promise<NamespacesListAuthorizationRulesResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, options }, listAuthorizationRulesOperationSpec ); } /** * Gets the Primary and Secondary ConnectionStrings to the namespace * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param authorizationRuleName The connection string of the namespace for the specified * authorizationRule. * @param options The options parameters. */ listKeys( resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: NamespacesListKeysOptionalParams ): Promise<NamespacesListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, authorizationRuleName, options }, listKeysOperationSpec ); } /** * Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param authorizationRuleName The connection string of the namespace for the specified * authorizationRule. * @param parameters Parameters supplied to regenerate the Namespace Authorization Rule Key. * @param options The options parameters. */ regenerateKeys( resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: PolicykeyResource, options?: NamespacesRegenerateKeysOptionalParams ): Promise<NamespacesRegenerateKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, authorizationRuleName, parameters, options }, regenerateKeysOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group. If resourceGroupName value is null the * method lists all the namespaces within subscription * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, nextLink: string, options?: NamespacesListNextOptionalParams ): Promise<NamespacesListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listNextOperationSpec ); } /** * ListAllNext * @param nextLink The nextLink from the previous successful call to the ListAll method. * @param options The options parameters. */ private _listAllNext( nextLink: string, options?: NamespacesListAllNextOptionalParams ): Promise<NamespacesListAllNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listAllNextOperationSpec ); } /** * ListAuthorizationRulesNext * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name * @param nextLink The nextLink from the previous successful call to the ListAuthorizationRules method. * @param options The options parameters. */ private _listAuthorizationRulesNext( resourceGroupName: string, namespaceName: string, nextLink: string, options?: NamespacesListAuthorizationRulesNextOptionalParams ): Promise<NamespacesListAuthorizationRulesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, nextLink, options }, listAuthorizationRulesNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const checkAvailabilityOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/checkNamespaceAvailability", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.CheckAvailabilityResult } }, requestBody: Parameters.parameters, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.NamespaceResource }, 201: { bodyMapper: Mappers.NamespaceResource } }, requestBody: Parameters.parameters1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const patchOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.NamespaceResource } }, requestBody: Parameters.parameters2, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {} }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NamespaceResource } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SharedAccessAuthorizationRuleResource } }, requestBody: Parameters.parameters3, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}", httpMethod: "DELETE", responses: { 200: {}, 204: {} }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName ], serializer }; const getAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedAccessAuthorizationRuleResource } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName ], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NamespaceListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const listAllOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/namespaces", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NamespaceListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listAuthorizationRulesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedAccessAuthorizationRuleListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept], serializer }; const listKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/listKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ResourceListKeys } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName ], headerParameters: [Parameters.accept], serializer }; const regenerateKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ResourceListKeys } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NamespaceListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const listAllNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NamespaceListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listAuthorizationRulesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedAccessAuthorizationRuleListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept], serializer };
the_stack
import {getTopicName} from '@/data-quality/utils'; import { ComputedParameter, ConstantParameter, Parameter, ParameterJoint, TopicFactorParameter, VariablePredefineFunctions } from '../tuples/factor-calculator-types'; import {Factor, FactorId} from '../tuples/factor-types'; import { isComputedParameter, isConstantParameter, isExpressionParameter, isJointParameter, isTopicFactorParameter } from '../tuples/parameter-utils'; import { isAlarmAction, isCopyToMemoryAction, isInsertRowAction, isMergeRowAction, isReadTopicAction, isWriteFactorAction, isWriteTopicAction } from '../tuples/pipeline-stage-unit-action/pipeline-stage-unit-action-utils'; import {Pipeline} from '../tuples/pipeline-types'; import {Topic, TopicId} from '../tuples/topic-types'; import {isRawTopic} from '../tuples/topic-utils'; export type FactorsMap = Record<FactorId, Factor>; export type TopicsMap = Record<TopicId, Topic>; export type MappedTopic = { topic: Topic; factors: FactorsMap }; export type MappedTopicsMap = Record<string, MappedTopic>; export type PipelinesMap = Record<string, Pipeline>; export interface RelevantTopic { topic: Topic; factors: Array<Factor>; } export interface PipelineRelation { pipeline: Pipeline; trigger?: RelevantTopic; incoming: Array<RelevantTopic>; outgoing: Array<RelevantTopic>; } export type PipelineRelationMap = Record<string, PipelineRelation> /** * a factor which is treated as used, means it is read somewhere. * some factor even not be written, just defined there only. * * but anyway, raw topic is triggered by api, therefore factors in raw topic is treated as written. */ export type NotUsedFactor = { factor: Factor, written: boolean }; export interface TopicRelation { topic: Topic; trigger: Array<Pipeline>; readMe: Array<Pipeline>; writeMe: Array<Pipeline>; notUsedFactors: Array<NotUsedFactor>; } export type TopicRelationMap = Record<TopicId, TopicRelation>; type UsedFactors = Record<TopicId, Array<FactorId>>; const findOnTopicFactorParameter = (parameter: TopicFactorParameter, result: UsedFactors) => { let factors = result[parameter.topicId]; if (!factors) { factors = []; result[parameter.topicId] = factors; } factors.push(parameter.factorId); }; const findOnComputedParameter = (parameter: ComputedParameter, result: UsedFactors, variables: Array<string>, triggerTopic?: Topic) => { parameter.parameters.forEach(parameter => { if (parameter.conditional && parameter.on) { findOnCondition(parameter.on, result, variables, triggerTopic); } findOnParameter(parameter, result, variables, triggerTopic); }); }; const findOnConstantParameter = (parameter: ConstantParameter, result: UsedFactors, variables: Array<string>, triggerTopic?: Topic) => { // variable in constant can be from trigger topic, variables in memory or predefined syntax // we collect factors of trigger topic only, therefore it is ignored when trigger topic not exists if (!triggerTopic) { return; } const statement = parameter.value?.trim() || ''; if (statement.length === 0) { return; } const segments = statement.match(/([^{]*({[^}]+})?)/g); if (segments == null) { // no variable return; } const matchVariable = (variable: string) => { const index = variable.lastIndexOf('.&'); if (index !== -1) { variable = variable.substring(0, index); } const factor = triggerTopic.factors.find(factor => factor.name === variable); if (factor) { let factors = result[triggerTopic.topicId]; if (!factors) { factors = []; result[triggerTopic.topicId] = factors; } factors.push(factor.factorId); } }; const findVariable = (variable: string) => { if (variable.startsWith(VariablePredefineFunctions.FROM_PREVIOUS_TRIGGER_DATA)) { matchVariable(variable.substring(VariablePredefineFunctions.FROM_PREVIOUS_TRIGGER_DATA.length + 1)); } else if (variables.includes(variable)) { // from memory variables, ignored } else { // from trigger data matchVariable(variable); } }; segments.filter(x => !!x).forEach(segment => { const braceStartIndex = segment.indexOf('{'); if (braceStartIndex === -1) { // do nothing, no variable here } else if (braceStartIndex === 0) { findVariable(segment.substring(1, segment.length - 1).trim()); } else { findVariable(segment.substring(braceStartIndex + 1, segment.length - 1).trim()); } }); }; const findOnParameter = (parameter: Parameter, result: UsedFactors, variables: Array<string>, triggerTopic?: Topic) => { if (!parameter) { return; } if (isTopicFactorParameter(parameter)) { findOnTopicFactorParameter(parameter, result); } else if (isComputedParameter(parameter)) { findOnComputedParameter(parameter, result, variables, triggerTopic); } else if (isConstantParameter(parameter)) { findOnConstantParameter(parameter, result, variables, triggerTopic); } }; const findOnCondition = (condition: ParameterJoint, result: UsedFactors, variables: Array<string>, triggerTopic?: Topic) => { if (!condition) { return; } condition.filters.forEach(sub => { if (isExpressionParameter(sub)) { const {left, right} = sub; findOnParameter(left, result, variables, triggerTopic); findOnParameter(right, result, variables, triggerTopic); } else if (isJointParameter(sub)) { findOnCondition(sub, result, variables, triggerTopic); } }); }; export const buildPipelineRelation = (options: { pipeline: Pipeline; topicsMap: MappedTopicsMap }): PipelineRelation => { const {pipeline, topicsMap} = options; const findFactorsByTrigger = (pipeline: Pipeline, topicsMap: MappedTopicsMap): { topic?: Topic; factorIds: Array<FactorId> } => { const triggerFactorIds: Array<FactorId> = []; const triggerTopic = topicsMap[pipeline.topicId]?.topic; if (triggerTopic) { // obviously, only when trigger topic existed if (pipeline.conditional && pipeline.on) { // no variables are defined now findOnCondition(pipeline.on, {[pipeline.topicId]: triggerFactorIds}, []); } } return {topic: triggerTopic, factorIds: triggerFactorIds}; }; const trigger = findFactorsByTrigger(pipeline, topicsMap); const variables: Array<string> = []; const readFactorIds: UsedFactors = {}; const writeFactorIds: UsedFactors = {}; pipeline.stages.forEach(stage => { if (stage.conditional && stage.on) { findOnCondition(stage.on, readFactorIds, variables, trigger.topic); } stage.units.forEach(unit => { if (unit.conditional && unit.on) { findOnCondition(unit.on, readFactorIds, variables, trigger.topic); } unit.do.forEach(action => { if (isAlarmAction(action) && action.conditional && action.on) { findOnCondition(action.on, readFactorIds, variables, trigger.topic); } else if (isCopyToMemoryAction(action)) { findOnParameter(action.source, readFactorIds, variables, trigger.topic); variables.push(action.variableName?.trim() || ''); } else if (isReadTopicAction(action)) { findOnCondition(action.by, readFactorIds, variables, trigger.topic); variables.push(action.variableName?.trim() || ''); } else if (isWriteTopicAction(action)) { const topicId = action.topicId; let factors = writeFactorIds[topicId]; if (!factors) { factors = []; writeFactorIds[topicId] = factors; } if (isInsertRowAction(action)) { action.mapping.forEach(mapping => { writeFactorIds[topicId].push(mapping.factorId); findOnParameter(mapping.source, readFactorIds, variables, trigger.topic); }); } else if (isWriteFactorAction(action)) { findOnCondition(action.by, readFactorIds, variables, trigger.topic); findOnParameter(action.source, readFactorIds, variables, trigger.topic); writeFactorIds[topicId].push(action.factorId); } else if (isMergeRowAction(action)) { findOnCondition(action.by, readFactorIds, variables, trigger.topic); action.mapping.forEach(mapping => { writeFactorIds[topicId].push(mapping.factorId); findOnParameter(mapping.source, readFactorIds, variables, trigger.topic); }); } } }); }); }); const redressFactors = (factors: UsedFactors, topicFilter: (topicId: TopicId) => boolean) => { return Object.keys(factors) .filter(topicFilter) .map(topicId => { const topic = topicsMap[topicId]; return {topic, factors: [...new Set(factors[topicId].filter(x => !!x))]}; }) .filter(({topic, factors}) => topic != null && factors && factors.length > 0) .sort((x1, x2) => { return getTopicName(x1.topic.topic).toLowerCase().localeCompare(getTopicName(x2.topic.topic)); }).map(item => { const topic = item.topic.topic; return { topic, factors: [...new Set(item.factors)].map(factorId => { const mappedTopic = topicsMap[topic.topicId] as MappedTopic; return mappedTopic?.factors[factorId]; }).filter(x => !!x) as Array<Factor> }; }); }; return { pipeline, trigger: !!trigger.topic ? { topic: trigger.topic, factors: [...new Set([...trigger.factorIds, ...(readFactorIds[pipeline.topicId] || [])])].map(factorId => { const mappedTopic = topicsMap[trigger.topic?.topicId || ''] as MappedTopic; return mappedTopic?.factors[factorId]; }).filter(x => !!x) as Array<Factor> } : (void 0), // eslint-disable-next-line incoming: redressFactors(readFactorIds, topicId => !!(topicId && topicId != pipeline.topicId)), outgoing: redressFactors(writeFactorIds, () => true) }; }; export const buildPipelinesRelation = (pipelines: Array<Pipeline>, topicsMap: MappedTopicsMap): PipelineRelationMap => { return pipelines.reduce((relations, pipeline) => { relations[pipeline.pipelineId] = buildPipelineRelation({pipeline, topicsMap}); return relations; }, {} as PipelineRelationMap); }; export const buildTopicsRelation = (topics: Array<Topic>, pipelineRelations: PipelineRelationMap): TopicRelationMap => { return topics.reduce((relations, topic) => { const part = { topic, trigger: Object.values(pipelineRelations) .filter(relation => relation.trigger?.topic === topic) .map(relation => relation.pipeline), readMe: Object.values(pipelineRelations) .filter(relation => relation.incoming.some(({topic: read}) => read === topic)) .map(relation => relation.pipeline), writeMe: Object.values(pipelineRelations) .filter(relation => relation.outgoing.some(({topic: write}) => write === topic)) .map(relation => relation.pipeline) }; const alwaysWritten = isRawTopic(topic); relations[topic.topicId] = { ...part, notUsedFactors: topic.factors.map(factor => { const read = part.trigger.some(pipeline => { const relation = pipelineRelations[pipeline.pipelineId]; // in trigger or in incoming, means read return relation.trigger?.factors.includes(factor); }) || part.readMe.some(pipeline => { const relation = pipelineRelations[pipeline.pipelineId]; // in trigger or in incoming, means read return relation.incoming.some(({factors}) => factors.includes(factor)); }); // always written or in outgoing const write = alwaysWritten || part.writeMe.some(pipeline => { const relation = pipelineRelations[pipeline.pipelineId]; return relation.outgoing.some(({factors}) => factors.includes(factor)); }); return (!read) ? {factor, written: write} : null; }).filter(x => !!x).sort((x1, x2) => { return (x1?.factor.name.toLowerCase() || '').localeCompare(x2?.factor.name.toLowerCase() || ''); }) as Array<NotUsedFactor> }; return relations; }, {} as TopicRelationMap); }; export const buildTopicsMap = (topics: Array<Topic>): MappedTopicsMap => { return topics.reduce((map, topic) => { map[topic.topicId] = { topic, factors: topic.factors.reduce((map, factor) => { map[factor.factorId] = factor; return map; }, {} as FactorsMap) }; return map; }, {} as MappedTopicsMap); }; export const buildPipelinesMap = (pipelines: Array<Pipeline>): PipelinesMap => { return pipelines.reduce((map, pipeline) => { map[pipeline.pipelineId] = pipeline; return map; }, {} as PipelinesMap); };
the_stack
import * as assert from 'assert'; import * as cp from 'child_process'; import { File } from 'decompress'; import * as fse from 'fs-extra'; import * as glob from 'glob'; import * as gulp from 'gulp'; import * as os from 'os'; import * as path from 'path'; import * as process from 'process'; import * as recursiveReadDir from 'recursive-readdir'; import * as shelljs from 'shelljs'; import { Stream } from 'stream'; import { gulp_webpack } from 'vscode-azureextensiondev'; import { langServerDotnetVersion, languageServerFolderName } from './src/constants'; import { getTempFilePath } from './test/support/getTempFilePath'; import { DEFAULT_TESTCASE_TIMEOUT_MS } from "./test/testConstants"; // tslint:disable:no-require-imports import decompress = require('gulp-decompress'); import download = require('gulp-download'); import rimraf = require('rimraf'); // tslint:enable:no-require-imports const filesAndFoldersToPackage: string[] = [ // NOTE: License.txt and languageServer folder are handled separately so should not be in this list 'dist', 'assets', 'icons', 'AzureRMTools128x128.png', 'CHANGELOG.md', 'main.js', 'NOTICE.html', 'node_modules', // Must be present for vsce package to work, but will be ignored during packaging 'README.md', '.vscodeignore' ]; const env = process.env; // If set, does not delete the staging folder after package (for debugging purposes) const preserveStagingFolder = !!env.ARMTOOLS_PRESERVE_STAGING_FOLDER; // Points to a local folder path to retrieve the language server from when packaging (for packaging private builds) // e.g. (MacOS): "export LANGUAGE_SERVER_PACKAGING_PATH=~/repos/ARM-LanguageServer/artifacts/bin/Microsoft.ArmLanguageServer/Debug/netcoreapp3.1" const languageServerPackagingPath = env.LANGUAGE_SERVER_PACKAGING_PATH; // Official builds will download and include the language server bits (which are licensed differently than the code in the public repo) const languageServerAvailable = !env.DISABLE_LANGUAGE_SERVER && (languageServerPackagingPath || (!!env.LANGSERVER_NUGET_USERNAME && !!env.LANGSERVER_NUGET_PASSWORD)); const publicLicenseFileName = 'LICENSE.md'; const languageServerLicenseFileName = 'License.txt'; const languageServerVersionEnv = 'npm_package_config_ARM_LANGUAGE_SERVER_NUGET_VERSION'; // Set the value in package.json's config section const languageServerVersion = env[languageServerVersionEnv]; const languageServerNugetPackage = 'Microsoft.ArmLanguageServer'; const jsonArmGrammarSourcePath: string = path.resolve('grammars', 'JSONC.arm.tmLanguage.json'); const jsonArmGrammarDestPath: string = path.resolve('dist', 'grammars', 'JSONC.arm.tmLanguage.json'); const tleGrammarSourcePath: string = path.resolve('grammars', 'arm-expression-string.tmLanguage.json'); const tleGrammarBuiltPath: string = path.resolve('dist', 'grammars', 'arm-expression-string.tmLanguage.json'); const armConfigurationSourcePath: string = path.resolve('grammars', 'jsonc.arm.language-configuration.json'); const armConfigurationDestPath: string = path.resolve('dist', 'grammars', 'jsonc.arm.language-configuration.json'); interface IGrammar { preprocess?: { "builtin-functions": string; [key: string]: string; }; [key: string]: unknown; } interface IExpressionMetadata { functionSignatures: { name: string; }[]; } function test(): cp.ChildProcess { env.DEBUGTELEMETRY = 'verbose'; env.CODE_TESTS_PATH = path.join(__dirname, 'dist/test'); // This is the timeout for individual tests env.MOCHA_timeout = String(DEFAULT_TESTCASE_TIMEOUT_MS); env.MOCHA_enableTimeouts = "1"; env.MOCHA_grep = ""; //env.ALWAYS_ECHO_TEST_LOG = "1"; return cp.spawn('node', ['./node_modules/vscode/bin/test'], { stdio: 'inherit', env }); } function buildTLEGrammar(): void { const sourceGrammar: string = fse.readFileSync(tleGrammarSourcePath).toString(); let grammar: string = sourceGrammar; const expressionMetadataPath: string = path.resolve("assets/ExpressionMetadata.json"); const expressionMetadata = <IExpressionMetadata>JSON.parse(fse.readFileSync(expressionMetadataPath).toString()); // Add list of built-in functions from our metadata and place at beginning of grammar's preprocess section let builtinFunctions: string[] = expressionMetadata.functionSignatures.map(sig => sig.name); let grammarAsObject = <IGrammar>JSON.parse(grammar); grammarAsObject.preprocess = { "builtin-functions": `(?:(?i)${builtinFunctions.join('|')})`, // tslint:disable-next-line: strict-boolean-expressions ... (grammarAsObject.preprocess || {}) }; grammarAsObject = { $comment: `DO NOT EDIT - This file was built from ${path.relative(__dirname, tleGrammarSourcePath)}`, ...grammarAsObject }; grammar = JSON.stringify(grammarAsObject, null, 4); // Get the replacement keys from the preprocess section (ignore those that start with "$") const replacementKeys = Object.getOwnPropertyNames((<IGrammar>JSON.parse(grammar)).preprocess).filter(key => !key.startsWith("$")); // Build grammar: Make replacements specified for (let key of replacementKeys) { let replacementKey = `{{${key}}}`; // Re-read value from current grammar contents because the replacement value might contain replacements, too let value = JSON.parse(grammar).preprocess[key]; let valueString = JSON.stringify(value); // remove quotes valueString = valueString.slice(1, valueString.length - 1); if (!sourceGrammar.includes(replacementKey)) { console.log(`WARNING: Preprocess key ${replacementKey} is never referenced in ${tleGrammarSourcePath}`); } grammar = grammar.replace(new RegExp(replacementKey, "g"), valueString); } // Remove preprocess section from the output grammar file let outputGrammarAsObject = (<IGrammar>JSON.parse(grammar)); delete outputGrammarAsObject.preprocess; grammar = JSON.stringify(outputGrammarAsObject, null, 4); fse.writeFileSync(tleGrammarBuiltPath, grammar); console.log(`Built ${tleGrammarBuiltPath}`); if (grammar.includes('{{')) { throw new Error("At least one replacement key could not be found in the grammar - '{{' was found in the final file"); } } async function buildGrammars(): Promise<void> { fse.ensureDirSync('dist'); fse.ensureDirSync('dist/grammars'); buildTLEGrammar(); fse.copyFileSync(jsonArmGrammarSourcePath, jsonArmGrammarDestPath); console.log(`Copied ${jsonArmGrammarDestPath}`); fse.copyFileSync(armConfigurationSourcePath, armConfigurationDestPath); console.log(`Copied ${armConfigurationDestPath}`); } function executeInShell(command: string): void { console.log(command); const result = shelljs.exec(command); console.log(result.stdout); console.log(result.stderr); if (result.code !== 0) { throw new Error(`Error executing ${command}`); } } async function getLanguageServer(): Promise<void> { if (languageServerAvailable) { const pkgsPath = path.join(__dirname, 'pkgs'); const destPath = path.join(__dirname, languageServerFolderName); console.log(`Retrieving language server ${languageServerNugetPackage}@${languageServerVersion}`); // Create temporary config file with credentials const config = fse.readFileSync(path.join(__dirname, 'NuGet.Config')).toString(); const withCreds = config. // tslint:disable-next-line: strict-boolean-expressions replace('$LANGSERVER_NUGET_USERNAME', env.LANGSERVER_NUGET_USERNAME || ''). // tslint:disable-next-line: strict-boolean-expressions replace('$LANGSERVER_NUGET_PASSWORD', env.LANGSERVER_NUGET_PASSWORD || ''); const configPath = getTempFilePath('nuget', '.config'); fse.writeFileSync(configPath, withCreds); // Nuget install to pkgs folder let app = 'nuget'; const args = [ 'install', languageServerNugetPackage, '-Version', languageServerVersion, '-Framework', `netcoreapp${langServerDotnetVersion}`, '-OutputDirectory', 'pkgs', //'-Verbosity', 'detailed', '-ExcludeVersion', // Keeps the package version from being included in the output folder name '-NonInteractive', '-ConfigFile', configPath ]; if (os.platform() === 'linux') { app = 'mono'; args.unshift('nuget.exe'); } const command = `${app} ${args.join(' ')}`; executeInShell(command); fse.unlinkSync(configPath); // Copy binaries and license into dist\languageServer console.log(`Removing ${languageServerFolderName}`); rimraf.sync(languageServerFolderName); console.log(`Copying language server binaries to ${languageServerFolderName}`); const langServerSourcePath = path.join(pkgsPath, languageServerNugetPackage, 'lib', `netcoreapp${langServerDotnetVersion}`); const licenseSourcePath = path.join(pkgsPath, languageServerNugetPackage, languageServerLicenseFileName); fse.mkdirpSync(destPath); copyFolder(langServerSourcePath, destPath); const licenseDest = path.join(languageServerFolderName, languageServerLicenseFileName); console.log(`Copying language server license ${licenseSourcePath} to ${licenseDest}`); fse.copyFileSync(licenseSourcePath, licenseDest); console.log(`Language server binaries and license are in ${languageServerFolderName}`); } else { console.warn(`Language server not available, skipping packaging of language server binaries.`); } } function copyFolder(sourceFolder: string, destFolder: string, sourceRoot: string = sourceFolder): void { fse.ensureDirSync(destFolder); fse.readdirSync(sourceFolder).forEach(fn => { let src = path.join(sourceFolder, fn); let dest = path.join(destFolder, fn); if (fse.statSync(src).isFile()) { // console.log(`Copying file ${src} to ${dest}`); fse.copyFileSync(src, dest); } else if (fse.statSync(src).isDirectory()) { copyFolder(src, dest, sourceRoot); } else { assert("Unexpected path type"); } }); } async function packageVsix(): Promise<void> { // We use a staging folder so we have more control over exactly what goes into the .vsix function copyToStagingFolder(relativeOrAbsSource: string, relativeDest: string): void { const absSource = path.resolve(__dirname, relativeOrAbsSource); const absDest = path.join(stagingFolder, relativeDest); if (fse.statSync(absSource).isDirectory()) { console.log(`Copying folder ${absSource} to staging folder`); copyFolder(absSource, absDest); } else { console.log(`Copying file ${absSource} to staging folder`); fse.copyFileSync(absSource, absDest); } } let stagingFolder = getTempFilePath('staging', ''); console.log(`Staging folder: ${stagingFolder}`); fse.mkdirpSync(stagingFolder); // Copy files/folders to staging for (let p of filesAndFoldersToPackage) { copyToStagingFolder(p, p); } let filesInStaging = fse.readdirSync(stagingFolder); filesInStaging.forEach(fn => assert(!/license/i.test(fn), `Should not have copied the original license file into staging: ${fn}`)); let expectedLicenseFileName: string; if (languageServerAvailable) { let languageServerSourcePath: string; let licenseSourcePath: string; if (languageServerPackagingPath) { console.warn(`========== WARNING ==========: Packaging language server from local path instead of NuGet location`); languageServerSourcePath = languageServerPackagingPath; licenseSourcePath = path.join(languageServerPackagingPath, '../../../../..', languageServerLicenseFileName); } else { languageServerSourcePath = path.join(__dirname, languageServerFolderName); licenseSourcePath = path.join(__dirname, languageServerFolderName, languageServerLicenseFileName); } console.warn(` Language server source path: ${languageServerSourcePath}`); console.warn(` License source path: ${licenseSourcePath}`); // Copy language server bits copyToStagingFolder(languageServerSourcePath, languageServerFolderName); // Copy license to staging main folder copyToStagingFolder(licenseSourcePath, languageServerLicenseFileName); expectedLicenseFileName = languageServerLicenseFileName; } else { // No language server available - jusy copy license.md to staging main folder copyToStagingFolder(publicLicenseFileName, languageServerFolderName); expectedLicenseFileName = publicLicenseFileName; } // Copy package.json to staging let packageContents = fse.readJsonSync(path.join(__dirname, 'package.json')); assert(packageContents.license, "package.json doesn't contain a license field?"); // ... modify package.json to point to language server license packageContents.license = `SEE LICENSE IN ${expectedLicenseFileName}`; // ... remove vscode:prepublish script from package, since everything's already built delete packageContents.scripts['vscode:prepublish']; fse.writeFileSync(path.join(stagingFolder, 'package.json'), JSON.stringify(packageContents, null, 2)); assert(fse.readFileSync(path.join(stagingFolder, 'package.json')).toString().includes(`"license": "SEE LICENSE IN ${expectedLicenseFileName}"`), "Language server license not correctly installed into staged package.json"); try { console.log(`Running vsce package in staging folder ${stagingFolder}`); shelljs.cd(stagingFolder); executeInShell('vsce package --githubBranch main'); } finally { shelljs.cd(__dirname); } // Copy vsix to current folder let vsixName = fse.readdirSync(stagingFolder).find(fn => /\.vsix$/.test(fn)); if (!vsixName) { throw new Error("Couldn't find a .vsix file"); } let vsixDestPath = path.join(__dirname, vsixName); if (!languageServerAvailable) { vsixDestPath = vsixDestPath.replace('.vsix', '-no-languageserver.vsix'); } if (fse.existsSync(vsixDestPath)) { fse.unlinkSync(vsixDestPath); } fse.copyFileSync(path.join(stagingFolder, vsixName), vsixDestPath); // Remove staging folder since packaging was a success if (!preserveStagingFolder) { rimraf.sync(stagingFolder); } console.log(`Packaged successfully to ${vsixDestPath}`); } // When webpacked, the tests cannot touch any code under src/, or it will end up getting loaded // twice (because it's also in the bundle), which causes problems with objects that are supposed to // be singletons. The test errors are somewhat mysterious, so verify that condition here during build. async function verifyTestsReferenceOnlyExtensionBundle(testFolder: string): Promise<void> { const errors: string[] = []; for (let filePath of await recursiveReadDir(testFolder)) { await verifyFile(filePath); } async function verifyFile(file: string): Promise<void> { const regex = /import .*['"]\.\.\/(\.\.\/)?src\/.*['"]/mg; if (path.extname(file) === ".ts") { const contents: string = (await fse.readFile(file)).toString(); const matches = contents.match(regex); if (matches) { for (let match of matches) { if (!match.includes('.shared.ts')) { errors.push( os.EOL + `${path.relative(__dirname, file)}: error: Test code may not import from the src folder, it should import from '../extension.bundle'${os.EOL}` + ` Error is here: ===> ${match}${os.EOL}` ); console.error(match); } } } } } if (errors.length > 0) { throw new Error(errors.join("\n")); } } export function gulp_installDotNetExtension(): Promise<void> | Stream { const extensionName = '.NET Install Tool for Extension Authors'; console.log(`Installing ${extensionName}`); const version: string = '0.1.0'; const extensionPath: string = path.join(os.homedir(), `.vscode/extensions/ms-dotnettools.vscode-dotnet-runtime-${version}`); console.log(extensionPath); const existingExtensions: string[] = glob.sync(extensionPath.replace(version, '*')); if (existingExtensions.length === 0) { // tslint:disable-next-line:no-http-string return download(`http://ms-vscode.gallery.vsassets.io/_apis/public/gallery/publisher/ms-dotnettools/extension/vscode-dotnet-runtime/${version}/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage`) .pipe(decompress({ filter: (file: File): boolean => file.path.startsWith('extension/'), map: (file: File): File => { file.path = file.path.slice(10); return file; } })) .pipe(gulp.dest(extensionPath)); } else { console.log(`${extensionName} already installed.`); // We need to signal to gulp that we've completed this async task return Promise.resolve(); } } exports['webpack-dev'] = gulp.series(() => gulp_webpack('development'), buildGrammars); exports['webpack-prod'] = gulp.series(() => gulp_webpack('production'), buildGrammars); exports.test = gulp.series(gulp_installDotNetExtension, test); exports['build-grammars'] = buildGrammars; exports['watch-grammars'] = (): unknown => gulp.watch('grammars/**', buildGrammars); exports['get-language-server'] = getLanguageServer; exports.package = packageVsix; exports['error-vsce-package'] = (): never => { throw new Error(`Please do not run vsce package, instead use 'npm run package`); }; exports['verify-test-uses-extension-bundle'] = (): Promise<void> => verifyTestsReferenceOnlyExtensionBundle(path.resolve("test"));
the_stack
import * as DOM from 'vs/base/browser/dom'; import * as nls from 'vs/nls'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { DiffElementViewModelBase, SideBySideDiffElementViewModel } from 'vs/workbench/contrib/notebook/browser/diff/diffElementViewModel'; import { DiffSide, INotebookTextDiffEditor } from 'vs/workbench/contrib/notebook/browser/diff/notebookDiffEditorBrowser'; import { ICellOutputViewModel, IInsetRenderOutput, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { NotebookCellOutputsSplice } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { DiffNestedCellViewModel } from 'vs/workbench/contrib/notebook/browser/diff/diffNestedCellViewModel'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; interface IMimeTypeRenderer extends IQuickPickItem { index: number; } export class OutputElement extends Disposable { readonly resizeListener = this._register(new DisposableStore()); domNode!: HTMLElement; renderResult?: IInsetRenderOutput; constructor( private _notebookEditor: INotebookTextDiffEditor, private _notebookTextModel: NotebookTextModel, private _notebookService: INotebookService, private _quickInputService: IQuickInputService, private _diffElementViewModel: DiffElementViewModelBase, private _diffSide: DiffSide, private _nestedCell: DiffNestedCellViewModel, private _outputContainer: HTMLElement, readonly output: ICellOutputViewModel ) { super(); } render(index: number, beforeElement?: HTMLElement) { const outputItemDiv = document.createElement('div'); let result: IInsetRenderOutput | undefined = undefined; const [mimeTypes, pick] = this.output.resolveMimeTypes(this._notebookTextModel, undefined); const pickedMimeTypeRenderer = mimeTypes[pick]; if (mimeTypes.length > 1) { outputItemDiv.style.position = 'relative'; const mimeTypePicker = DOM.$('.multi-mimetype-output'); mimeTypePicker.classList.add(...ThemeIcon.asClassNameArray(mimetypeIcon)); mimeTypePicker.tabIndex = 0; mimeTypePicker.title = nls.localize('mimeTypePicker', "Choose a different output mimetype, available mimetypes: {0}", mimeTypes.map(mimeType => mimeType.mimeType).join(', ')); outputItemDiv.appendChild(mimeTypePicker); this.resizeListener.add(DOM.addStandardDisposableListener(mimeTypePicker, 'mousedown', async e => { if (e.leftButton) { e.preventDefault(); e.stopPropagation(); await this.pickActiveMimeTypeRenderer(this._notebookTextModel, this.output); } })); this.resizeListener.add((DOM.addDisposableListener(mimeTypePicker, DOM.EventType.KEY_DOWN, async e => { const event = new StandardKeyboardEvent(e); if ((event.equals(KeyCode.Enter) || event.equals(KeyCode.Space))) { e.preventDefault(); e.stopPropagation(); await this.pickActiveMimeTypeRenderer(this._notebookTextModel, this.output); } }))); } const innerContainer = DOM.$('.output-inner-container'); DOM.append(outputItemDiv, innerContainer); if (mimeTypes.length !== 0) { const renderer = this._notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId); result = renderer ? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType } : this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType); this.output.pickedMimeType = pickedMimeTypeRenderer; } this.domNode = outputItemDiv; this.renderResult = result; if (!result) { // this.viewCell.updateOutputHeight(index, 0); return; } if (beforeElement) { this._outputContainer.insertBefore(outputItemDiv, beforeElement); } else { this._outputContainer.appendChild(outputItemDiv); } this._notebookEditor.createOutput( this._diffElementViewModel, this._nestedCell, result, () => this.getOutputOffsetInCell(index), this._diffElementViewModel instanceof SideBySideDiffElementViewModel ? this._diffSide : this._diffElementViewModel.type === 'insert' ? DiffSide.Modified : DiffSide.Original ); } private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput { if (!viewModel.model.outputs.length) { return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output")); } if (!preferredMimeType) { const mimeTypes = viewModel.model.outputs.map(op => op.mime); const mimeTypesMessage = mimeTypes.join(', '); return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage)); } return this._renderSearchForMimetype(viewModel, preferredMimeType); } private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput { const query = `@tag:notebookRenderer ${mimeType}`; return { type: RenderOutputType.Html, source: viewModel, htmlContent: `<p>No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.</p> <a href="command:workbench.extensions.search?%22${query}%22" class="monaco-button monaco-text-button" tabindex="0" role="button" style="padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;">Search Marketplace</a>` }; } private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput { return { type: RenderOutputType.Html, source: viewModel, htmlContent: `<p>${message}</p>` }; } private async pickActiveMimeTypeRenderer(notebookTextModel: NotebookTextModel, viewModel: ICellOutputViewModel) { const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, undefined); const items = mimeTypes.filter(mimeType => mimeType.isTrusted).map((mimeType, index): IMimeTypeRenderer => ({ label: mimeType.mimeType, id: mimeType.mimeType, index: index, picked: index === currIndex, detail: this.generateRendererInfo(mimeType.rendererId), description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined })); const picker = this._quickInputService.createQuickPick(); picker.items = items; picker.activeItems = items.filter(item => !!item.picked); picker.placeholder = items.length !== mimeTypes.length ? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output. Rich mimetypes are available only when the notebook is trusted") : nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output"); const pick = await new Promise<number | undefined>(resolve => { picker.onDidAccept(() => { resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer).index : undefined); picker.dispose(); }); picker.show(); }); if (pick === undefined) { return; } if (pick !== currIndex) { // user chooses another mimetype const index = this._nestedCell.outputsViewModels.indexOf(viewModel); const nextElement = this.domNode.nextElementSibling; this.resizeListener.clear(); const element = this.domNode; if (element) { element.parentElement?.removeChild(element); this._notebookEditor.removeInset( this._diffElementViewModel, this._nestedCell, viewModel, this._diffSide ); } viewModel.pickedMimeType = mimeTypes[pick]; this.render(index, nextElement as HTMLElement); } } private generateRendererInfo(renderId: string): string { const renderInfo = this._notebookService.getRendererInfo(renderId); if (renderInfo) { const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id; return `${displayName} (${renderInfo.extensionId.value})`; } return nls.localize('builtinRenderInfo', "built-in"); } getCellOutputCurrentIndex() { return this._diffElementViewModel.getNestedCellViewModel(this._diffSide).outputs.indexOf(this.output.model); } updateHeight(index: number, height: number) { this._diffElementViewModel.updateOutputHeight(this._diffSide, index, height); } getOutputOffsetInContainer(index: number) { return this._diffElementViewModel.getOutputOffsetInContainer(this._diffSide, index); } getOutputOffsetInCell(index: number) { return this._diffElementViewModel.getOutputOffsetInCell(this._diffSide, index); } } export class OutputContainer extends Disposable { private _outputEntries = new Map<ICellOutputViewModel, OutputElement>(); constructor( private _editor: INotebookTextDiffEditor, private _notebookTextModel: NotebookTextModel, private _diffElementViewModel: DiffElementViewModelBase, private _nestedCellViewModel: DiffNestedCellViewModel, private _diffSide: DiffSide, private _outputContainer: HTMLElement, @INotebookService private _notebookService: INotebookService, @IQuickInputService private readonly _quickInputService: IQuickInputService, @IOpenerService readonly _openerService: IOpenerService ) { super(); this._register(this._diffElementViewModel.onDidLayoutChange(() => { this._outputEntries.forEach((value, key) => { const index = _nestedCellViewModel.outputs.indexOf(key.model); if (index >= 0) { const top = this._diffElementViewModel.getOutputOffsetInContainer(this._diffSide, index); value.domNode.style.top = `${top}px`; } }); })); this._register(this._nestedCellViewModel.textModel.onDidChangeOutputs(splice => { this._updateOutputs(splice); })); } private _updateOutputs(splice: NotebookCellOutputsSplice) { const removedKeys: ICellOutputViewModel[] = []; this._outputEntries.forEach((value, key) => { if (this._nestedCellViewModel.outputsViewModels.indexOf(key) < 0) { // already removed removedKeys.push(key); // remove element from DOM this._outputContainer.removeChild(value.domNode); this._editor.removeInset(this._diffElementViewModel, this._nestedCellViewModel, key, this._diffSide); } }); removedKeys.forEach(key => { this._outputEntries.get(key)?.dispose(); this._outputEntries.delete(key); }); let prevElement: HTMLElement | undefined = undefined; const outputsToRender = this._nestedCellViewModel.outputsViewModels; outputsToRender.reverse().forEach(output => { if (this._outputEntries.has(output)) { // already exist prevElement = this._outputEntries.get(output)!.domNode; return; } // newly added element const currIndex = this._nestedCellViewModel.outputsViewModels.indexOf(output); this._renderOutput(output, currIndex, prevElement); prevElement = this._outputEntries.get(output)?.domNode; }); } render() { // TODO, outputs to render (should have a limit) for (let index = 0; index < this._nestedCellViewModel.outputsViewModels.length; index++) { const currOutput = this._nestedCellViewModel.outputsViewModels[index]; // always add to the end this._renderOutput(currOutput, index, undefined); } } showOutputs() { for (let index = 0; index < this._nestedCellViewModel.outputsViewModels.length; index++) { const currOutput = this._nestedCellViewModel.outputsViewModels[index]; // always add to the end this._editor.showInset(this._diffElementViewModel, currOutput.cellViewModel, currOutput, this._diffSide); } } hideOutputs() { this._outputEntries.forEach((outputElement, cellOutputViewModel) => { this._editor.hideInset(this._diffElementViewModel, this._nestedCellViewModel, cellOutputViewModel); }); } private _renderOutput(currOutput: ICellOutputViewModel, index: number, beforeElement?: HTMLElement) { if (!this._outputEntries.has(currOutput)) { this._outputEntries.set(currOutput, new OutputElement(this._editor, this._notebookTextModel, this._notebookService, this._quickInputService, this._diffElementViewModel, this._diffSide, this._nestedCellViewModel, this._outputContainer, currOutput)); } const renderElement = this._outputEntries.get(currOutput)!; renderElement.render(index, beforeElement); } }
the_stack
import type { Location } from "history"; import { parsePath } from "history"; import type { AssetsManifest } from "./entry"; import type { ClientRoute } from "./routes"; import type { RouteMatch } from "./routeMatching"; // import { matchClientRoutes } from "./routeMatching"; import type { RouteModules, RouteModule } from "./routeModules"; import { loadRouteModule } from "./routeModules"; type Primitive = null | undefined | string | number | boolean | symbol | bigint; type LiteralUnion<LiteralType, BaseType extends Primitive> = | LiteralType | (BaseType & Record<never, never>); /** * Represents a `<link>` element. * * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element */ export interface HtmlLinkDescriptor { /** * Address of the hyperlink */ href: string; /** * How the element handles crossorigin requests */ crossOrigin?: "anonymous" | "use-credentials"; /** * Relationship between the document containing the hyperlink and the destination resource */ rel: LiteralUnion< | "alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string >; /** * Applicable media: "screen", "print", "(max-width: 764px)" */ media?: string; /** * Integrity metadata used in Subresource Integrity checks */ integrity?: string; /** * Language of the linked resource */ hrefLang?: string; /** * Hint for the type of the referenced resource */ type?: string; /** * Referrer policy for fetches initiated by the element */ referrerPolicy?: | "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; /** * Sizes of the icons (for rel="icon") */ sizes?: string; /** * Images to use in different situations, e.g., high-resolution displays, small monitors, etc. (for rel="preload") */ imagesrcset?: string; /** * Image sizes for different page layouts (for rel="preload") */ imagesizes?: string; /** * Potential destination for a preload request (for rel="preload" and rel="modulepreload") */ as?: LiteralUnion< | "audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string >; /** * Color to use when customizing a site's icon (for rel="mask-icon") */ color?: string; /** * Whether the link is disabled */ disabled?: boolean; /** * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name. */ title?: string; } export interface PrefetchPageDescriptor extends Omit< HtmlLinkDescriptor, | "href" | "rel" | "type" | "sizes" | "imagesrcset" | "imagesizes" | "as" | "color" | "title" > { /** * The absolute path of the page to prefetch. */ page: string; } export type LinkDescriptor = HtmlLinkDescriptor | PrefetchPageDescriptor; //////////////////////////////////////////////////////////////////////////////// /** * Gets all the links for a set of matches. The modules are assumed to have been * loaded already. */ export function getLinksForMatches( matches: RouteMatch<ClientRoute>[], routeModules: RouteModules, manifest: AssetsManifest ): LinkDescriptor[] { let descriptors = matches .map((match): LinkDescriptor[] => { let module = routeModules[match.route.id]; return module.links?.() || []; }) .flat(1); let preloads = getCurrentPageModulePreloadHrefs(matches, manifest); return dedupe(descriptors, preloads); } export async function prefetchStyleLinks( routeModule: RouteModule ): Promise<void> { if (!routeModule.links) return; let descriptors = routeModule.links(); if (!descriptors) return; let styleLinks = []; for (let descriptor of descriptors) { if (!isPageLinkDescriptor(descriptor) && descriptor.rel === "stylesheet") { styleLinks.push({ ...descriptor, rel: "preload", as: "style" }); } } // don't block for non-matching media queries let matchingLinks = styleLinks.filter( (link) => !link.media || window.matchMedia(link.media).matches ); await Promise.all(matchingLinks.map(prefetchStyleLink)); } async function prefetchStyleLink( descriptor: HtmlLinkDescriptor ): Promise<void> { return new Promise((resolve) => { let link = document.createElement("link"); Object.assign(link, descriptor); function removeLink() { // if a navigation interrupts this prefetch React will update the <head> // and remove the link we put in there manually, so we check if it's still // there before trying to remove it if (document.head.contains(link)) { document.head.removeChild(link); } } link.onload = () => { removeLink(); resolve(); }; link.onerror = () => { removeLink(); resolve(); }; document.head.appendChild(link); }); } //////////////////////////////////////////////////////////////////////////////// export function isPageLinkDescriptor( object: any ): object is PrefetchPageDescriptor { return object != null && typeof object.page === "string"; } export function isHtmlLinkDescriptor( object: any ): object is HtmlLinkDescriptor { return ( object != null && typeof object.rel === "string" && typeof object.href === "string" ); } export async function getStylesheetPrefetchLinks( matches: RouteMatch<ClientRoute>[], routeModules: RouteModules ) { let links = await Promise.all( matches.map(async (match) => { let mod = await loadRouteModule(match.route, routeModules); return mod.links ? mod.links() : []; }) ); return links .flat(1) .filter(isHtmlLinkDescriptor) .filter((link) => link.rel === "stylesheet" || link.rel === "preload") .map(({ rel, ...attrs }) => rel === "preload" ? { rel: "prefetch", ...attrs } : { rel: "prefetch", as: "style", ...attrs } ); } // This is ridiculously identical to transition.ts `filterMatchesToLoad` export function getNewMatchesForLinks( page: string, nextMatches: RouteMatch<ClientRoute>[], currentMatches: RouteMatch<ClientRoute>[], location: Location, mode: "data" | "assets" ): RouteMatch<ClientRoute>[] { let path = parsePathPatch(page); let isNew = (match: RouteMatch<ClientRoute>, index: number) => { if (!currentMatches[index]) return true; return match.route.id !== currentMatches[index].route.id; }; let matchPathChanged = (match: RouteMatch<ClientRoute>, index: number) => { return ( // param change, /users/123 -> /users/456 currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path // e.g. /files/images/avatar.jpg -> files/finances.xls (currentMatches[index].route.path?.endsWith("*") && currentMatches[index].params["*"] !== match.params["*"]) ); }; // NOTE: keep this mostly up-to-date w/ the transition data diff, but this // version doesn't care about submissions let newMatches = mode === "data" && location.search !== path.search ? // this is really similar to stuff in transition.ts, maybe somebody smarter // than me (or in less of a hurry) can share some of it. You're the best. nextMatches.filter((match, index) => { if (!match.route.hasLoader) { return false; } if (isNew(match, index) || matchPathChanged(match, index)) { return true; } if (match.route.shouldReload) { return match.route.shouldReload({ params: match.params, prevUrl: new URL( location.pathname + location.search + location.hash, window.origin ), url: new URL(page, window.origin), }); } return true; }) : nextMatches.filter((match, index) => { return ( (mode === "assets" || match.route.hasLoader) && (isNew(match, index) || matchPathChanged(match, index)) ); }); return newMatches; } export function getDataLinkHrefs( page: string, matches: RouteMatch<ClientRoute>[], manifest: AssetsManifest ): string[] { let path = parsePathPatch(page); return dedupeHrefs( matches .filter((match) => manifest.routes[match.route.id].hasLoader) .map((match) => { let { pathname, search } = path; let searchParams = new URLSearchParams(search); searchParams.set("_data", match.route.id); return `${pathname}?${searchParams}`; }) ); } export function getModuleLinkHrefs( matches: RouteMatch<ClientRoute>[], manifestPatch: AssetsManifest ): string[] { return dedupeHrefs( matches .map((match) => { let route = manifestPatch.routes[match.route.id]; let hrefs = [route.module]; if (route.imports) { hrefs = hrefs.concat(route.imports); } return hrefs; }) .flat(1) ); } // The `<Script>` will render rel=modulepreload for the current page, we don't // need to include them in a page prefetch, this gives us the list to remove // while deduping. function getCurrentPageModulePreloadHrefs( matches: RouteMatch<ClientRoute>[], manifest: AssetsManifest ): string[] { return dedupeHrefs( matches .map((match) => { let route = manifest.routes[match.route.id]; let hrefs = [route.module]; if (route.imports) { hrefs = hrefs.concat(route.imports); } return hrefs; }) .flat(1) ); } function dedupeHrefs(hrefs: string[]): string[] { return [...new Set(hrefs)]; } export function dedupe(descriptors: LinkDescriptor[], preloads: string[]) { let set = new Set(); let preloadsSet = new Set(preloads); return descriptors.reduce((deduped, descriptor) => { let alreadyModulePreload = !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href); if (alreadyModulePreload) { return deduped; } let str = JSON.stringify(descriptor); if (!set.has(str)) { set.add(str); deduped.push(descriptor); } return deduped; }, [] as LinkDescriptor[]); } // https://github.com/remix-run/history/issues/897 function parsePathPatch(href: string) { let path = parsePath(href); if (path.search === undefined) path.search = ""; return path; }
the_stack
import type {BrowserObject} from 'webdriverio' import {createStore, createEvent, combine, sample} from 'effector' import {using, h, spec, text, list, rec, remap} from 'forest' import {Leaf} from '../index.h' // let addGlobals: Function declare const act: (cb?: () => any) => Promise<void> declare const initBrowser: () => Promise<void> declare const el: HTMLElement // let execFun: <T>(cb: (() => Promise<T> | T) | string) => Promise<T> // let readHTML: () => string declare const browser: BrowserObject declare const exec: (cb: () => any) => Promise<string[]> declare const execFunc: <T>(cb: () => Promise<T>) => Promise<T> beforeEach(async () => { await initBrowser() }, 10e3) test('rec visible support', async () => { const [s1, s2, s3] = await exec(async () => { const toggleNestedRows = createEvent() const nestedRowsVisible = createStore(true).on( toggleNestedRows, visible => !visible, ) type Item = { value: string child: Item[] } type FlatItem = { value: string child: string[] } const items = createStore([ { value: 'a', child: [ { value: 'a_a', child: [], }, { value: 'a_b', child: [ { value: 'a_b_a', child: [], }, ], }, ], }, { value: 'b', child: [ { value: 'b_a', child: [], }, { value: 'b_b', child: [], }, ], }, ]) const flatItems = items.map(list => { const result = [] as FlatItem[] list.forEach(processValue) function processValue({value, child}: Item) { result.push({value, child: child.map(({value}) => value)}) child.forEach(processValue) } return result }) const topLevelFlatItems = flatItems.map(list => list .filter(({value}) => value.length === 1) .map(item => ({item, level: 0})), ) let rootLeaf: Leaf //@ts-expect-error using(el, { fn() { const Row = rec<{item: FlatItem; level: number}>(({store}) => { const [level, item] = remap(store, ['level', 'item'] as const) const visible = combine( level, nestedRowsVisible, (level, visible) => { if (level === 0) return true return visible }, ) const childs = combine( flatItems, item, level, (list, {child}, level) => list .filter(({value}) => child.includes(value)) .map(item => ({item, level: level + 1})), ) h('div', { // style: {marginLeft: '1em'}, visible, fn() { spec({text: [remap(item, 'value'), ' ', level]}) list(childs, ({store}) => { Row({store}) }) }, }) }) list(topLevelFlatItems, ({store}) => { Row({store}) }) }, onRoot({leaf}: {leaf: Leaf}) { rootLeaf = leaf }, }) await act() // printLeaf(rootLeaf) await act(() => { toggleNestedRows() }) await act(() => { toggleNestedRows() }) // printLeaf(rootLeaf) }) expect(s1).toMatchInlineSnapshot(` " <div> a 0 <div>a_a 1</div> <div> a_b 1 <div>a_b_a 2</div> </div> </div> <div> b 0 <div>b_a 1</div> <div>b_b 1</div> </div> " `) expect(s2).toMatchInlineSnapshot(` " <div>a 0</div> <div>b 0</div> " `) expect(s3).toBe(s1) }) test('rec style update support', async () => { const [s1, s2, s3] = await exec(async () => { const toggleNestedRows = createEvent() const nestedRowsVisible = createStore(true).on( toggleNestedRows, visible => !visible, ) type Item = { value: string child: Item[] } type FlatItem = { value: string child: string[] } const items = createStore([ { value: 'a', child: [ { value: 'a_a', child: [], }, { value: 'a_b', child: [ { value: 'a_b_a', child: [], }, ], }, ], }, { value: 'b', child: [ { value: 'b_a', child: [], }, { value: 'b_b', child: [], }, ], }, ]) const flatItems = items.map(list => { const result = [] as FlatItem[] list.forEach(processValue) function processValue({value, child}: Item) { result.push({value, child: child.map(({value}) => value)}) child.forEach(processValue) } return result }) const topLevelFlatItems = flatItems.map(list => list .filter(({value}) => value.length === 1) .map(item => ({item, level: 0})), ) let rootLeaf: Leaf //@ts-expect-error using(el, { fn() { const Row = rec<{item: FlatItem; level: number}>(({store}) => { const [level, item] = remap(store, ['level', 'item'] as const) const visible = combine( level, nestedRowsVisible, (level, visible): string => { if (level === 0) return 'yes' return visible ? 'yes' : 'no' }, ) h('div', { style: {marginLeft: level.map(value => `${value}em`)}, data: {visible}, fn() { const value = remap(item, 'value') const status = visible.map( vis => (vis === 'yes' ? 'visible' : 'hidden') as string, ) text`${value} ${level} ${status}` }, }) const childs = combine( flatItems, store, (list, {item: {child}, level}) => list .filter(({value}) => child.includes(value)) .map(item => ({item, level: level + 1})), ) list(childs, ({store}) => { Row({store}) }) }) list(topLevelFlatItems, ({store}) => { Row({store}) }) }, onRoot({leaf}: {leaf: Leaf}) { rootLeaf = leaf }, }) await act() // printLeaf(rootLeaf) await act(() => { toggleNestedRows() }) await act(() => { toggleNestedRows() }) // printLeaf(rootLeaf) }) expect(s1).toMatchInlineSnapshot(` " <div data-visible='yes' style='margin-left: 0em'> a 0 visible </div> <div data-visible='yes' style='margin-left: 1em'> a_a 1 visible </div> <div data-visible='yes' style='margin-left: 1em'> a_b 1 visible </div> <div data-visible='yes' style='margin-left: 2em'> a_b_a 2 visible </div> <div data-visible='yes' style='margin-left: 0em'> b 0 visible </div> <div data-visible='yes' style='margin-left: 1em'> b_a 1 visible </div> <div data-visible='yes' style='margin-left: 1em'> b_b 1 visible </div> " `) expect(s2).toMatchInlineSnapshot(` " <div data-visible='yes' style='margin-left: 0em'> a 0 visible </div> <div data-visible='no' style='margin-left: 1em'> a_a 1 hidden </div> <div data-visible='no' style='margin-left: 1em'> a_b 1 hidden </div> <div data-visible='no' style='margin-left: 2em'> a_b_a 2 hidden </div> <div data-visible='yes' style='margin-left: 0em'> b 0 visible </div> <div data-visible='no' style='margin-left: 1em'> b_a 1 hidden </div> <div data-visible='no' style='margin-left: 1em'> b_b 1 hidden </div> " `) expect(s3).toBe(s1) }) function printLeaf(leaf: Leaf) { const rows = [] as string[] parse(leaf, {level: 0}) function parse(leaf: Leaf, {level}: {level: number}) { const {data} = leaf const tab = ' '.repeat(level * 2) rows.push(`${tab}id: ${leaf.fullID}`) rows.push(`${tab}type: ${data.type}`) switch (data.type) { case 'using': { break } case 'element': { const {value, index} = data.block rows.push(`${tab}index: ${index}`) rows.push(`${tab}text: ${value.textContent}`) break } case 'list': { break } case 'list item': { break } case 'route': { break } case 'rec item': { break } case 'rec': { break } } let hasChilds = false iterateChildLeafs(leaf, child => { parse(child, {level: level + 1}) rows.push(`${tab} --`) hasChilds = true }) if (hasChilds) { rows.pop() } } console.log(rows.join(`\n`)) function iterateChildLeafs(leaf: Leaf, cb: (child: Leaf) => void) { for (const key in leaf.root.childSpawns[leaf.fullID]) { const childs = leaf.root.childSpawns[leaf.fullID][key] for (let i = 0; i < childs.length; i++) { cb(childs[i]) } } } } test('top level rec suppot', async () => { //prettier-ignore type Item = {id: number; title: string; child: Item[]}; const [s1] = await exec(async () => { const Article = rec<Item>(({store}) => { const [title, child] = remap(store, ['title', 'child'] as const) h('div', () => { h('header', {text: title}) list({ source: child, key: 'id', fn({store}) { Article({store}) }, }) }) }) const item = createStore<Item>({ id: 0, title: 'root', child: [ { id: 1, title: 'a', child: [], }, { id: 2, title: 'b', child: [ { id: 3, title: 'c', child: [], }, ], }, ], }) using(el, () => { h('section', () => { Article({store: item}) }) }) await act() }) expect(s1).toMatchInlineSnapshot(` " <section> <div> <header>root</header> <div><header>a</header></div> <div> <header>b</header> <div><header>c</header></div> </div> </div> </section> " `) }) describe('recursion', () => { /** * TODO wrong behavior! * infinite loop during #c click */ test.skip('store update #1', async () => { type ValueType = {id: string; child: ValueType[]} const [initial, cClicked, bClicked, dClicked, aClicked] = await exec( async () => { const Value = rec<ValueType & {parentValues: number[]}>(({store}) => { const [id, child, inputValues] = remap(store, [ 'id', 'child', 'parentValues', ]) const click = createEvent<any>() const count = createStore(0).on(click, x => x + 1) const parentValues = combine(inputValues, count, (items, n) => [ ...items, n, ]) h('div', () => { h('button', { attr: {id}, handler: {click}, text: ['Click ', id], }) h('b', {text: count}) list(inputValues, ({store}) => { h('i', {text: store}) }) list(child, ({store}) => { Value({ store: combine( store, parentValues, ({id, child}, parentValues) => ({id, child, parentValues}), ), }) }) }) }) const root = createStore<ValueType & {parentValues: number[]}>({ id: 'a', child: [ {id: 'b', child: [{id: 'c', child: []}]}, {id: 'd', child: [{id: 'e', child: []}]}, {id: 'f', child: []}, ], parentValues: [], }) using(el, { fn() { Value({store: root}) }, }) await act() await act(async () => { el.querySelector<HTMLButtonElement>('#c')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#b')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#d')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#a')!.click() }) }, ) expect(initial).toMatchInlineSnapshot() expect(cClicked).toMatchInlineSnapshot() expect(bClicked).toMatchInlineSnapshot() expect(dClicked).toMatchInlineSnapshot() expect(aClicked).toMatchInlineSnapshot() }) describe('store update #2', () => { //prettier-ignore type ValueType = {id: string; child: ValueType[]}; test('with on', async () => { const [initial, cClicked, bClicked, dClicked, aClicked] = await exec( async () => { const Value = rec<ValueType>(({store}) => { const [id, child] = remap(store, ['id', 'child']) const click = createEvent<any>() const count = createStore(0).on(click, x => x + 1) h('div', () => { h('button', { attr: {id}, handler: {click}, text: ['Click ', id], }) h('b', {text: count}) list(child, ({store}) => { Value({store}) }) }) }) const root = createStore<ValueType>({ id: 'a', child: [ {id: 'b', child: [{id: 'c', child: []}]}, {id: 'd', child: [{id: 'e', child: []}]}, {id: 'f', child: []}, ], }) using(el, { fn() { Value({store: root}) }, }) await act() await act(async () => { el.querySelector<HTMLButtonElement>('#c')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#b')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#d')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#a')!.click() }) }, ) expect(initial).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>0</b> <div><button id='c'>Click c</button><b>0</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(cClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>0</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(bClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(dClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>1</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(aClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>1</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>1</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) }) test('with sample single target', async () => { const [initial, cClicked, bClicked, dClicked, aClicked] = await exec( async () => { const Value = rec<ValueType>(({store}) => { const [id, child] = remap(store, ['id', 'child']) const click = createEvent<any>() const count = createStore(0) sample({ clock: click, source: count, target: count, fn: x => x + 1, }) h('div', () => { h('button', { attr: {id}, handler: {click}, text: ['Click ', id], }) h('b', {text: count}) list(child, ({store}) => { Value({store}) }) }) }) const root = createStore<ValueType>({ id: 'a', child: [ {id: 'b', child: [{id: 'c', child: []}]}, {id: 'd', child: [{id: 'e', child: []}]}, {id: 'f', child: []}, ], }) using(el, { fn() { Value({store: root}) }, }) await act() await act(async () => { el.querySelector<HTMLButtonElement>('#c')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#b')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#d')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#a')!.click() }) }, ) expect(initial).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>0</b> <div><button id='c'>Click c</button><b>0</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(cClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>0</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(bClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(dClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>1</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(aClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>1</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>1</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) }) test('with sample array target', async () => { const [initial, cClicked, bClicked, dClicked, aClicked] = await exec( async () => { const Value = rec<ValueType>(({store}) => { const [id, child] = remap(store, ['id', 'child']) const click = createEvent<any>() const count = createStore(0) sample({ clock: click, source: count, target: [count], fn: x => x + 1, }) h('div', () => { h('button', { attr: {id}, handler: {click}, text: ['Click ', id], }) h('b', {text: count}) list(child, ({store}) => { Value({store}) }) }) }) const root = createStore<ValueType>({ id: 'a', child: [ {id: 'b', child: [{id: 'c', child: []}]}, {id: 'd', child: [{id: 'e', child: []}]}, {id: 'f', child: []}, ], }) using(el, { fn() { Value({store: root}) }, }) await act() await act(async () => { el.querySelector<HTMLButtonElement>('#c')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#b')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#d')!.click() }) await act(async () => { el.querySelector<HTMLButtonElement>('#a')!.click() }) }, ) expect(initial).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>0</b> <div><button id='c'>Click c</button><b>0</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(cClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>0</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(bClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>0</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(dClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>0</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>1</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) expect(aClicked).toMatchInlineSnapshot(` " <div> <button id='a'>Click a</button><b>1</b> <div> <button id='b'>Click b</button><b>1</b> <div><button id='c'>Click c</button><b>1</b></div> </div> <div> <button id='d'>Click d</button><b>1</b> <div><button id='e'>Click e</button><b>0</b></div> </div> <div><button id='f'>Click f</button><b>0</b></div> </div> " `) }) }) })
the_stack
import expect from 'expect'; import { getTestState, setupTestBrowserHooks, setupTestPageAndContextHooks, describeChromeOnly, } from './mocha-utils'; // eslint-disable-line import/extensions import { ElementHandle } from '../lib/cjs/puppeteer/common/JSHandle.js'; import utils from './utils.js'; describeChromeOnly('AriaQueryHandler', () => { setupTestBrowserHooks(); setupTestPageAndContextHooks(); describe('parseAriaSelector', () => { beforeEach(async () => { const { page } = getTestState(); await page.setContent( '<button id="btn" role="button"> Submit button and some spaces </button>' ); }); it('should find button', async () => { const { page } = getTestState(); const expectFound = async (button: ElementHandle) => { const id = await button.evaluate((button: Element) => button.id); expect(id).toBe('btn'); }; let button = await page.$( 'aria/Submit button and some spaces[role="button"]' ); await expectFound(button); button = await page.$( 'aria/ Submit button and some spaces[role="button"]' ); await expectFound(button); button = await page.$( 'aria/Submit button and some spaces [role="button"]' ); await expectFound(button); button = await page.$( 'aria/Submit button and some spaces [ role = "button" ] ' ); await expectFound(button); button = await page.$( 'aria/[role="button"]Submit button and some spaces' ); await expectFound(button); button = await page.$( 'aria/Submit button [role="button"]and some spaces' ); await expectFound(button); button = await page.$( 'aria/[name=" Submit button and some spaces"][role="button"]' ); await expectFound(button); button = await page.$( 'aria/ignored[name="Submit button and some spaces"][role="button"]' ); await expectFound(button); await expect(page.$('aria/smth[smth="true"]')).rejects.toThrow( 'Unknown aria attribute "smth" in selector' ); }); }); describe('queryOne', () => { it('should find button by role', async () => { const { page } = getTestState(); await page.setContent( '<div id="div"><button id="btn" role="button">Submit</button></div>' ); const button = await page.$('aria/[role="button"]'); const id = await button.evaluate((button: Element) => button.id); expect(id).toBe('btn'); }); it('should find button by name and role', async () => { const { page } = getTestState(); await page.setContent( '<div id="div"><button id="btn" role="button">Submit</button></div>' ); const button = await page.$('aria/Submit[role="button"]'); const id = await button.evaluate((button: Element) => button.id); expect(id).toBe('btn'); }); it('should find first matching element', async () => { const { page } = getTestState(); await page.setContent( ` <div role="menu" id="mnu1" aria-label="menu div"></div> <div role="menu" id="mnu2" aria-label="menu div"></div> ` ); const div = await page.$('aria/menu div'); const id = await div.evaluate((div: Element) => div.id); expect(id).toBe('mnu1'); }); it('should find by name', async () => { const { page } = getTestState(); await page.setContent( ` <div role="menu" id="mnu1" aria-label="menu-label1">menu div</div> <div role="menu" id="mnu2" aria-label="menu-label2">menu div</div> ` ); const menu = await page.$('aria/menu-label1'); const id = await menu.evaluate((div: Element) => div.id); expect(id).toBe('mnu1'); }); it('should find by name', async () => { const { page } = getTestState(); await page.setContent( ` <div role="menu" id="mnu1" aria-label="menu-label1">menu div</div> <div role="menu" id="mnu2" aria-label="menu-label2">menu div</div> ` ); const menu = await page.$('aria/menu-label2'); const id = await menu.evaluate((div: Element) => div.id); expect(id).toBe('mnu2'); }); }); describe('queryAll', () => { it('should find menu by name', async () => { const { page } = getTestState(); await page.setContent( ` <div role="menu" id="mnu1" aria-label="menu div"></div> <div role="menu" id="mnu2" aria-label="menu div"></div> ` ); const divs = await page.$$('aria/menu div'); const ids = await Promise.all( divs.map((n) => n.evaluate((div: Element) => div.id)) ); expect(ids.join(', ')).toBe('mnu1, mnu2'); }); }); describe('queryAllArray', () => { it('$$eval should handle many elements', async () => { const { page } = getTestState(); await page.setContent(''); await page.evaluate( ` for (var i = 0; i <= 10000; i++) { const button = document.createElement('button'); button.textContent = i; document.body.appendChild(button); } ` ); const sum = await page.$$eval('aria/[role="button"]', (buttons) => buttons.reduce((acc, button) => acc + Number(button.textContent), 0) ); expect(sum).toBe(50005000); }); }); describe('waitForSelector (aria)', function () { const addElement = (tag) => document.body.appendChild(document.createElement(tag)); it('should immediately resolve promise if node exists', async () => { const { page, server } = getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(addElement, 'button'); await page.waitForSelector('aria/[role="button"]'); }); it('should persist query handler bindings across reloads', async () => { const { page, server } = getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(addElement, 'button'); await page.waitForSelector('aria/[role="button"]'); await page.reload(); await page.evaluate(addElement, 'button'); await page.waitForSelector('aria/[role="button"]'); }); it('should persist query handler bindings across navigations', async () => { const { page, server } = getTestState(); // Reset page but make sure that execution context ids start with 1. await page.goto('data:text/html,'); await page.goto(server.EMPTY_PAGE); await page.evaluate(addElement, 'button'); await page.waitForSelector('aria/[role="button"]'); // Reset page but again make sure that execution context ids start with 1. await page.goto('data:text/html,'); await page.goto(server.EMPTY_PAGE); await page.evaluate(addElement, 'button'); await page.waitForSelector('aria/[role="button"]'); }); it('should work independently of `exposeFunction`', async () => { const { page, server } = getTestState(); await page.goto(server.EMPTY_PAGE); await page.exposeFunction('ariaQuerySelector', (a, b) => a + b); await page.evaluate(addElement, 'button'); await page.waitForSelector('aria/[role="button"]'); const result = await page.evaluate('globalThis.ariaQuerySelector(2,8)'); expect(result).toBe(10); }); it('should work with removed MutationObserver', async () => { const { page } = getTestState(); await page.evaluate(() => delete window.MutationObserver); const [handle] = await Promise.all([ page.waitForSelector('aria/anything'), page.setContent(`<h1>anything</h1>`), ]); expect( await page.evaluate((x: HTMLElement) => x.textContent, handle) ).toBe('anything'); }); it('should resolve promise when node is added', async () => { const { page, server } = getTestState(); await page.goto(server.EMPTY_PAGE); const frame = page.mainFrame(); const watchdog = frame.waitForSelector('aria/[role="heading"]'); await frame.evaluate(addElement, 'br'); await frame.evaluate(addElement, 'h1'); const elementHandle = await watchdog; const tagName = await elementHandle .getProperty('tagName') .then((element) => element.jsonValue()); expect(tagName).toBe('H1'); }); it('should work when node is added through innerHTML', async () => { const { page, server } = getTestState(); await page.goto(server.EMPTY_PAGE); const watchdog = page.waitForSelector('aria/name'); await page.evaluate(addElement, 'span'); await page.evaluate( () => (document.querySelector('span').innerHTML = '<h3><div aria-label="name"></div></h3>') ); await watchdog; }); it('Page.waitForSelector is shortcut for main frame', async () => { const { page, server } = getTestState(); await page.goto(server.EMPTY_PAGE); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); const otherFrame = page.frames()[1]; const watchdog = page.waitForSelector('aria/[role="button"]'); await otherFrame.evaluate(addElement, 'button'); await page.evaluate(addElement, 'button'); const elementHandle = await watchdog; expect(elementHandle.executionContext().frame()).toBe(page.mainFrame()); }); it('should run in specified frame', async () => { const { page, server } = getTestState(); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE); const frame1 = page.frames()[1]; const frame2 = page.frames()[2]; const waitForSelectorPromise = frame2.waitForSelector( 'aria/[role="button"]' ); await frame1.evaluate(addElement, 'button'); await frame2.evaluate(addElement, 'button'); const elementHandle = await waitForSelectorPromise; expect(elementHandle.executionContext().frame()).toBe(frame2); }); it('should throw when frame is detached', async () => { const { page, server } = getTestState(); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); const frame = page.frames()[1]; let waitError = null; const waitPromise = frame .waitForSelector('aria/does-not-exist') .catch((error) => (waitError = error)); await utils.detachFrame(page, 'frame1'); await waitPromise; expect(waitError).toBeTruthy(); expect(waitError.message).toContain( 'waitForFunction failed: frame got detached.' ); }); it('should survive cross-process navigation', async () => { const { page, server } = getTestState(); let imgFound = false; const waitForSelector = page .waitForSelector('aria/[role="img"]') .then(() => (imgFound = true)); await page.goto(server.EMPTY_PAGE); expect(imgFound).toBe(false); await page.reload(); expect(imgFound).toBe(false); await page.goto(server.CROSS_PROCESS_PREFIX + '/grid.html'); await waitForSelector; expect(imgFound).toBe(true); }); it('should wait for visible', async () => { const { page } = getTestState(); let divFound = false; const waitForSelector = page .waitForSelector('aria/name', { visible: true }) .then(() => (divFound = true)); await page.setContent( `<div aria-label='name' style='display: none; visibility: hidden;'>1</div>` ); expect(divFound).toBe(false); await page.evaluate(() => document.querySelector('div').style.removeProperty('display') ); expect(divFound).toBe(false); await page.evaluate(() => document.querySelector('div').style.removeProperty('visibility') ); expect(await waitForSelector).toBe(true); expect(divFound).toBe(true); }); it('should wait for visible recursively', async () => { const { page } = getTestState(); let divVisible = false; const waitForSelector = page .waitForSelector('aria/inner', { visible: true }) .then(() => (divVisible = true)); await page.setContent( `<div style='display: none; visibility: hidden;'><div aria-label="inner">hi</div></div>` ); expect(divVisible).toBe(false); await page.evaluate(() => document.querySelector('div').style.removeProperty('display') ); expect(divVisible).toBe(false); await page.evaluate(() => document.querySelector('div').style.removeProperty('visibility') ); expect(await waitForSelector).toBe(true); expect(divVisible).toBe(true); }); it('hidden should wait for visibility: hidden', async () => { const { page } = getTestState(); let divHidden = false; await page.setContent( `<div role='button' style='display: block;'></div>` ); const waitForSelector = page .waitForSelector('aria/[role="button"]', { hidden: true }) .then(() => (divHidden = true)); await page.waitForSelector('aria/[role="button"]'); // do a round trip expect(divHidden).toBe(false); await page.evaluate(() => document.querySelector('div').style.setProperty('visibility', 'hidden') ); expect(await waitForSelector).toBe(true); expect(divHidden).toBe(true); }); it('hidden should wait for display: none', async () => { const { page } = getTestState(); let divHidden = false; await page.setContent(`<div role='main' style='display: block;'></div>`); const waitForSelector = page .waitForSelector('aria/[role="main"]', { hidden: true }) .then(() => (divHidden = true)); await page.waitForSelector('aria/[role="main"]'); // do a round trip expect(divHidden).toBe(false); await page.evaluate(() => document.querySelector('div').style.setProperty('display', 'none') ); expect(await waitForSelector).toBe(true); expect(divHidden).toBe(true); }); it('hidden should wait for removal', async () => { const { page } = getTestState(); await page.setContent(`<div role='main'></div>`); let divRemoved = false; const waitForSelector = page .waitForSelector('aria/[role="main"]', { hidden: true }) .then(() => (divRemoved = true)); await page.waitForSelector('aria/[role="main"]'); // do a round trip expect(divRemoved).toBe(false); await page.evaluate(() => document.querySelector('div').remove()); expect(await waitForSelector).toBe(true); expect(divRemoved).toBe(true); }); it('should return null if waiting to hide non-existing element', async () => { const { page } = getTestState(); const handle = await page.waitForSelector('aria/non-existing', { hidden: true, }); expect(handle).toBe(null); }); it('should respect timeout', async () => { const { page, puppeteer } = getTestState(); let error = null; await page .waitForSelector('aria/[role="button"]', { timeout: 10 }) .catch((error_) => (error = error_)); expect(error).toBeTruthy(); expect(error.message).toContain( 'waiting for selector `[role="button"]` failed: timeout' ); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); }); it('should have an error message specifically for awaiting an element to be hidden', async () => { const { page } = getTestState(); await page.setContent(`<div role='main'></div>`); let error = null; await page .waitForSelector('aria/[role="main"]', { hidden: true, timeout: 10 }) .catch((error_) => (error = error_)); expect(error).toBeTruthy(); expect(error.message).toContain( 'waiting for selector `[role="main"]` to be hidden failed: timeout' ); }); it('should respond to node attribute mutation', async () => { const { page } = getTestState(); let divFound = false; const waitForSelector = page .waitForSelector('aria/zombo') .then(() => (divFound = true)); await page.setContent(`<div aria-label='notZombo'></div>`); expect(divFound).toBe(false); await page.evaluate(() => document.querySelector('div').setAttribute('aria-label', 'zombo') ); expect(await waitForSelector).toBe(true); }); it('should return the element handle', async () => { const { page } = getTestState(); const waitForSelector = page.waitForSelector('aria/zombo'); await page.setContent(`<div aria-label='zombo'>anything</div>`); expect( await page.evaluate( (x: HTMLElement) => x.textContent, await waitForSelector ) ).toBe('anything'); }); it('should have correct stack trace for timeout', async () => { const { page } = getTestState(); let error; await page .waitForSelector('aria/zombo', { timeout: 10 }) .catch((error_) => (error = error_)); expect(error.stack).toContain('waiting for selector `zombo` failed'); }); }); describe('queryOne (Chromium web test)', async () => { beforeEach(async () => { const { page } = getTestState(); await page.setContent( ` <h2 id="shown">title</h2> <h2 id="hidden" aria-hidden="true">title</h2> <div id="node1" aria-labeledby="node2"></div> <div id="node2" aria-label="bar"></div> <div id="node3" aria-label="foo"></div> <div id="node4" class="container"> <div id="node5" role="button" aria-label="foo"></div> <div id="node6" role="button" aria-label="foo"></div> <!-- Accessible name not available when element is hidden --> <div id="node7" hidden role="button" aria-label="foo"></div> <div id="node8" role="button" aria-label="bar"></div> </div> <button id="node10">text content</button> <h1 id="node11">text content</h1> <!-- Accessible name not available when role is "presentation" --> <h1 id="node12" role="presentation">text content</h1> <!-- Elements inside shadow dom should be found --> <script> const div = document.createElement('div'); const shadowRoot = div.attachShadow({mode: 'open'}); const h1 = document.createElement('h1'); h1.textContent = 'text content'; h1.id = 'node13'; shadowRoot.appendChild(h1); document.documentElement.appendChild(div); </script> <img id="node20" src="" alt="Accessible Name"> <input id="node21" type="submit" value="Accessible Name"> <label id="node22" for="node23">Accessible Name</label> <!-- Accessible name for the <input> is "Accessible Name" --> <input id="node23"> <div id="node24" title="Accessible Name"></div> <div role="treeitem" id="node30"> <div role="treeitem" id="node31"> <div role="treeitem" id="node32">item1</div> <div role="treeitem" id="node33">item2</div> </div> <div role="treeitem" id="node34">item3</div> </div> <!-- Accessible name for the <div> is "item1 item2 item3" --> <div aria-describedby="node30"></div> ` ); }); const getIds = async (elements: ElementHandle[]) => Promise.all( elements.map((element) => element.evaluate((element: Element) => element.id) ) ); it('should find by name "foo"', async () => { const { page } = getTestState(); const found = await page.$$('aria/foo'); const ids = await getIds(found); expect(ids).toEqual(['node3', 'node5', 'node6']); }); it('should find by name "bar"', async () => { const { page } = getTestState(); const found = await page.$$('aria/bar'); const ids = await getIds(found); expect(ids).toEqual(['node1', 'node2', 'node8']); }); it('should find treeitem by name', async () => { const { page } = getTestState(); const found = await page.$$('aria/item1 item2 item3'); const ids = await getIds(found); expect(ids).toEqual(['node30']); }); it('should find by role "button"', async () => { const { page } = getTestState(); const found = await page.$$<HTMLButtonElement>('aria/[role="button"]'); const ids = await getIds(found); expect(ids).toEqual(['node5', 'node6', 'node8', 'node10', 'node21']); }); it('should find by role "heading"', async () => { const { page } = getTestState(); const found = await page.$$('aria/[role="heading"]'); const ids = await getIds(found); expect(ids).toEqual(['shown', 'hidden', 'node11', 'node13']); }); it('should find both ignored and unignored', async () => { const { page } = getTestState(); const found = await page.$$('aria/title'); const ids = await getIds(found); expect(ids).toEqual(['shown', 'hidden']); }); }); });
the_stack
import React, { useEffect, useRef } from "react"; import { connect } from "react-redux"; import { reduxForm, InjectedFormProps } from "redux-form"; import styled from "styled-components"; import { AppState } from "reducers"; import { API_HOME_SCREEN_FORM } from "constants/forms"; import { Colors } from "constants/Colors"; import { TabComponent, TabProp } from "components/ads/Tabs"; import { IconSize } from "components/ads/Icon"; import NewApiScreen from "./NewApi"; import NewQueryScreen from "./NewQuery"; import ActiveDataSources from "./ActiveDataSources"; import MockDataSources from "./MockDataSources"; import AddDatasourceSecurely from "./AddDatasourceSecurely"; import { getDatasources, getMockDatasources } from "selectors/entitiesSelector"; import { Datasource, MockDatasource } from "entities/Datasource"; import Text, { TextType } from "components/ads/Text"; import scrollIntoView from "scroll-into-view-if-needed"; import { INTEGRATION_TABS, INTEGRATION_EDITOR_URL, INTEGRATION_EDITOR_MODES, } from "constants/routes"; import { thinScrollbar } from "constants/DefaultTheme"; import BackButton from "../DataSourceEditor/BackButton"; import UnsupportedPluginDialog from "./UnsupportedPluginDialog"; import { getQueryParams } from "utils/AppsmithUtils"; import { getIsGeneratePageInitiator } from "utils/GenerateCrudUtil"; import { getCurrentApplicationId } from "selectors/editorSelectors"; const HeaderFlex = styled.div` display: flex; align-items: center; `; const ApiHomePage = styled.div` display: flex; flex-direction: column; font-size: 20px; padding: 20px 20px 0 20px; /* margin-left: 10px; */ flex: 1; overflow: hidden !important; .closeBtn { position: absolute; left: 70%; } .bp3-collapse-body { position: absolute; z-index: 99999; background-color: ${Colors.WHITE}; border: 1px solid ${Colors.ALTO}; box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1); border-radius: 4px; width: 100%; padding: 20px; } .fontSize16 { font-size: 16px; } `; const MainTabsContainer = styled.div` width: 100%; height: 100%; `; const SectionGrid = styled.div` margin-top: 16px; display: grid; grid-template-columns: 1fr 180px; grid-template-rows: auto minmax(0, 1fr); gap: 10px 16px; flex: 1; min-height: 0; `; const NewIntegrationsContainer = styled.div` ${thinScrollbar}; scrollbar-width: thin; overflow: auto; flex: 1; & > div { margin-bottom: 20px; } `; type IntegrationsHomeScreenProps = { pageId: string; selectedTab: string; location: { search: string; pathname: string; }; history: { replace: (data: string) => void; push: (data: string) => void; }; isCreating: boolean; dataSources: Datasource[]; mockDatasources: MockDatasource[]; applicationId: string; }; type IntegrationsHomeScreenState = { page: number; activePrimaryMenuId: number; activeSecondaryMenuId: number; unsupportedPluginDialogVisible: boolean; }; type Props = IntegrationsHomeScreenProps & InjectedFormProps<{ category: string }, IntegrationsHomeScreenProps>; const PRIMARY_MENU: TabProp[] = [ { key: "ACTIVE", title: "Active", panelComponent: <div />, }, { key: "CREATE_NEW", title: "Create New", panelComponent: <div />, icon: "plus", iconSize: IconSize.XS, }, ]; const PRIMARY_MENU_IDS = { ACTIVE: 0, CREATE_NEW: 1, }; const SECONDARY_MENU: TabProp[] = [ { key: "API", title: "API", panelComponent: <div />, }, { key: "DATABASE", title: "Database", panelComponent: <div />, }, ]; const getSecondaryMenu = (hasActiveSources: boolean) => { const mockDbMenu = { key: "MOCK_DATABASE", title: "Sample Databases", panelComponent: <div />, }; return hasActiveSources ? [...SECONDARY_MENU, mockDbMenu] : [mockDbMenu, ...SECONDARY_MENU]; }; const getSecondaryMenuIds = (hasActiveSources = false) => { return { API: 0 + (hasActiveSources ? 0 : 1), DATABASE: 1 + (hasActiveSources ? 0 : 1), MOCK_DATABASE: 2 - (hasActiveSources ? 0 : 2), }; }; // const TERTIARY_MENU: TabProp[] = [ // { // key: "ACTIVE_CONNECTIONS", // title: "Active Connections", // panelComponent: <div />, // }, // { // key: "MOCK_DATABASE", // title: "Mock Databases", // panelComponent: <div />, // }, // ]; const TERTIARY_MENU_IDS = { ACTIVE_CONNECTIONS: 0, MOCK_DATABASE: 1, }; interface MockDataSourcesProps { mockDatasources: MockDatasource[]; active: boolean; } function UseMockDatasources({ active, mockDatasources }: MockDataSourcesProps) { const useMockRef = useRef<HTMLDivElement>(null); const isMounted = useRef(false); useEffect(() => { if (active && useMockRef.current) { isMounted.current && scrollIntoView(useMockRef.current, { behavior: "smooth", scrollMode: "always", block: "start", boundary: document.getElementById("new-integrations-wrapper"), }); } else { isMounted.current = true; } }, [active]); return ( <div id="mock-database" ref={useMockRef}> <Text type={TextType.H2}>Sample Databases</Text> <MockDataSources mockDatasources={mockDatasources} /> </div> ); } function CreateNewAPI({ active, history, isCreating, pageId, showUnsupportedPluginDialog, }: any) { const newAPIRef = useRef<HTMLDivElement>(null); const isMounted = useRef(false); useEffect(() => { if (active && newAPIRef.current) { isMounted.current && scrollIntoView(newAPIRef.current, { behavior: "smooth", scrollMode: "always", block: "start", boundary: document.getElementById("new-integrations-wrapper"), }); } else { isMounted.current = true; } }, [active]); return ( <div id="new-api" ref={newAPIRef}> <Text type={TextType.H2}>APIs</Text> <NewApiScreen history={history} isCreating={isCreating} location={location} pageId={pageId} showUnsupportedPluginDialog={showUnsupportedPluginDialog} /> </div> ); } function CreateNewDatasource({ active, history, isCreating, pageId, showUnsupportedPluginDialog, }: any) { const newDatasourceRef = useRef<HTMLDivElement>(null); useEffect(() => { if (active && newDatasourceRef.current) { scrollIntoView(newDatasourceRef.current, { behavior: "smooth", scrollMode: "always", block: "start", boundary: document.getElementById("new-integrations-wrapper"), }); } }, [active]); return ( <div id="new-datasources" ref={newDatasourceRef}> <Text type={TextType.H2}>Databases</Text> <NewQueryScreen history={history} isCreating={isCreating} location={location} pageId={pageId} showUnsupportedPluginDialog={showUnsupportedPluginDialog} /> </div> ); } class IntegrationsHomeScreen extends React.Component< Props, IntegrationsHomeScreenState > { unsupportedPluginContinueAction: () => void; constructor(props: Props) { super(props); this.unsupportedPluginContinueAction = () => null; this.state = { page: 1, activePrimaryMenuId: PRIMARY_MENU_IDS.CREATE_NEW, activeSecondaryMenuId: getSecondaryMenuIds( props.mockDatasources.length > 0, ).API, unsupportedPluginDialogVisible: false, }; } syncActivePrimaryMenu = () => { // on mount/update if syncing the primary active menu. const { selectedTab } = this.props; if ( (selectedTab === INTEGRATION_TABS.NEW && this.state.activePrimaryMenuId !== PRIMARY_MENU_IDS.CREATE_NEW) || (selectedTab === INTEGRATION_TABS.ACTIVE && this.state.activePrimaryMenuId !== PRIMARY_MENU_IDS.ACTIVE) ) { this.setState({ activePrimaryMenuId: selectedTab === INTEGRATION_TABS.NEW ? PRIMARY_MENU_IDS.CREATE_NEW : PRIMARY_MENU_IDS.ACTIVE, }); } }; componentDidMount() { const { applicationId, dataSources, history, pageId } = this.props; const queryParams = getQueryParams(); const redirectMode = queryParams.mode; const isGeneratePageInitiator = getIsGeneratePageInitiator(); if (isGeneratePageInitiator) { if (redirectMode === INTEGRATION_EDITOR_MODES.AUTO) { delete queryParams.mode; delete queryParams.from; history.replace( INTEGRATION_EDITOR_URL( applicationId, pageId, INTEGRATION_TABS.NEW, "", queryParams, ), ); } } else if ( dataSources.length > 0 && redirectMode === INTEGRATION_EDITOR_MODES.AUTO ) { // User will be taken to active tab if there are datasources history.replace( INTEGRATION_EDITOR_URL(applicationId, pageId, INTEGRATION_TABS.ACTIVE), ); } else if (redirectMode === INTEGRATION_EDITOR_MODES.MOCK) { // If there are no datasources -> new user history.replace( INTEGRATION_EDITOR_URL(applicationId, pageId, INTEGRATION_TABS.NEW), ); this.onSelectSecondaryMenu( getSecondaryMenuIds(dataSources.length > 0).MOCK_DATABASE, ); } else { this.syncActivePrimaryMenu(); } } componentDidUpdate(prevProps: Props) { this.syncActivePrimaryMenu(); const { applicationId, dataSources, history, pageId } = this.props; if (dataSources.length === 0 && prevProps.dataSources.length > 0) { history.replace( INTEGRATION_EDITOR_URL(applicationId, pageId, INTEGRATION_TABS.NEW), ); this.onSelectSecondaryMenu( getSecondaryMenuIds(dataSources.length > 0).MOCK_DATABASE, ); } } onSelectPrimaryMenu = (activePrimaryMenuId: number) => { const { applicationId, dataSources, history, pageId } = this.props; if (activePrimaryMenuId === this.state.activePrimaryMenuId) { return; } history.push( INTEGRATION_EDITOR_URL( applicationId, pageId, activePrimaryMenuId === PRIMARY_MENU_IDS.ACTIVE ? INTEGRATION_TABS.ACTIVE : INTEGRATION_TABS.NEW, ), ); this.setState({ activeSecondaryMenuId: activePrimaryMenuId === PRIMARY_MENU_IDS.ACTIVE ? TERTIARY_MENU_IDS.ACTIVE_CONNECTIONS : getSecondaryMenuIds(dataSources.length > 0).API, }); }; onSelectSecondaryMenu = (activeSecondaryMenuId: number) => { this.setState({ activeSecondaryMenuId }); }; showUnsupportedPluginDialog = (callback: () => void) => { this.setState({ unsupportedPluginDialogVisible: true, }); this.unsupportedPluginContinueAction = callback; }; render() { const { dataSources, history, isCreating, location, pageId } = this.props; const { unsupportedPluginDialogVisible } = this.state; let currentScreen; const { activePrimaryMenuId, activeSecondaryMenuId } = this.state; const isGeneratePageInitiator = getIsGeneratePageInitiator(); // Avoid user to switch tabs when in generate page flow by hiding the tabs itself. const showTabs = !isGeneratePageInitiator; const mockDataSection = this.props.mockDatasources.length > 0 ? ( <UseMockDatasources active={ activeSecondaryMenuId === getSecondaryMenuIds(dataSources.length > 0).MOCK_DATABASE } mockDatasources={this.props.mockDatasources} /> ) : null; if (activePrimaryMenuId === PRIMARY_MENU_IDS.CREATE_NEW) { currentScreen = ( <NewIntegrationsContainer id="new-integrations-wrapper"> {dataSources.length === 0 && <AddDatasourceSecurely />} {dataSources.length === 0 && this.props.mockDatasources.length > 0 && mockDataSection} <CreateNewAPI active={ activeSecondaryMenuId === getSecondaryMenuIds(dataSources.length > 0).API } history={history} isCreating={isCreating} location={location} pageId={pageId} showUnsupportedPluginDialog={this.showUnsupportedPluginDialog} /> <CreateNewDatasource active={ activeSecondaryMenuId === getSecondaryMenuIds(dataSources.length > 0).DATABASE } history={history} isCreating={isCreating} location={location} pageId={pageId} showUnsupportedPluginDialog={this.showUnsupportedPluginDialog} /> {dataSources.length > 0 && this.props.mockDatasources.length > 0 && mockDataSection} </NewIntegrationsContainer> ); } else { currentScreen = ( <ActiveDataSources dataSources={dataSources} history={this.props.history} location={location} onCreateNew={() => this.onSelectPrimaryMenu(PRIMARY_MENU_IDS.CREATE_NEW) } pageId={pageId} /> ); } return ( <> <BackButton /> <UnsupportedPluginDialog isModalOpen={unsupportedPluginDialogVisible} onClose={() => this.setState({ unsupportedPluginDialogVisible: false }) } onContinue={this.unsupportedPluginContinueAction} /> <ApiHomePage className="t--integrationsHomePage" style={{ overflow: "auto" }} > <HeaderFlex> <p className="sectionHeadings">Datasources</p> </HeaderFlex> <SectionGrid> <MainTabsContainer> {showTabs && ( <TabComponent onSelect={this.onSelectPrimaryMenu} selectedIndex={this.state.activePrimaryMenuId} tabs={PRIMARY_MENU} /> )} </MainTabsContainer> <div /> {currentScreen} {activePrimaryMenuId === PRIMARY_MENU_IDS.CREATE_NEW && ( <TabComponent className="t--vertical-menu" onSelect={this.onSelectSecondaryMenu} selectedIndex={this.state.activeSecondaryMenuId} tabs={ this.props.mockDatasources.length > 0 ? getSecondaryMenu(dataSources.length > 0) : SECONDARY_MENU } vertical /> )} </SectionGrid> </ApiHomePage> </> ); } } const mapStateToProps = (state: AppState) => { return { dataSources: getDatasources(state), mockDatasources: getMockDatasources(state), isCreating: state.ui.apiPane.isCreating, applicationId: getCurrentApplicationId(state), }; }; export default connect(mapStateToProps)( reduxForm<{ category: string }, IntegrationsHomeScreenProps>({ form: API_HOME_SCREEN_FORM, })(IntegrationsHomeScreen), );
the_stack
import * as sr from 'staffrender'; import {INoteSequence, NoteSequence} from '../protobuf/index'; import {MAX_MIDI_PITCH, MIN_MIDI_PITCH} from './constants'; import * as logging from './logging'; import * as sequences from './sequences'; const MIN_NOTE_LENGTH = 1; /** * An interface for providing configurable properties to a Visualizer. * @param noteHeight The vertical height in pixels of a note. * @param noteSpacing Number of horizontal pixels between each note. * @param pixelsPerTimeStep The horizontal scale at which notes are drawn. The * bigger this value, the "wider" a note looks. * @param noteRGB The color (as an RGB comma separated string) of a note. * @param activeNoteRGB The color (as an RGB comma separated string) of an * active note being played. * @param minPitch The smallest pitch to be included in the visualization. If * undefined, this will be computed from the NoteSequence being visualized. * @param maxPitch The biggest pitch to be included in the visualization. If * undefined, this will be computed from the NoteSequence being visualized. */ export interface VisualizerConfig { noteHeight?: number; noteSpacing?: number; pixelsPerTimeStep?: number; noteRGB?: string; activeNoteRGB?: string; minPitch?: number; maxPitch?: number; } /** * Abstract base class for a `NoteSequence` visualizer. */ export abstract class BaseVisualizer { public noteSequence: INoteSequence; protected config: VisualizerConfig; protected height: number; protected width: number; protected parentElement: HTMLElement; /** * Redraws the entire note sequence, optionally painting a note as * active * @param activeNote (Optional) If specified, this `Note` will be painted * in the active color. * @param scrollIntoView (Optional) If specified and the note being painted is * offscreen, the parent container will be scrolled so that the note is * in view. * @returns The x position of the painted active note. Useful for * automatically advancing the visualization if the note was painted outside * of the screen. */ public abstract redraw( activeNote?: NoteSequence.INote, scrollIntoView?: boolean): number; // Clears the current visualization. protected abstract clear(): void; // Clears the active notes in the visualization. public abstract clearActiveNotes(): void; /** * BaseVisualizer` constructor. * * @param sequence The `NoteSequence` to be visualized. * @param canvas The element where the visualization should be displayed. * @param config (optional) Visualization configuration options. */ constructor(sequence: INoteSequence, config: VisualizerConfig = {}) { // The core player (see player.ts:169) can only play unquantized sequences, // and will unquantize any quantized sequences. We must do the same here, // or else in the redrawing callback none of the visual notes will be found. const isQuantized = sequences.isQuantizedSequence(sequence); const qpm = (sequence.tempos && sequence.tempos.length > 0) ? sequence.tempos[0].qpm : undefined; this.noteSequence = isQuantized ? sequences.unquantizeSequence(sequence, qpm) : sequence; const defaultPixelsPerTimeStep = 30; this.config = { noteHeight: config.noteHeight || 6, noteSpacing: config.noteSpacing || 1, pixelsPerTimeStep: config.pixelsPerTimeStep || defaultPixelsPerTimeStep, noteRGB: config.noteRGB || '8, 41, 64', activeNoteRGB: config.activeNoteRGB || '240, 84, 119', minPitch: config.minPitch, maxPitch: config.maxPitch, }; const size = this.getSize(); this.width = size.width; this.height = size.height; } protected updateMinMaxPitches(noExtraPadding = false) { if (this.config.minPitch && this.config.maxPitch) { return; } // If the pitches haven't been specified already, figure them out // from the NoteSequence. if (this.config.minPitch === undefined) { this.config.minPitch = MAX_MIDI_PITCH; } if (this.config.maxPitch === undefined) { this.config.maxPitch = MIN_MIDI_PITCH; } // Find the smallest pitch so that we can scale the drawing correctly. for (const note of this.noteSequence.notes) { this.config.minPitch = Math.min(note.pitch, this.config.minPitch); this.config.maxPitch = Math.max(note.pitch, this.config.maxPitch); } // Add a little bit of padding at the top and the bottom. if (!noExtraPadding) { this.config.minPitch -= 2; this.config.maxPitch += 2; } } protected getSize(): {width: number; height: number} { this.updateMinMaxPitches(); // Height of the canvas based on the range of pitches in the sequence. const height = (this.config.maxPitch - this.config.minPitch) * this.config.noteHeight; // Calculate a nice width based on the length of the sequence we're // playing. // Warn if there's no totalTime or quantized steps set, since it leads // to a bad size. const endTime = this.noteSequence.totalTime; if (!endTime) { throw new Error( 'The sequence you are using with the visualizer does not have a ' + 'totalQuantizedSteps or totalTime ' + 'field set, so the visualizer can\'t be horizontally ' + 'sized correctly.'); } const width = (endTime * this.config.pixelsPerTimeStep); return {width, height}; } protected getNotePosition(note: NoteSequence.INote, noteIndex: number): {x: number; y: number, w: number, h: number} { // Size of this note. const duration = this.getNoteEndTime(note) - this.getNoteStartTime(note); const x = (this.getNoteStartTime(note) * this.config.pixelsPerTimeStep); const w = Math.max( this.config.pixelsPerTimeStep * duration - this.config.noteSpacing, MIN_NOTE_LENGTH); // The svg' y=0 is at the top, but a smaller pitch is actually // lower, so we're kind of painting backwards. const y = this.height - ((note.pitch - this.config.minPitch) * this.config.noteHeight); return {x, y, w, h: this.config.noteHeight}; } protected scrollIntoViewIfNeeded( scrollIntoView: boolean, activeNotePosition: number) { if (scrollIntoView && this.parentElement) { // See if we need to scroll the container. const containerWidth = this.parentElement.getBoundingClientRect().width; if (activeNotePosition > (this.parentElement.scrollLeft + containerWidth)) { this.parentElement.scrollLeft = activeNotePosition - 20; } } } protected getNoteStartTime(note: NoteSequence.INote) { return Math.round(note.startTime * 100000000) / 100000000; } protected getNoteEndTime(note: NoteSequence.INote) { return Math.round(note.endTime * 100000000) / 100000000; } protected isPaintingActiveNote( note: NoteSequence.INote, playedNote: NoteSequence.INote): boolean { // A note is active if it's literally the same as the note we are // playing (aka activeNote), or if it overlaps because it's a held note. const isPlayedNote = this.getNoteStartTime(note) === this.getNoteStartTime(playedNote); const heldDownDuringPlayedNote = this.getNoteStartTime(note) <= this.getNoteStartTime(playedNote) && this.getNoteEndTime(note) >= this.getNoteEndTime(playedNote); return isPlayedNote || heldDownDuringPlayedNote; } } /** * Displays a pianoroll on a canvas. Pitches are the vertical axis and time is * the horizontal. When connected to a player, the visualizer can also highlight * the notes being currently played. */ export class PianoRollCanvasVisualizer extends BaseVisualizer { protected ctx: CanvasRenderingContext2D; /** * PianoRollCanvasVisualizer` constructor. * * @param sequence The `NoteSequence` to be visualized. * @param canvas The element where the visualization should be displayed. * @param config (optional) Visualization configuration options. */ constructor( sequence: INoteSequence, canvas: HTMLCanvasElement, config: VisualizerConfig = {}) { super(sequence, config); // Initialize the canvas. this.ctx = canvas.getContext('2d'); this.parentElement = canvas.parentElement; // Use the correct device pixel ratio so that the canvas isn't blurry // on retina screens. See: // https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio const dpr = window.devicePixelRatio || 1; if (this.ctx) { this.ctx.canvas.width = dpr * this.width; this.ctx.canvas.height = dpr * this.height; // If we don't do this, then the canvas will look 2x bigger than we // want to. canvas.style.width = `${this.width}px`; canvas.style.height = `${this.height}px`; this.ctx.scale(dpr, dpr); } this.redraw(); } /** * Redraws the entire note sequence, optionally painting a note as * active * @param activeNote (Optional) If specified, this `Note` will be painted * in the active color. * @param scrollIntoView (Optional) If specified and the note being painted is * offscreen, the parent container will be scrolled so that the note is * in view. * @returns The x position of the painted active note. Useful for * automatically advancing the visualization if the note was painted outside * of the screen. */ redraw(activeNote?: NoteSequence.INote, scrollIntoView?: boolean): number { this.clear(); let activeNotePosition; for (let i = 0; i < this.noteSequence.notes.length; i++) { const note = this.noteSequence.notes[i]; const size = this.getNotePosition(note, i); // Color of this note. const opacityBaseline = 0.2; // Shift all the opacities up a little. const opacity = note.velocity ? note.velocity / 100 + opacityBaseline : 1; const isActive = activeNote && this.isPaintingActiveNote(note, activeNote); const fill = `rgba(${isActive ? this.config.activeNoteRGB : this.config.noteRGB}, ${opacity})`; this.redrawNote(size.x, size.y, size.w, size.h, fill); if (isActive && note === activeNote) { activeNotePosition = size.x; } } this.scrollIntoViewIfNeeded(scrollIntoView, activeNotePosition); return activeNotePosition; } protected clear() { this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); } public clearActiveNotes() { this.redraw(); } private redrawNote(x: number, y: number, w: number, h: number, fill: string) { this.ctx.fillStyle = fill; // Round values to the nearest integer to avoid partially filled pixels. this.ctx.fillRect( Math.round(x), Math.round(y), Math.round(w), Math.round(h)); } } /** * @deprecated * Alias for PianoRollCanvasVisualizer to maintain backwards compatibility. */ export class Visualizer extends PianoRollCanvasVisualizer { constructor( sequence: INoteSequence, canvas: HTMLCanvasElement, config: VisualizerConfig = {}) { super(sequence, canvas, config); logging.log( 'mm.Visualizer is deprecated, and will be removed in a future \ version. Please use mm.PianoRollCanvasVisualizer instead', 'mm.Visualizer', logging.Level.WARN); } } /** * HTML/CSS key-value pairs. */ type DataAttribute = [string, any]; // tslint:disable-line:no-any type CSSProperty = [string, string | null]; /** * Abstract base class for a `NoteSequence` visualizer. */ export abstract class BaseSVGVisualizer extends BaseVisualizer { // This is the element used for drawing. You must set this property in // implementations of this class. protected svg: SVGSVGElement; protected drawn: boolean; /** * `SVGVisualizer` constructor. * * @param sequence The `NoteSequence` to be visualized. * @param svg The element where the visualization should be displayed. * @param config (optional) Visualization configuration options. */ constructor(sequence: INoteSequence, config: VisualizerConfig = {}) { super(sequence, config); this.drawn = false; } /** * Redraws the entire note sequence if it hasn't been drawn before, * optionally painting a note as active * @param activeNote (Optional) If specified, this `Note` will be painted * in the active color. * @param scrollIntoView (Optional) If specified and the note being * painted is offscreen, the parent container will be scrolled so that * the note is in view. * @returns The x position of the painted active note. Useful for * automatically advancing the visualization if the note was painted * outside of the screen. */ redraw(activeNote?: NoteSequence.INote, scrollIntoView?: boolean): number { if (!this.drawn) { this.draw(); } if (!activeNote) { return null; } // Remove the current active note, if one exists. this.unfillActiveRect(this.svg); let activeNotePosition; for (let i = 0; i < this.noteSequence.notes.length; i++) { const note = this.noteSequence.notes[i]; const isActive = activeNote && this.isPaintingActiveNote(note, activeNote); // We're only looking to re-paint the active notes. if (!isActive) { continue; } const el = this.svg.querySelector(`rect[data-index="${i}"]`); this.fillActiveRect(el, note); if (note === activeNote) { activeNotePosition = parseFloat(el.getAttribute('x')); } } this.scrollIntoViewIfNeeded(scrollIntoView, activeNotePosition); return activeNotePosition; } protected fillActiveRect(el: Element, note: NoteSequence.INote) { el.setAttribute('fill', this.getNoteFillColor(note, true)); el.classList.add('active'); } protected unfillActiveRect(svg: SVGSVGElement) { const els = svg.querySelectorAll('rect.active'); for (let i = 0; i < els.length; ++i) { const el = els[i]; const fill = this.getNoteFillColor( this.noteSequence.notes[parseInt(el.getAttribute('data-index'), 10)], false); el.setAttribute('fill', fill); el.classList.remove('active'); } } protected draw() { for (let i = 0; i < this.noteSequence.notes.length; i++) { const note = this.noteSequence.notes[i]; const size = this.getNotePosition(note, i); const fill = this.getNoteFillColor(note, false); const dataAttributes: DataAttribute[] = [ ['index', i], ['instrument', note.instrument], ['program', note.program], ['isDrum', note.isDrum === true], ['pitch', note.pitch], ]; const cssProperties: CSSProperty[] = [ ['--midi-velocity', String(note.velocity !== undefined ? note.velocity : 127)] ]; this.drawNote(size.x, size.y, size.w, size.h, fill, dataAttributes, cssProperties); } this.drawn = true; } private getNoteFillColor(note: NoteSequence.INote, isActive: boolean) { const opacityBaseline = 0.2; // Shift all the opacities up a little. const opacity = note.velocity ? note.velocity / 100 + opacityBaseline : 1; const fill = `rgba(${isActive ? this.config.activeNoteRGB : this.config.noteRGB}, ${opacity})`; return fill; } private drawNote( x: number, y: number, w: number, h: number, fill: string, dataAttributes: DataAttribute[], cssProperties: CSSProperty[]) { if (!this.svg) { return; } const rect: SVGRectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); rect.classList.add('note'); rect.setAttribute('fill', fill); // Round values to the nearest integer to avoid partially filled pixels. rect.setAttribute('x', `${Math.round(x)}`); rect.setAttribute('y', `${Math.round(y)}`); rect.setAttribute('width', `${Math.round(w)}`); rect.setAttribute('height', `${Math.round(h)}`); dataAttributes.forEach(([key, value]: DataAttribute) => { if (value !== undefined) { rect.dataset[key] = `${value}`; } }); cssProperties.forEach(([key, value]: CSSProperty) => { rect.style.setProperty(key, value); }); this.svg.appendChild(rect); } protected clear() { this.svg.innerHTML = ''; this.drawn = false; } public clearActiveNotes() { this.unfillActiveRect(this.svg); } } /** * Displays a pianoroll as an SVG. Pitches are the vertical axis and time is * the horizontal. When connected to a player, the visualizer can also highlight * the notes being currently played. * * Unlike PianoRollCanvasVisualizer which looks similar, PianoRollSVGVisualizer * does not redraw the entire sequence when activating a note. */ export class PianoRollSVGVisualizer extends BaseSVGVisualizer { /** * `PianoRollSVGVisualizer` constructor. * * @param sequence The `NoteSequence` to be visualized. * @param svg The element where the visualization should be displayed. * @param config (optional) Visualization configuration options. */ constructor( sequence: INoteSequence, svg: SVGSVGElement, config: VisualizerConfig = {}) { super(sequence, config); if (!(svg instanceof SVGSVGElement)) { throw new Error( 'This visualizer requires an <svg> element to display the visualization'); } this.svg = svg; this.parentElement = svg.parentElement; const size = this.getSize(); this.width = size.width; this.height = size.height; // Make sure that if we've used this svg element before, it's now emptied. this.svg.style.width = `${this.width}px`; this.svg.style.height = `${this.height}px`; this.clear(); this.draw(); } } export interface WaterfallVisualizerConfig extends VisualizerConfig { whiteNoteHeight?: number; whiteNoteWidth?: number; blackNoteHeight?: number; blackNoteWidth?: number; // Set this to true if you don't want to see the full 88 keys piano // keyboard, and only want to see the octaves used in the NoteSequence. showOnlyOctavesUsed?: boolean; } /** * Displays a waterfall pianoroll as an SVG, on top of a piano keyboard. When * connected to a player, the visualizer can also highlight the notes being * currently played, by letting them "fall down" onto the piano keys that * match them. By default, a keyboard with 88 keys will be drawn, but this can * be overriden with the `showOnlyOctavesUsed` config parameter, in which case * only the octaves present in the NoteSequence will be used. * * The DOM created by this element is: * <div> * <svg class="waterfall-notes"></svg> * </div> * <svg class="waterfall-piano"></svg> * * In particular, the `div` created needs to make some default * styling decisions (such as its height, to hide the overlow, and how much * it should be initially overflown), that we don't recommend you override since * it has a high chance of breaking how the visualizer works. * If you want to style the waterfall area, style the element that you * pass in the `WaterfallSVGVisualizer` constructor. For example, if you * want to resize the height (by default it is 200px), you can do: * * <style> * #waterfall { * height: 500px; * } * </style> * <div id="waterfall"></div> * <script> * const viz = new mm.WaterfallSVGVisualizer(seq, waterfall); * </script> * * If you want to style the piano keyboard, you can style the rects themselves: * * <style> * #waterfall svg.waterfall-notes rect.black { * fill: hotpink; * } * </style> */ export class WaterfallSVGVisualizer extends BaseSVGVisualizer { private NOTES_PER_OCTAVE = 12; private WHITE_NOTES_PER_OCTAVE = 7; private LOW_C = 24; private firstDrawnOctave = 0; private lastDrawnOctave = 6; protected svgPiano: SVGSVGElement; protected config: WaterfallVisualizerConfig; /** * `WaterfallSVGVisualizer` constructor. * * @param sequence The `NoteSequence` to be visualized. * @param parentElement The parent element that will contain the * visualization. * @param config (optional) Visualization configuration options. */ constructor( sequence: INoteSequence, parentElement: HTMLDivElement, config: WaterfallVisualizerConfig = {}) { super(sequence, config); if (!(parentElement instanceof HTMLDivElement)) { throw new Error( 'This visualizer requires a <div> element to display the visualization'); } // Some sensible defaults. this.config.whiteNoteWidth = config.whiteNoteWidth || 20; this.config.blackNoteWidth = config.blackNoteWidth || this.config.whiteNoteWidth * 2 / 3; this.config.whiteNoteHeight = config.whiteNoteHeight || 70; this.config.blackNoteHeight = config.blackNoteHeight || (2 * 70 / 3); this.config.showOnlyOctavesUsed = config.showOnlyOctavesUsed; this.setupDOM(parentElement); const size = this.getSize(); this.width = size.width; this.height = size.height; // Make sure that if we've used this svg element before, it's now emptied. this.svg.style.width = `${this.width}px`; this.svg.style.height = `${this.height}px`; this.svgPiano.style.width = `${this.width}px`; this.svgPiano.style.height = `${this.config.whiteNoteHeight}px`; // Add a little bit of padding to the right, so that the scrollbar // doesn't overlap the last note on the piano. this.parentElement.style.width = `${this.width + this.config.whiteNoteWidth}px`; this.parentElement.scrollTop = this.parentElement.scrollHeight; this.clear(); this.drawPiano(); this.draw(); } private setupDOM(container: HTMLDivElement) { this.parentElement = document.createElement('div'); this.parentElement.classList.add('waterfall-notes-container'); const height = Math.max(container.getBoundingClientRect().height, 200); // Height and padding-top must match for this to work. this.parentElement.style.paddingTop = `${height - this.config.whiteNoteHeight}px`; this.parentElement.style.height = `${height - this.config.whiteNoteHeight}px`; this.parentElement.style.boxSizing = 'border-box'; this.parentElement.style.overflowX = 'hidden'; this.parentElement.style.overflowY = 'auto'; this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); this.svgPiano = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); this.svg.classList.add('waterfall-notes'); this.svgPiano.classList.add('waterfall-piano'); this.parentElement.appendChild(this.svg); container.innerHTML = ''; container.appendChild(this.parentElement); container.appendChild(this.svgPiano); } /** * Redraws the entire note sequence if it hasn't been drawn before, * optionally painting a note as active * @param activeNote (Optional) If specified, this `Note` will be painted * in the active color. * @param scrollIntoView (Optional) If specified and the note being * painted is offscreen, the parent container will be scrolled so that * the note is in view. * @returns The x position of the painted active note. Useful for * automatically advancing the visualization if the note was painted * outside of the screen. */ redraw(activeNote?: NoteSequence.INote, scrollIntoView?: boolean): number { if (!this.drawn) { this.draw(); } if (!activeNote) { return null; } // Remove the current active note, if one exists. this.clearActiveNotes(); this.parentElement.style.paddingTop = this.parentElement.style.height; for (let i = 0; i < this.noteSequence.notes.length; i++) { const note = this.noteSequence.notes[i]; const isActive = activeNote && this.isPaintingActiveNote(note, activeNote); // We're only looking to re-paint the active notes. if (!isActive) { continue; } // Activate this note. const el = this.svg.querySelector(`rect[data-index="${i}"]`); this.fillActiveRect(el, note); // And on the keyboard. const key = this.svgPiano.querySelector(`rect[data-pitch="${note.pitch}"]`); this.fillActiveRect(key, note); if (note === activeNote) { const y = parseFloat(el.getAttribute('y')); const height = parseFloat(el.getAttribute('height')); // Scroll the waterfall. if (y < (this.parentElement.scrollTop - height)) { this.parentElement.scrollTop = y + height; } // This is the note we wanted to draw. return y; } } return null; } protected getSize(): {width: number; height: number} { this.updateMinMaxPitches(true); let whiteNotesDrawn = 52; // For a full piano. if (this.config.showOnlyOctavesUsed) { // Go through each C note and see which is the one right below and // above our sequence. let foundFirst = false, foundLast = false; for (let i = 1; i < 7; i++) { const c = this.LOW_C + this.NOTES_PER_OCTAVE * i; // Have we found the lowest pitch? if (!foundFirst && c > this.config.minPitch) { this.firstDrawnOctave = i - 1; foundFirst = true; } // Have we found the highest pitch? if (!foundLast && c > this.config.maxPitch) { this.lastDrawnOctave = i - 1; foundLast = true; } } whiteNotesDrawn = (this.lastDrawnOctave - this.firstDrawnOctave + 1) * this.WHITE_NOTES_PER_OCTAVE; } const width = whiteNotesDrawn * this.config.whiteNoteWidth; // Calculate a nice width based on the length of the sequence we're // playing. // Warn if there's no totalTime or quantized steps set, since it leads // to a bad size. const endTime = this.noteSequence.totalTime; if (!endTime) { throw new Error( 'The sequence you are using with the visualizer does not have a ' + 'totalQuantizedSteps or totalTime ' + 'field set, so the visualizer can\'t be horizontally ' + 'sized correctly.'); } const height = Math.max(endTime * this.config.pixelsPerTimeStep, MIN_NOTE_LENGTH); return {width, height}; } protected getNotePosition(note: NoteSequence.INote, noteIndex: number): {x: number; y: number, w: number, h: number} { const rect = this.svgPiano.querySelector(`rect[data-pitch="${note.pitch}"]`); if (!rect) { return null; } // Size of this note. const len = this.getNoteEndTime(note) - this.getNoteStartTime(note); const x = Number(rect.getAttribute('x')); const w = Number(rect.getAttribute('width')); const h = Math.max( this.config.pixelsPerTimeStep * len - this.config.noteSpacing, MIN_NOTE_LENGTH); // The svg' y=0 is at the top, but a smaller pitch is actually // lower, so we're kind of painting backwards. const y = this.height - (this.getNoteStartTime(note) * this.config.pixelsPerTimeStep) - h; return {x, y, w, h}; } private drawPiano() { this.svgPiano.innerHTML = ''; const blackNoteOffset = this.config.whiteNoteWidth - this.config.blackNoteWidth / 2; const blackNoteIndexes = [1, 3, 6, 8, 10]; // Dear future reader: I am sure there is a better way to do this, but // splitting it up makes it more readable and maintainable in case there's // an off by one key error somewhere. // Each note has an pitch. Pianos start on pitch 21 and end on 108. // First draw all the white notes, in this order: // - if we're using all the octaves, pianos start on an A (so draw A, // B) // - ... the rest of the white keys per octave // - if we started on an A, we end on an extra C. // Then draw all the black notes (so that these rects sit on top): // - if the piano started on an A, draw the A sharp // - ... the rest of the black keys per octave. let x = 0; let currentPitch = 0; if (this.config.showOnlyOctavesUsed) { // Starting on a C, and a bunch of octaves up. currentPitch = (this.firstDrawnOctave * this.NOTES_PER_OCTAVE) + this.LOW_C; } else { // Starting on the lowest A and B. currentPitch = this.LOW_C - 3; this.drawWhiteKey(currentPitch, x); this.drawWhiteKey(currentPitch + 2, this.config.whiteNoteWidth); currentPitch += 3; x = 2 * this.config.whiteNoteWidth; } // Draw the rest of the white notes. for (let o = this.firstDrawnOctave; o <= this.lastDrawnOctave; o++) { for (let i = 0; i < this.NOTES_PER_OCTAVE; i++) { // Black keys come later. if (blackNoteIndexes.indexOf(i) === -1) { this.drawWhiteKey(currentPitch, x); x += this.config.whiteNoteWidth; } currentPitch++; } } if (this.config.showOnlyOctavesUsed) { // Starting on a C, and a bunch of octaves up. currentPitch = (this.firstDrawnOctave * this.NOTES_PER_OCTAVE) + this.LOW_C; x = -this.config.whiteNoteWidth; } else { // Before we reset, add an extra C at the end because pianos. this.drawWhiteKey(currentPitch, x); // This piano started on an A, so draw the A sharp black key. currentPitch = this.LOW_C - 3; this.drawBlackKey(currentPitch + 1, blackNoteOffset); currentPitch += 3; // Next one is the LOW_C. x = this.config.whiteNoteWidth; } // Draw the rest of the black notes. for (let o = this.firstDrawnOctave; o <= this.lastDrawnOctave; o++) { for (let i = 0; i < this.NOTES_PER_OCTAVE; i++) { if (blackNoteIndexes.indexOf(i) !== -1) { this.drawBlackKey(currentPitch, x + blackNoteOffset); } else { x += this.config.whiteNoteWidth; } currentPitch++; } } } private drawWhiteKey(index: number, x: number) { const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); rect.dataset.pitch = String(index); rect.setAttribute('x', String(x)); rect.setAttribute('y', '0'); rect.setAttribute('width', String(this.config.whiteNoteWidth)); rect.setAttribute('height', String(this.config.whiteNoteHeight)); rect.setAttribute('fill', 'white'); rect.setAttribute('original-fill', 'white'); rect.setAttribute('stroke', 'black'); rect.setAttribute('stroke-width', '3px'); rect.classList.add('white'); this.svgPiano.appendChild(rect); return rect; } private drawBlackKey(index: number, x: number) { const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); rect.dataset.pitch = String(index); rect.setAttribute('x', String(x)); rect.setAttribute('y', '0'); rect.setAttribute('width', String(this.config.blackNoteWidth)); rect.setAttribute('height', String(this.config.blackNoteHeight)); rect.setAttribute('fill', 'black'); rect.setAttribute('original-fill', 'black'); rect.setAttribute('stroke', 'black'); rect.setAttribute('stroke-width', '3px'); rect.classList.add('black'); this.svgPiano.appendChild(rect); return rect; } public clearActiveNotes() { super.unfillActiveRect(this.svg); // And the piano. const els = this.svgPiano.querySelectorAll('rect.active'); for (let i = 0; i < els.length; ++i) { const el = els[i]; el.setAttribute('fill', el.getAttribute('original-fill')); el.classList.remove('active'); } } } /** * Enumeration of different ways of horizontal score scrolling, like paginated * (PAGE is default value), note by note (NOTE) or in packed chunks by doing * scroll just on bar starting (BAR). */ export enum ScrollType { PAGE = 0, NOTE = 1, BAR = 2 } /** * An interface for providing extra configurable properties to a Visualizer * extending the basic configurable properties of `VisualizerConfig`. * * @param defaultKey The musical key the score must use to adapt the score to * the right accidentals. It can be overwritten with * `NoteSequence.keySignatures` value at time or step 0. If not assigned it * will be asumed C key. * @param instruments The subset of the `NoteSequence` instrument track * numbers which should be merged and displayed. If not assigned or equal to [] * it will be used all instruments altogether. * @param scrollType Sets scrolling to follow scoreplaying in different ways * according to `ScrollType` enum values. */ export interface StaffSVGVisualizerConfig extends VisualizerConfig { defaultKey?: number; instruments?: number[]; scrollType?: ScrollType; } /** * Displays a `NoteSecuence` as a staff on a given SVG. Staff is scaled to fit * vertically `config.noteHeight` and note horizontal position can behave in * two different ways: If `config.pixelsPerTimeStep` is greater than zero, * horizontal position will be proportional to its starting time, allowing to * pile several instances for different voices (parts). Otherwise, resulting * staff will display notes in a compact form, using minimum horizontal space * between musical symbols as regular paper staff does. * * Clef, key and time signature will be displayed at the leftmost side and the * rest of the staff will scroll under this initial signature area * accordingly. In case of proportional note positioning, given it starts at * pixel zero, the signature area will blink meanwhile it collides with * initial active notes. Key and time signature changes will be shown * accordingly through score. * * New configuration features have been introduced through * `StaffSVGVisualizerConfig` over basic `VisualizerConfig`. * * When connected to a player, the visualizer can also highlight * the notes being currently played. * * You can find more info at: * * https://github.com/rogerpasky/staffrender-magentaviewer */ export class StaffSVGVisualizer extends BaseVisualizer { private render: sr.StaffSVGRender; // The actual render. private instruments: number[]; // Instruments filter to be rendered. private drawnNotes: number; // Number of drawn notes. Will redraw if changed. /** * `StaffSVGVisualizer` constructor. * * @param sequence The `NoteSequence` to be visualized. * @param div The element where the visualization should be displayed. * @param config (optional) Visualization configuration options. */ constructor( sequence: INoteSequence, div: HTMLDivElement, config: StaffSVGVisualizerConfig = {}) { super(sequence, config); if ( // Overwritting super() value. Compact visualization as default. config.pixelsPerTimeStep === undefined || config.pixelsPerTimeStep <= 0) { this.config.pixelsPerTimeStep = 0; } this.instruments = config.instruments || []; this.render = new sr.StaffSVGRender( this.getScoreInfo(sequence), { noteHeight: this.config.noteHeight, noteSpacing: this.config.noteSpacing, pixelsPerTimeStep: this.config.pixelsPerTimeStep, noteRGB: this.config.noteRGB, activeNoteRGB: this.config.activeNoteRGB, defaultKey: config.defaultKey || 0, scrollType: config.scrollType || ScrollType.PAGE, }, div); this.drawnNotes = sequence.notes.length; this.clear(); this.redraw(); } /** * Clears and resets the visualizer object for further redraws from scratch. */ protected clear() { this.render.clear(); } /** * Redraws the entire `noteSequence` in a staff if no `activeNote` is given, * highlighting on and off the appropriate notes otherwise. Should the * `noteSequence` had changed adding more notes at the end, calling this * method again would complete the redrawing from the very last note it was * drawn, maintaining the active note and the scroll position as they were. * This is handy for incremental compositions. Given the complexity of * adaption to a modified score, modifyied notes previously drawn will be * ignored (you can always `clear()` and `redraw()` for a full redraw). * Please have in mind `mm.Player` does not have this incremental capability * so, once the player had started, it will go on ignoring the changes. * * @param activeNote (Optional) If specified, this `Note` will be painted * in the active color and there won't be an actual redrawing, but a * re-colouring of the involved note heads, accidentals, dots and ties * (activated and de-activated ones). Otherwise, all musical symbols which * were not processed yet will be drawn to complete the score. * @param scrollIntoView (Optional) If specified and the active note to be * highlighted is not visualized in the container DIV, the latter will be * scrolled so that the note is viewed in the right place. This can be * altered by `AdvancedVisualizerConfig.scrollType`. * @returns The x position of the highlighted active note relative to the * beginning of the DIV, or -1 if there wasn't any given active note. Useful * for automatically advancing the visualization if needed. */ public redraw(activeNote?: NoteSequence.INote, scrollIntoView?: boolean): number { if (this.drawnNotes !== this.noteSequence.notes.length) { this.render.scoreInfo = this.getScoreInfo(this.noteSequence); } const activeNoteInfo = activeNote ? this.getNoteInfo(activeNote) : undefined; return this.render.redraw(activeNoteInfo, scrollIntoView); } private isNoteInInstruments(note: NoteSequence.INote): boolean { if (note.instrument === undefined || this.instruments.length === 0) { return true; // No instrument information in note means no filtering. } else { // Instrument filtering return this.instruments.indexOf(note.instrument) >= 0; } } private timeToQuarters(time: number): number { const q = time * this.noteSequence.tempos[0].qpm / 60; return Math.round(q * 16) / 16; // Current resolution = 1/16 quarter. } private getNoteInfo(note: NoteSequence.INote): sr.NoteInfo { const startQ = this.timeToQuarters(note.startTime); const endQ = this.timeToQuarters(note.endTime); return { start: startQ, length: endQ - startQ, pitch: note.pitch, intensity: note.velocity }; } private getScoreInfo(sequence: INoteSequence): sr.ScoreInfo { const notesInfo: sr.NoteInfo[] = []; sequence.notes.forEach((note: NoteSequence.INote) => { if (this.isNoteInInstruments(note)) { notesInfo.push(this.getNoteInfo(note)); } }); return { notes: notesInfo, tempos: sequence.tempos ? sequence.tempos.map((t: NoteSequence.ITempo) => { return {start: this.timeToQuarters(t.time), qpm: t.qpm}; }) : [], keySignatures: sequence.keySignatures ? sequence.keySignatures.map((ks: NoteSequence.IKeySignature) => { return {start: this.timeToQuarters(ks.time), key: ks.key}; }) : [], timeSignatures: sequence.timeSignatures ? sequence.timeSignatures.map((ts: NoteSequence.ITimeSignature) => { return { start: this.timeToQuarters(ts.time), numerator: ts.numerator, denominator: ts.denominator }; }) : [] }; } public clearActiveNotes() { this.redraw(); } }
the_stack
import React, { PropsWithChildren, useEffect } from "react"; import { CardProps, getCardProps, CardFooter } from "@codestream/webview/src/components/Card"; import { DidChangeObservabilityDataNotificationType, GetNewRelicAssigneesRequestType, ResolveStackTraceResponse } from "@codestream/protocols/agent"; import { MinimumWidthCard, Header, MetaSection, Meta, MetaLabel, MetaSectionCollapsed, HeaderActions, BigTitle } from "../Codemark/BaseCodemark"; import { CSUser, CSCodeError, CSPost } from "@codestream/protocols/api"; import { CodeStreamState } from "@codestream/webview/store"; import { useSelector, useDispatch } from "react-redux"; import Icon from "../Icon"; import Tooltip from "../Tooltip"; import { replaceHtml, emptyArray } from "@codestream/webview/utils"; import { useDidMount } from "@codestream/webview/utilities/hooks"; import { HostApi } from "../.."; import { api, fetchCodeError, fetchErrorGroup, jumpToStackLine, PENDING_CODE_ERROR_ID_PREFIX, upgradePendingCodeError } from "@codestream/webview/store/codeErrors/actions"; import { DelayedRender } from "@codestream/webview/Container/DelayedRender"; import { getCodeError, getCodeErrorCreator } from "@codestream/webview/store/codeErrors/reducer"; import MessageInput, { AttachmentField } from "../MessageInput"; import styled from "styled-components"; import { getTeamMates, findMentionedUserIds, isCurrentUserInternal, getTeamMembers } from "@codestream/webview/store/users/reducer"; import { createPost, markItemRead } from "../actions"; import { getThreadPosts } from "@codestream/webview/store/posts/reducer"; import { DropdownButton, DropdownButtonItems } from "../DropdownButton"; import { RepliesToPost } from "../Posts/RepliesToPost"; import Menu from "../Menu"; import { confirmPopup } from "../Confirm"; import { Link } from "../Link"; import { Dispatch } from "@codestream/webview/store/common"; import { Loading } from "@codestream/webview/Container/Loading"; import { getPost } from "../../store/posts/reducer"; import { AddReactionIcon, Reactions } from "../Reactions"; import { Attachments } from "../Attachments"; import { RepoMetadata } from "../Review"; import Timestamp from "../Timestamp"; import { Button } from "@codestream/webview/src/components/Button"; import { ButtonRow, Dialog } from "@codestream/webview/src/components/Dialog"; import { Headshot } from "@codestream/webview/src/components/Headshot"; import { SharingModal } from "../SharingModal"; import { PROVIDER_MAPPINGS } from "../CrossPostIssueControls/types"; import { NewRelicErrorGroup } from "@codestream/protocols/agent"; import { isConnected } from "@codestream/webview/store/providers/reducer"; import { Modal } from "../Modal"; import { ConfigureNewRelic } from "../ConfigureNewRelic"; import { ConditionalNewRelic } from "./ConditionalComponent"; import { invite } from "../actions"; interface SimpleError { /** * Error message from the server */ message: string; /** * Typed error message (to switch off of, etc.) */ type?: string; } export interface BaseCodeErrorProps extends CardProps { codeError: CSCodeError; errorGroup?: NewRelicErrorGroup; parsedStack?: ResolveStackTraceResponse; post?: CSPost; repoInfo?: RepoMetadata; headerError?: SimpleError; currentUserId?: string; collapsed?: boolean; isFollowing?: boolean; assignees?: CSUser[]; renderFooter?: ( footer: typeof CardFooter, inputContainer?: typeof ComposeWrapper ) => React.ReactNode; setIsEditing: Function; onRequiresCheckPreconditions?: Function; stackFrameClickDisabled?: boolean; } export interface BaseCodeErrorHeaderProps { codeError: CSCodeError; errorGroup?: NewRelicErrorGroup; post?: CSPost; collapsed?: boolean; isFollowing?: boolean; assignees?: CSUser[]; setIsEditing: Function; } export interface BaseCodeErrorMenuProps { codeError: CSCodeError; errorGroup?: NewRelicErrorGroup; setIsEditing: Function; collapsed?: boolean; } const ComposeWrapper = styled.div.attrs(() => ({ className: "compose codemark-compose" }))` &&& { padding: 0 !important; } .message-input#input-div { max-width: none !important; } `; export const ExpandedAuthor = styled.div` width: 100%; color: var(--text-color-subtle); white-space: normal; `; export const Description = styled.div` margin-bottom: 15px; `; const ClickLines = styled.div` padding: 1px !important; &:focus { border: none; outline: none; } `; const DisabledClickLine = styled.div` color: var(--text-color); opacity: 0.4; text-align: right; direction: rtl; text-overflow: ellipsis; overflow: hidden; padding: 2px 0px 2px 0px; `; const ClickLine = styled.div` position: relative; cursor: pointer; padding: 2px 0px 2px 0px; text-align: right; direction: rtl; text-overflow: ellipsis; overflow: hidden; :hover { color: var(--text-color-highlight); background: var(--app-background-color-hover); opacity: 1; } `; const DataRow = styled.div` display: flex; align-items: center; `; const DataLabel = styled.div` margin-right: 5px; `; const DataValue = styled.div` color: var(--text-color-subtle); `; const ApmServiceTitle = styled.span` a { color: var(--text-color-highlight); text-decoration: none; } .open-external { margin-left: 5px; font-size: 12px; visibility: hidden; color: var(--text-color-highlight); } &:hover .open-external { visibility: visible; } padding-left: 5px; `; export const Message = styled.div` width: 100%; margin-bottom: 10px; display: flex; align-items: flex-start; font-size: 12px; `; const ALERT_SEVERITY_COLORS = { "": "#9FA5A5", CRITICAL: "#F5554B", NOT_ALERTING: "#01B076", NOT_CONFIGURED: "#9FA5A5", WARNING: "#F0B400", // if not connected, we're unknown UNKNOWN: "transparent" }; /** * States are from NR */ const STATES_TO_ACTION_STRINGS = { RESOLVED: "Resolve", IGNORED: "Ignore", UNRESOLVED: "Unresolve" }; /** * States are from NR */ const STATES_TO_DISPLAY_STRINGS = { RESOLVED: "Resolved", IGNORED: "Ignored", UNRESOLVED: "Unresolved", // if not connected, we're unknown, just say "Status" UNKNOWN: "Status" }; // if child props are passed in, we assume they are the action buttons/menu for the header export const BaseCodeErrorHeader = (props: PropsWithChildren<BaseCodeErrorHeaderProps>) => { const { codeError, collapsed } = props; const dispatch = useDispatch<any>(); const derivedState = useSelector((state: CodeStreamState) => { return { isConnectedToNewRelic: isConnected(state, { id: "newrelic*com" }), codeErrorCreator: getCodeErrorCreator(state), isCurrentUserInternal: isCurrentUserInternal(state), ideName: encodeURIComponent(state.ide.name || ""), teamMembers: getTeamMembers(state), emailAddress: state.session.userId ? state.users[state.session.userId]?.email : "" }; }); const [items, setItems] = React.useState<DropdownButtonItems[]>([]); const [states, setStates] = React.useState<DropdownButtonItems[] | undefined>(undefined); const [openConnectionModal, setOpenConnectionModal] = React.useState(false); const [isStateChanging, setIsStateChanging] = React.useState(false); const [isAssigneeChanging, setIsAssigneeChanging] = React.useState(false); const notify = (emailAddress?: string) => { // if no email address or it's you if (!emailAddress || derivedState.emailAddress.toLowerCase() === emailAddress.toLowerCase()) { HostApi.instance.emit(DidChangeObservabilityDataNotificationType.method, { type: "Assignment" }); } }; type AssigneeType = "Teammate" | "Invitee"; const setAssignee = async (emailAddress: string, assigneeType: AssigneeType) => { if (!props.errorGroup) return; const _setAssignee = async (type: AssigneeType) => { HostApi.instance.track("Error Assigned", { "Error Group ID": props.errorGroup?.guid, "NR Account ID": props.errorGroup?.accountId, Assignment: props.errorGroup?.assignee ? "Change" : "New", "Assignee Type": type }); setIsAssigneeChanging(true); await dispatch(upgradePendingCodeError(props.codeError.id, "Assignee Change")); await dispatch( api("setAssignee", { errorGroupGuid: props.errorGroup?.guid!, emailAddress: emailAddress }) ); notify(emailAddress); setTimeout(_ => { setIsAssigneeChanging(false); }, 1); }; // if it's me, or someone that is already on the team -- just assign them without asking to invite if ( derivedState.emailAddress.toLowerCase() === emailAddress.toLowerCase() || derivedState.teamMembers.find(_ => _.email.toLowerCase() === emailAddress.toLowerCase()) ) { _setAssignee(assigneeType); return; } confirmPopup({ title: "Invite to CodeStream?", message: ( <span> Assign the error to <b>{emailAddress}</b> and invite them to join CodeStream </span> ), centered: true, buttons: [ { label: "Cancel", className: "control-button btn-secondary" }, { label: "Invite", className: "control-button", wait: true, action: () => { dispatch( invite({ email: emailAddress, inviteType: "error" }) ); // "upgrade" them to an invitee _setAssignee("Invitee"); } } ] }); }; const removeAssignee = async ( e: React.SyntheticEvent<Element, Event>, emailAddress: string | undefined, userId: number | undefined ) => { if (!props.errorGroup) return; // dont allow this to bubble to the parent item which would call setAssignee e.stopPropagation(); setIsAssigneeChanging(true); await dispatch(upgradePendingCodeError(props.codeError.id, "Assignee Change")); await dispatch( api("removeAssignee", { errorGroupGuid: props.errorGroup?.guid!, emailAddress: emailAddress, userId: userId }) ); notify(emailAddress); setTimeout(_ => { setIsAssigneeChanging(false); }, 1); }; const buildStates = () => { if (collapsed) return; if (derivedState.isConnectedToNewRelic && props.errorGroup?.states) { // only show states that aren't the current state setStates( props.errorGroup?.states .filter(_ => (props.errorGroup?.state ? _ !== props.errorGroup.state : true)) .map(_ => { return { key: _, label: STATES_TO_ACTION_STRINGS[_], action: async e => { setIsStateChanging(true); await dispatch(upgradePendingCodeError(props.codeError.id, "Status Change")); await dispatch( api("setState", { errorGroupGuid: props.errorGroup?.guid!, state: _ }) ); notify(); setIsStateChanging(false); HostApi.instance.track("Error Status Changed", { "Error Group ID": props.errorGroup?.guid, "NR Account ID": props.errorGroup?.accountId, "Error Status": STATES_TO_ACTION_STRINGS[_] }); } }; }) as DropdownButtonItems[] ); } else { setStates([ { key: "UNKNOWN", label: STATES_TO_DISPLAY_STRINGS["UNKNOWN"], action: e => { setOpenConnectionModal(true); } } as DropdownButtonItems ]); } }; const buildAssignees = async () => { if (collapsed) return; let assigneeItems: DropdownButtonItems[] = [{ type: "search", label: "", key: "search" }]; let assigneeEmail; if (props.errorGroup && props.errorGroup.assignee) { const a = props.errorGroup.assignee; const label = a.name || a.email; assigneeEmail = a.email; assigneeItems.push({ label: "-", key: "sep-assignee" }); assigneeItems.push({ label: ( <span style={{ fontSize: "10px", fontWeight: "bold", opacity: 0.7 }}> CURRENT ASSIGNEE </span> ), noHover: true, disabled: true }); assigneeItems.push({ icon: <Headshot size={16} display="inline-block" person={{ email: a.email }} />, key: a.email, label: label, subtext: label === a.email ? undefined : a.email, floatRight: { label: ( <Icon name="x" onClick={e => { removeAssignee(e, a.email, a.id); }} /> ) } }); } if (derivedState.isConnectedToNewRelic) { let { users } = await HostApi.instance.send(GetNewRelicAssigneesRequestType, {}); if (assigneeEmail) { users = users.filter(_ => _.email !== assigneeEmail); } let usersFromGit = users.filter(_ => _.group === "GIT"); if (usersFromGit.length) { // take no more than 100 usersFromGit = usersFromGit.slice(0, 100); assigneeItems.push({ label: "-", key: "sep-git" }); assigneeItems.push({ label: ( <span style={{ fontSize: "10px", fontWeight: "bold", opacity: 0.7 }}> SUGGESTIONS FROM GIT </span> ), noHover: true, disabled: true }); assigneeItems = assigneeItems.concat( usersFromGit.map(_ => { const label = _.displayName || _.email; return { icon: <Headshot size={16} display="inline-block" person={{ email: _.email }} />, key: _.id || `git-${_.email}`, label: label, searchLabel: _.displayName || _.email, subtext: label === _.email ? undefined : _.email, action: () => setAssignee(_.email, "Teammate") }; }) ); } const usersFromGitByEmail = usersFromGit.map(_ => _.email); // only show users not already shown let usersFromCodeStream = derivedState.teamMembers.filter( _ => !usersFromGitByEmail.includes(_.email) ); if (assigneeEmail) { // if we have an assignee don't re-include them here usersFromCodeStream = usersFromCodeStream.filter(_ => _.email !== assigneeEmail); } if (usersFromCodeStream.length) { assigneeItems.push({ label: "-", key: "sep-nr" }); assigneeItems.push({ label: ( <span style={{ fontSize: "10px", fontWeight: "bold", opacity: 0.7 }}> OTHER TEAMMATES </span> ), noHover: true, disabled: true }); assigneeItems = assigneeItems.concat( usersFromCodeStream.map(_ => { const label = _.fullName || _.email; return { icon: <Headshot size={16} display="inline-block" person={{ email: _.email }} />, key: _.id, label: _.fullName || _.email, searchLabel: _.fullName || _.username, subtext: label === _.email ? undefined : _.email, action: () => setAssignee(_.email, "Teammate") }; }) ); } setItems(assigneeItems); } else { setItems([{ label: "-", key: "none" }]); } }; useEffect(() => { buildAssignees(); }, [props.errorGroup, props.errorGroup?.assignee, derivedState.isConnectedToNewRelic]); useEffect(() => { buildStates(); }, [props.errorGroup, props.errorGroup?.state, derivedState.isConnectedToNewRelic]); useDidMount(() => { if (collapsed) return; buildStates(); buildAssignees(); }); const title = (props.codeError?.title || "").split(/(\.)/).map(part => ( <> {part} <wbr /> </> )); return ( <> {openConnectionModal && ( <Modal translucent onClose={() => { setOpenConnectionModal(false); }} > <Dialog narrow title=""> <div className="embedded-panel"> <ConfigureNewRelic headerChildren={ <> <div className="panel-header" style={{ background: "none" }}> <span className="panel-title">Connect to New Relic</span> </div> <div style={{ textAlign: "center" }}> Working with errors requires a connection to your New Relic account. If you don't have one, get a teammate{" "} {derivedState.codeErrorCreator ? `like ${derivedState.codeErrorCreator.fullName || derivedState.codeErrorCreator.username} ` : ""} to invite you. </div> </> } disablePostConnectOnboarding={true} showSignupUrl={false} providerId={"newrelic*com"} onClose={e => { setOpenConnectionModal(false); }} onSubmited={async e => { setOpenConnectionModal(false); }} originLocation={"Open in IDE Flow"} /> </div> </Dialog> </Modal> )} {!collapsed && ( <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "space-between" }} > <div style={{ paddingTop: "2px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", marginBottom: "10px" }} > <div style={{ display: "inline-block", width: "10px", height: "10px", border: derivedState.isConnectedToNewRelic ? "0px" : `1px solid ${ALERT_SEVERITY_COLORS["NOT_CONFIGURED"]}`, backgroundColor: ALERT_SEVERITY_COLORS[props.errorGroup?.entityAlertingSeverity || "UNKNOWN"], margin: "0 5px 0 6px" }} /> <ApmServiceTitle> <Tooltip title="Open Entity on New Relic" placement="bottom" delay={1}> <span> <ConditionalNewRelic connected={ <> {props.errorGroup && ( <> <Link href={props.errorGroup.entityUrl}> <span className="subtle">{props.errorGroup.entityName}</span> </Link>{" "} <Icon name="link-external" className="open-external"></Icon> </> )} </> } disconnected={ <> {!props.errorGroup && props.codeError && ( <> <Link href="#" onClick={e => { e.preventDefault(); setOpenConnectionModal(true); }} > <span className="subtle"> {props.codeError?.objectInfo?.entityName || "Service"} </span> </Link>{" "} <Icon name="link-external" className="open-external"></Icon> </> )} </> } /> </span> </Tooltip> </ApmServiceTitle> </div> <div style={{ marginLeft: "auto", alignItems: "center", whiteSpace: "nowrap" }}> <> <DropdownButton items={items} preventStopPropagation={!derivedState.isConnectedToNewRelic} // onChevronClick={e => // !derivedState.isConnectedToNewRelic ? setOpenConnectionModal(true) : undefined // } variant="secondary" size="compact" noChevronDown={true} > <ConditionalNewRelic connected={ <> {props.errorGroup && ( <> {isAssigneeChanging ? ( <Icon name="sync" className="spin" /> ) : ( <> {/* no assignee */} {!props.errorGroup.assignee || (!props.errorGroup.assignee.email && !props.errorGroup.assignee.id) ? ( <Icon name="person" /> ) : ( <Headshot size={16} display="inline-block" className="no-right-margin" person={{ fullName: props.errorGroup.assignee.name, email: props.errorGroup.assignee.email }} /> )} </> )} </> )} </> } disconnected={ <Icon style={{ cursor: "pointer" }} name="person" onClick={e => { setOpenConnectionModal(true); }} /> } /> </DropdownButton> </> {states && ( <> <div style={{ display: "inline-block", width: "5px" }} /> <DropdownButton items={states} selectedKey={props.errorGroup?.state || "UNKNOWN"} isLoading={isStateChanging} variant="secondary" size="compact" preventStopPropagation={!derivedState.isConnectedToNewRelic} onButtonClicked={ derivedState.isConnectedToNewRelic ? undefined : e => { e.preventDefault(); e.stopPropagation(); setOpenConnectionModal(true); } } wrap > {STATES_TO_DISPLAY_STRINGS[props.errorGroup?.state || "UNKNOWN"]} </DropdownButton> </> )} <> {props.post && <AddReactionIcon post={props.post} className="in-review" />} {props.children || (codeError && ( <> <div style={{ display: "inline-block", width: "5px" }} /> <BaseCodeErrorMenu codeError={codeError} errorGroup={props.errorGroup} collapsed={collapsed} setIsEditing={props.setIsEditing} /> </> ))} </> </div> </div> )} <Header> <Icon name="alert" className="type" /> <BigTitle> <HeaderActions> {props.post && <AddReactionIcon post={props.post} className="in-review" />} </HeaderActions> <ApmServiceTitle> <ConditionalNewRelic connected={ <Tooltip title={ derivedState.isCurrentUserInternal ? props.codeError?.id : props.errorGroup?.errorGroupUrl && props.codeError?.title ? "Open Error on New Relic" : "" } placement="bottom" delay={1} > {props.errorGroup?.errorGroupUrl && props.codeError.title ? ( <span> <Link href={ props.errorGroup.errorGroupUrl! + `&utm_source=codestream&utm_medium=ide-${derivedState.ideName}&utm_campaign=error_group_link` } > {title} </Link>{" "} <Icon name="link-external" className="open-external"></Icon> </span> ) : ( <span>{title}</span> )} </Tooltip> } disconnected={ <> {props.codeError && !props.errorGroup?.errorGroupUrl && ( <span> <Link href="#" onClick={e => { e.preventDefault(); setOpenConnectionModal(true); }} > {title} </Link>{" "} <Icon name="link-external" className="open-external"></Icon> </span> )} </> } /> </ApmServiceTitle> </BigTitle> </Header> </> ); }; export const BaseCodeErrorMenu = (props: BaseCodeErrorMenuProps) => { const { codeError, collapsed } = props; const dispatch = useDispatch(); const derivedState = useSelector((state: CodeStreamState) => { const post = codeError && codeError.postId ? getPost(state.posts, codeError!.streamId, codeError.postId) : undefined; return { post, currentUserId: state.session.userId!, currentUser: state.users[state.session.userId!], author: props.codeError ? state.users[props.codeError.creatorId] : undefined, userIsFollowing: props.codeError ? (props.codeError.followerIds || []).includes(state.session.userId!) : [] }; }); const [isLoading, setIsLoading] = React.useState(false); const [menuState, setMenuState] = React.useState<{ open: boolean; target?: any }>({ open: false, target: undefined }); const [shareModalOpen, setShareModalOpen] = React.useReducer(open => !open, false); const permalinkRef = React.useRef<HTMLTextAreaElement>(null); const menuItems = React.useMemo(() => { let items: any[] = []; if (props.errorGroup) { items.push({ label: "Refresh", icon: <Icon name="refresh" />, key: "refresh", action: async () => { setIsLoading(true); await dispatch(fetchErrorGroup(props.codeError)); setIsLoading(false); } }); } if (props.codeError?.id?.indexOf(PENDING_CODE_ERROR_ID_PREFIX) === -1) { // don't add the ability to share for pending codeErrors items.push({ label: "Share", icon: <Icon name="share" />, key: "share", action: () => setShareModalOpen(true) }); } items = items.concat([ { label: "Copy Link", icon: <Icon name="copy" />, key: "copy-permalink", action: () => { if (permalinkRef && permalinkRef.current) { permalinkRef.current.select(); document.execCommand("copy"); } } } // commented out until we have back-end support as per // https://trello.com/c/MhAWDZNF/6886-remove-delete-and-follow-unfollow // { // label: derivedState.userIsFollowing ? "Unfollow" : "Follow", // key: "toggle-follow", // icon: <Icon name="eye" />, // action: () => { // const value = !derivedState.userIsFollowing; // const changeType = value ? "Followed" : "Unfollowed"; // HostApi.instance.send(FollowCodeErrorRequestType, { // id: codeError.id, // value // }); // HostApi.instance.track("Notification Change", { // Change: `Code Error ${changeType}`, // "Source of Change": "Code Error menu" // }); // } // } ]); // commented out until we have back-end support as per // https://trello.com/c/MhAWDZNF/6886-remove-delete-and-follow-unfollow // if (codeError?.creatorId === derivedState.currentUser.id) { // items.push({ // label: "Delete", // icon: <Icon name="trash" />, // action: () => { // confirmPopup({ // title: "Are you sure?", // message: "Deleting a code error cannot be undone.", // centered: true, // buttons: [ // { label: "Go Back", className: "control-button" }, // { // label: "Delete Code Error", // className: "delete", // wait: true, // action: () => { // dispatch(deleteCodeError(codeError.id)); // dispatch(setCurrentCodeError()); // } // } // ] // }); // } // }); // } return items; }, [codeError, collapsed, props.errorGroup]); if (shareModalOpen) return ( <SharingModal codeError={props.codeError!} post={derivedState.post} onClose={() => setShareModalOpen(false)} /> ); if (collapsed) { return ( <DropdownButton size="compact" items={menuItems}> <textarea readOnly key="permalink-offscreen" ref={permalinkRef} value={codeError?.permalink} style={{ position: "absolute", left: "-9999px" }} /> </DropdownButton> ); } return ( <> <DropdownButton items={menuItems} selectedKey={props.errorGroup?.state || "UNKNOWN"} isLoading={isLoading} variant="secondary" size="compact" noChevronDown wrap > <Icon loading={isLoading} name="kebab-horizontal" /> </DropdownButton> <textarea readOnly key="permalink-offscreen" ref={permalinkRef} value={codeError?.permalink} style={{ position: "absolute", left: "-9999px" }} /> {menuState.open && ( <Menu target={menuState.target} action={() => setMenuState({ open: false })} items={menuItems} align="dropdownRight" /> )} </> ); }; const BaseCodeError = (props: BaseCodeErrorProps) => { const dispatch = useDispatch(); const derivedState = useSelector((state: CodeStreamState) => { const codeError = state.codeErrors[props.codeError.id] || props.codeError; const codeAuthorId = (props.codeError.codeAuthorIds || [])[0]; return { providers: state.providers, isInVscode: state.ide.name === "VSC", author: props.codeError ? state.users[props.codeError.creatorId] : undefined, codeAuthor: state.users[codeAuthorId || props.codeError?.creatorId], codeError, errorGroup: props.errorGroup, errorGroupIsLoading: (state.codeErrors.errorGroups[codeError.objectId] as any)?.isLoading, currentCodeErrorData: state.context.currentCodeErrorData }; }); const renderedFooter = props.renderFooter && props.renderFooter(CardFooter, ComposeWrapper); const { codeError, errorGroup } = derivedState; const [currentSelectedLine, setCurrentSelectedLineIndex] = React.useState( derivedState.currentCodeErrorData?.lineIndex || 0 ); const onClickStackLine = async (event, lineIndex) => { event && event.preventDefault(); if (props.collapsed) return; const { stackTraces } = codeError; const stackInfo = (stackTraces && stackTraces[0]) || codeError.stackInfo; if (stackInfo && stackInfo.lines[lineIndex] && stackInfo.lines[lineIndex].line !== undefined) { setCurrentSelectedLineIndex(lineIndex); dispatch( jumpToStackLine(lineIndex, stackInfo.lines[lineIndex], stackInfo.sha!, stackInfo.repoId!) ); } }; const { stackTraces } = codeError as CSCodeError; const stackTrace = stackTraces && stackTraces[0] && stackTraces[0].lines; useEffect(() => { if (!props.collapsed) { const { stackTraces } = codeError; const stackInfo = (stackTraces && stackTraces[0]) || codeError.stackInfo; if (stackInfo?.lines) { let lineIndex = currentSelectedLine; const len = stackInfo.lines.length; while ( lineIndex < len && // stackInfo.lines[lineNum].line !== undefined && stackInfo.lines[lineIndex].error ) { lineIndex++; } if (lineIndex < len) { setCurrentSelectedLineIndex(lineIndex); try { dispatch( jumpToStackLine( lineIndex, stackInfo.lines[lineIndex], stackInfo.sha, stackInfo.repoId! ) ); } catch (ex) { console.warn(ex); } } } } }, [codeError]); const handleKeyDown = event => { if ( props.stackFrameClickDisabled || props.collapsed || !props.parsedStack?.resolvedStackInfo?.lines ) return; const lines = props.parsedStack?.resolvedStackInfo?.lines; if (!lines) return; let nextLine = currentSelectedLine; if (event.key === "ArrowUp" || event.which === 38) { event.stopPropagation(); while (currentSelectedLine >= 0) { nextLine--; if (!lines[nextLine].error) { onClickStackLine(event, nextLine); return; } } } if (event.key === "ArrowDown" || event.which === 40) { event.stopPropagation(); while (currentSelectedLine <= lines.length) { nextLine++; if (!lines[nextLine].error) { onClickStackLine(event, nextLine); return; } } } }; return ( <MinimumWidthCard {...getCardProps(props)} noCard={!props.collapsed}> {props.collapsed && ( <BaseCodeErrorHeader codeError={codeError} errorGroup={errorGroup} post={props.post} collapsed={props.collapsed} setIsEditing={props.setIsEditing} /> )} {props.headerError && props.headerError.message && ( <div className="color-warning" style={{ display: "flex", padding: "10px 0", whiteSpace: "normal", alignItems: "flex-start" }} > <Icon name="alert" /> <div style={{ paddingLeft: "10px" }}>{props.headerError.message}</div> </div> )} {codeError?.text && <Message>{codeError.text}</Message>} {/* assuming 3 items (58px) */} {!props.collapsed && ( <div style={{ minHeight: derivedState.errorGroupIsLoading || errorGroup ? "18px" : "initial" }} > {errorGroup && errorGroup.attributes && Object.keys(errorGroup.attributes).map(key => { const value: { type: string; value: any } = errorGroup.attributes![key]; return ( <DataRow> <DataLabel>{key}:</DataLabel> <DataValue> {value.type === "timestamp" && ( <Timestamp className="no-padding" time={value.value as number} /> )} {value.type !== "timestamp" && <>{value.value}</>} </DataValue> </DataRow> ); })} {props.repoInfo && ( <DataRow> <DataLabel>Repo:</DataLabel> <DataValue>{props.repoInfo.repoName}</DataValue> </DataRow> )} {props.repoInfo?.branch && ( <DataRow> <DataLabel>Build:</DataLabel> <DataValue>{props.repoInfo.branch.substr(0, 7)}</DataValue> </DataRow> )} </div> )} <MetaSection> {stackTrace && ( <Meta> <MetaLabel>Stack Trace</MetaLabel> <ClickLines id="stack-trace" className="code" tabIndex={0} onKeyDown={handleKeyDown}> {(stackTrace || []).map((line, i) => { if (!line || !line.fileFullPath) return null; const className = i === currentSelectedLine ? "monospace li-active" : "monospace"; const mline = line.fileFullPath.replace(/\s\s\s\s+/g, " "); return props.stackFrameClickDisabled || props.collapsed || props.parsedStack?.resolvedStackInfo?.lines[i]?.error ? ( <Tooltip key={"tooltipline-" + i} title={props.parsedStack?.resolvedStackInfo?.lines[i]?.error} placement="bottom" delay={1} > <DisabledClickLine key={"disabled-line" + i} className="monospace"> <span> <span style={{ opacity: ".6" }}>{line.method}</span>({mline}: <strong>{line.line}</strong> {line.column ? `:${line.column}` : null}) </span> </DisabledClickLine> </Tooltip> ) : ( <ClickLine key={"click-line" + i} className={className} onClick={e => onClickStackLine(e, i)} > <span> <span style={{ opacity: ".6" }}>{line.method}</span>({mline}: <strong>{line.line}</strong> {line.column ? `:${line.column}` : null}) </span> </ClickLine> ); })} </ClickLines> </Meta> )} {props.post && ( <div style={{ marginBottom: "10px" }}> <Reactions className="reactions no-pad-left" post={props.post} /> </div> )} {!props.collapsed && props.post && <Attachments post={props.post as CSPost} />} </MetaSection> {props.collapsed && renderMetaSectionCollapsed(props)} {!props.collapsed && props && props.post && props.post.sharedTo && props.post.sharedTo.length > 0 && ( <div className="related"> <div className="related-label">Shared To</div> {props.post.sharedTo.map(target => { const providerDisplay = PROVIDER_MAPPINGS[target.providerId]; return ( <Link className="external-link" href={target.url}> {providerDisplay && providerDisplay.icon && ( <span> <Icon name={providerDisplay.icon} /> </span> )} {target.channelName} </Link> ); })} </div> )} {renderedFooter} </MinimumWidthCard> ); }; const renderMetaSectionCollapsed = (props: BaseCodeErrorProps) => { if (!props.isFollowing) return null; return ( <MetaSectionCollapsed> {props.isFollowing && ( <span> <Icon className="detail-icon" title="You are following this code error" placement="bottomLeft" align={{ offset: [-18, 4] }} name="eye" /> </span> )} {props.codeError.numReplies > 0 && ( <Tooltip title="Show replies" placement="bottom"> <span className="detail-icon"> <Icon name="comment" /> {props.codeError.numReplies} </span> </Tooltip> )} </MetaSectionCollapsed> ); }; const ReplyInput = (props: { codeError: CSCodeError }) => { const dispatch = useDispatch(); const [text, setText] = React.useState(""); const [attachments, setAttachments] = React.useState<AttachmentField[]>([]); const [isLoading, setIsLoading] = React.useState(false); const teamMates = useSelector((state: CodeStreamState) => getTeamMates(state)); const submit = async () => { // don't create empty replies if (text.length === 0) return; setIsLoading(true); const actualCodeError = ((await dispatch( upgradePendingCodeError(props.codeError.id, "Comment") )) as any) as { codeError: CSCodeError; }; dispatch(markItemRead(props.codeError.id, actualCodeError.codeError.numReplies + 1)); await dispatch( createPost( actualCodeError.codeError.streamId, actualCodeError.codeError.postId, replaceHtml(text)!, null, findMentionedUserIds(teamMates, text), { entryPoint: "Code Error", files: attachments } ) ); setIsLoading(false); setText(""); setAttachments([]); }; return ( <> <MessageInput multiCompose text={text} placeholder="Add a comment..." onChange={setText} onSubmit={submit} attachments={attachments} attachmentContainerType="reply" setAttachments={setAttachments} /> <ButtonRow style={{ marginTop: 0 }}> <Tooltip title={ <span> Submit Comment <span className="keybinding extra-pad"> {navigator.appVersion.includes("Macintosh") ? "⌘" : "Ctrl"} ENTER </span> </span> } placement="bottomRight" delay={1} > <Button disabled={text.length === 0} onClick={submit} isLoading={isLoading}> Comment </Button> </Tooltip> </ButtonRow> </> ); }; type FromBaseCodeErrorProps = Pick< BaseCodeErrorProps, "collapsed" | "hoverEffect" | "onClick" | "className" | "renderFooter" | "stackFrameClickDisabled" >; interface PropsWithId extends FromBaseCodeErrorProps { id: string; } interface PropsWithCodeError extends FromBaseCodeErrorProps { codeError: CSCodeError; errorGroup?: NewRelicErrorGroup; parsedStack?: ResolveStackTraceResponse; } function isPropsWithId(props: PropsWithId | PropsWithCodeError): props is PropsWithId { return (props as any).id != undefined; } export type CodeErrorProps = PropsWithId | PropsWithCodeError; const CodeErrorForCodeError = (props: PropsWithCodeError) => { const { codeError, ...baseProps } = props; let disposableDidChangeDataNotification: { dispose(): void }; const derivedState = useSelector((state: CodeStreamState) => { const post = codeError && codeError.postId ? getPost(state.posts, codeError!.streamId, codeError.postId) : undefined; return { post, currentTeamId: state.context.currentTeamId, currentUser: state.users[state.session.userId!], author: state.users[props.codeError.creatorId], repos: state.repos, userIsFollowing: (props.codeError.followerIds || []).includes(state.session.userId!), replies: props.collapsed ? emptyArray : getThreadPosts(state, codeError.streamId, codeError.postId) }; }); const [preconditionError, setPreconditionError] = React.useState<SimpleError>({ message: "", type: "" }); const [isEditing, setIsEditing] = React.useState(false); const [shareModalOpen, setShareModalOpen] = React.useReducer(open => !open, false); const webviewFocused = useSelector((state: CodeStreamState) => state.context.hasFocus); useDidMount(() => { if (!props.collapsed && webviewFocused) { HostApi.instance.track("Page Viewed", { "Page Name": "Code Error Details" }); } requestAnimationFrame(() => { const $stackTrace = document.getElementById("stack-trace"); if ($stackTrace) $stackTrace.focus(); }); return () => { // cleanup this disposable on unmount. it may or may not have been set. disposableDidChangeDataNotification && disposableDidChangeDataNotification.dispose(); }; }); const renderFooter = props.renderFooter || ((Footer, InputContainer) => { if (props.collapsed) return null; return ( <Footer className="replies-to-review" style={{ borderTop: "none", marginTop: 0 }}> {props.codeError.postId && ( <> {derivedState.replies?.length > 0 && <MetaLabel>Activity</MetaLabel>} <RepliesToPost streamId={props.codeError.streamId} parentPostId={props.codeError.postId} itemId={props.codeError.id} numReplies={props.codeError.numReplies} /> </> )} {InputContainer && ( <InputContainer> <ReplyInput codeError={codeError} /> </InputContainer> )} </Footer> ); }); const repoInfo = React.useMemo(() => { const { stackTraces } = codeError; let stackInfo = stackTraces && stackTraces[0]; // TODO deal with multiple stacks if (!stackInfo) stackInfo = (codeError as any).stackInfo; // this is for old code, maybe can remove after a while? if (stackInfo && stackInfo.repoId) { const repo = derivedState.repos[stackInfo.repoId]; if (!repo) return undefined; return { repoName: repo.name, branch: stackInfo.sha! }; } else { return undefined; } }, [codeError, derivedState.repos]); return ( <> {shareModalOpen && ( <SharingModal codeError={props.codeError} post={derivedState.post} onClose={() => setShareModalOpen(false)} /> )} <BaseCodeError {...baseProps} parsedStack={props.parsedStack} codeError={props.codeError} post={derivedState.post} repoInfo={repoInfo} isFollowing={derivedState.userIsFollowing} currentUserId={derivedState.currentUser.id} renderFooter={renderFooter} setIsEditing={setIsEditing} headerError={preconditionError} /> </> ); }; const CodeErrorForId = (props: PropsWithId) => { const { id, ...otherProps } = props; const dispatch = useDispatch<Dispatch>(); const codeError = useSelector((state: CodeStreamState) => { return getCodeError(state.codeErrors, id); }); const [notFound, setNotFound] = React.useState(false); useDidMount(() => { let isValid = true; if (codeError == null) { dispatch(fetchCodeError(id)) .then(result => { if (!isValid) return; if (result == null) setNotFound(true); }) .catch(() => setNotFound(true)); } return () => { isValid = false; }; }); if (notFound) return ( <MinimumWidthCard> This code error was not found. Perhaps it was deleted by the author, or you don't have permission to view it. </MinimumWidthCard> ); if (codeError == null) return ( <DelayedRender> <Loading /> </DelayedRender> ); return <CodeErrorForCodeError codeError={codeError} {...otherProps} />; }; export const CodeError = (props: CodeErrorProps) => { if (isPropsWithId(props)) return <CodeErrorForId {...props} />; return <CodeErrorForCodeError {...props} />; };
the_stack
import { EOL } from 'os'; import { AsyncCreatable, lowerFirst, mapKeys, omit, parseJsonMap, upperFirst } from '@salesforce/kit'; import { asJsonArray, asNumber, ensure, ensureJsonMap, ensureString, getString, isJsonMap, Many, } from '@salesforce/ts-types'; import { QueryResult, RequestInfo } from 'jsforce'; import { DescribeSObjectResult } from 'jsforce/describe-result'; import { AuthFields, AuthInfo } from './authInfo'; import { Connection } from './connection'; import { Logger } from './logger'; import { Messages } from './messages'; import { Org } from './org'; import { PermissionSetAssignment } from './permissionSetAssignment'; import { SecureBuffer } from './secureBuffer'; import { SfdxError } from './sfdxError'; import { sfdc } from './util/sfdc'; const rand = (len: Many<string>): number => Math.floor(Math.random() * len.length); interface Complexity { [key: string]: boolean | undefined; LOWER?: boolean; UPPER?: boolean; NUMBERS?: boolean; SYMBOLS?: boolean; } const CHARACTERS: { [index: string]: string | string[] } = { LOWER: 'abcdefghijklmnopqrstuvwxyz', UPPER: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', NUMBERS: '1234567890', SYMBOLS: ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '[', ']', '|', '-'], }; const PASSWORD_COMPLEXITY: { [index: number]: Complexity } = { '0': { LOWER: true }, '1': { LOWER: true, NUMBERS: true }, '2': { LOWER: true, SYMBOLS: true }, '3': { LOWER: true, UPPER: true, NUMBERS: true }, '4': { LOWER: true, NUMBERS: true, SYMBOLS: true }, '5': { LOWER: true, UPPER: true, NUMBERS: true, SYMBOLS: true }, }; const scimEndpoint = '/services/scim/v1/Users'; const scimHeaders = { 'auto-approve-user': 'true' }; /** * A Map of Required Salesforce User fields. */ export const REQUIRED_FIELDS = { id: 'id', username: 'username', lastName: 'lastName', alias: 'alias', timeZoneSidKey: 'timeZoneSidKey', localeSidKey: 'localeSidKey', emailEncodingKey: 'emailEncodingKey', profileId: 'profileId', languageLocaleKey: 'languageLocaleKey', email: 'email', }; /** * Required fields type needed to represent a Salesforce User object. * * **See** https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_user.htm */ export type UserFields = { -readonly [K in keyof typeof REQUIRED_FIELDS]: string }; /** * Helper method to lookup UserFields. * * @param logger * @param username The username. */ async function retrieveUserFields(logger: Logger, username: string): Promise<UserFields> { const connection: Connection = await Connection.create({ authInfo: await AuthInfo.create({ username }), }); if (sfdc.matchesAccessToken(username)) { logger.debug('received an accessToken for the username. Converting...'); username = (await connection.identity()).username; logger.debug(`accessToken converted to ${username}`); } else { logger.debug('not a accessToken'); } const fromFields = Object.keys(REQUIRED_FIELDS).map(upperFirst); const requiredFieldsFromAdminQuery = `SELECT ${fromFields} FROM User WHERE Username='${username}'`; const result: QueryResult<string[]> = await connection.query<string[]>(requiredFieldsFromAdminQuery); logger.debug('Successfully retrieved the admin user for this org.'); if (result.totalSize === 1) { const results = mapKeys(result.records[0], (value: unknown, key: string) => lowerFirst(key)); const fields: UserFields = { id: ensure(getString(results, REQUIRED_FIELDS.id)), username, alias: ensure(getString(results, REQUIRED_FIELDS.alias)), email: ensure(getString(results, REQUIRED_FIELDS.email)), emailEncodingKey: ensure(getString(results, REQUIRED_FIELDS.emailEncodingKey)), languageLocaleKey: ensure(getString(results, REQUIRED_FIELDS.languageLocaleKey)), localeSidKey: ensure(getString(results, REQUIRED_FIELDS.localeSidKey)), profileId: ensure(getString(results, REQUIRED_FIELDS.profileId)), lastName: ensure(getString(results, REQUIRED_FIELDS.lastName)), timeZoneSidKey: ensure(getString(results, REQUIRED_FIELDS.timeZoneSidKey)), }; return fields; } else { throw SfdxError.create('@salesforce/core', 'user', 'userQueryFailed', [username]); } } /** * Gets the profile id associated with a profile name. * * @param name The name of the profile. * @param connection The connection for the query. */ async function retrieveProfileId(name: string, connection: Connection): Promise<string> { if (!sfdc.validateSalesforceId(name)) { const profileQuery = `SELECT Id FROM Profile WHERE name='${name}'`; const result = await connection.query<{ Id: string }>(profileQuery); if (result.records.length > 0) { return result.records[0].Id; } } return name; } /** * Provides a default set of fields values that can be used to create a user. This is handy for * software development purposes. * * ``` * const connection: Connection = await Connection.create({ * authInfo: await AuthInfo.create({ username: 'user@example.com' }) * }); * const org: Org = await Org.create({ connection }); * const options: DefaultUserFields.Options = { * templateUser: org.getUsername() * }; * const fields = (await DefaultUserFields.create(options)).getFields(); * ``` */ export class DefaultUserFields extends AsyncCreatable<DefaultUserFields.Options> { // Initialized in init private logger!: Logger; private userFields!: UserFields; private options: DefaultUserFields.Options; /** * @ignore */ public constructor(options: DefaultUserFields.Options) { super(options); this.options = options || { templateUser: '' }; } /** * Get user fields. */ public getFields(): UserFields { return this.userFields; } /** * Initialize asynchronous components. */ protected async init(): Promise<void> { this.logger = await Logger.child('DefaultUserFields'); this.userFields = await retrieveUserFields(this.logger, this.options.templateUser); this.userFields.profileId = await retrieveProfileId( 'Standard User', await Connection.create({ authInfo: await AuthInfo.create({ username: this.options.templateUser }), }) ); this.logger.debug(`Standard User profileId: ${this.userFields.profileId}`); if (this.options.newUserName) { this.userFields.username = this.options.newUserName; } else { this.userFields.username = `${Date.now()}_${this.userFields.username}`; } } } export namespace DefaultUserFields { /** * Used to initialize default values for fields based on a templateUser user. This user will be part of the * Standard User profile. */ export interface Options { templateUser: string; newUserName?: string; } } export interface PasswordConditions { length: number; complexity: number; } /** * A class for creating a User, generating a password for a user, and assigning a user to one or more permission sets. * See methods for examples. */ export class User extends AsyncCreatable<User.Options> { private org: Org; private logger!: Logger; /** * @ignore */ public constructor(options: User.Options) { super(options); this.org = options.org; } /** * Generate default password for a user. Returns An encrypted buffer containing a utf8 encoded password. */ public static generatePasswordUtf8( passwordCondition: PasswordConditions = { length: 13, complexity: 5 } ): SecureBuffer<void> { if (!PASSWORD_COMPLEXITY[passwordCondition.complexity]) { throw SfdxError.create('@salesforce/core', 'user', 'complexityOutOfBound'); } if (passwordCondition.length < 8 || passwordCondition.length > 1000) { throw SfdxError.create('@salesforce/core', 'user', 'lengthOutOfBound'); } let password: string[] = []; ['SYMBOLS', 'NUMBERS', 'UPPER', 'LOWER'].forEach((charSet) => { if (PASSWORD_COMPLEXITY[passwordCondition.complexity][charSet]) { password.push(CHARACTERS[charSet][rand(CHARACTERS[charSet])]); } }); // Concatinating remaining length randomly with all lower characters password = password.concat( Array(Math.max(passwordCondition.length - password.length, 0)) .fill('0') .map(() => CHARACTERS['LOWER'][rand(CHARACTERS['LOWER'])]) ); password = password.sort(() => Math.random() - 0.5); const secureBuffer: SecureBuffer<void> = new SecureBuffer<void>(); secureBuffer.consume(Buffer.from(password.join(''), 'utf8')); return secureBuffer; } /** * Initialize a new instance of a user and return it. */ public async init(): Promise<void> { this.logger = await Logger.child('User'); await this.org.refreshAuth(); this.logger.debug('Auth refresh ok'); } /** * Assigns a password to a user. For a user to have the ability to assign their own password, the org needs the * following org feature: EnableSetPasswordInApi. * * @param info The AuthInfo object for user to assign the password to. * @param password [throwWhenRemoveFails = User.generatePasswordUtf8()] A SecureBuffer containing the new password. */ public async assignPassword( info: AuthInfo, password: SecureBuffer<void> = User.generatePasswordUtf8() ): Promise<void> { this.logger.debug( `Attempting to set password for userId: ${info.getFields().userId} username: ${info.getFields().username}` ); const userConnection = await Connection.create({ authInfo: info }); return new Promise((resolve, reject) => { // eslint-disable-next-line @typescript-eslint/no-misused-promises password.value(async (buffer: Buffer) => { try { // @ts-ignore TODO: expose `soap` on Connection however appropriate const soap = userConnection.soap; await soap.setPassword(info.getFields().userId as string, buffer.toString('utf8')); this.logger.debug(`Set password for userId: ${info.getFields().userId}`); resolve(); } catch (e) { reject(e); } }); }); } /** * Methods to assign one or more permission set names to a user. * * @param id The Salesforce id of the user to assign the permission set to. * @param permsetNames An array of permission set names. * * ``` * const username = 'user@example.com'; * const connection: Connection = await Connection.create({ * authInfo: await AuthInfo.create({ username }) * }); * const org = await Org.create({ connection }); * const user: User = await User.create({ org }); * const fields: UserFields = await user.retrieve(username); * await user.assignPermissionSets(fields.id, ['sfdx', 'approver']); * ``` */ public async assignPermissionSets(id: string, permsetNames: string[]): Promise<void> { if (!id) { throw SfdxError.create('@salesforce/core', 'user', 'missingId'); } if (!permsetNames) { throw SfdxError.create('@salesforce/core', 'user', 'permsetNamesAreRequired'); } const assignments: PermissionSetAssignment = await PermissionSetAssignment.init(this.org); for (const permsetName of permsetNames) { await assignments.create(id, permsetName); } } /** * Method for creating a new User. * * By default scratch orgs only allow creating 2 additional users. Work with Salesforce Customer Service to increase * user limits. * * The Org Preferences required to increase the number of users are: * Standard User Licenses * Salesforce CRM Content User * * @param fields The required fields for creating a user. * * ``` * const connection: Connection = await Connection.create({ * authInfo: await AuthInfo.create({ username: 'user@example.com' }) * }); * const org = await Org.create({ connection }); * * const defaultUserFields = await DefaultUserFields.create({ templateUser: 'devhub_user@example.com' }); * const user: User = await User.create({ org }); * const info: AuthInfo = await user.createUser(defaultUserFields.getFields()); * ``` */ public async createUser(fields: UserFields): Promise<AuthInfo> { // Create a user and get a refresh token const refreshTokenSecret: { buffer: SecureBuffer<string>; userId: string; } = await this.createUserInternal(fields); // Create the initial auth info const authInfo = await AuthInfo.create({ username: this.org.getUsername() }); const adminUserAuthFields: AuthFields = authInfo.getFields(true); // Setup oauth options for the new user const oauthOptions = { loginUrl: adminUserAuthFields.loginUrl, refreshToken: refreshTokenSecret.buffer.value((buffer: Buffer): string => buffer.toString('utf8')), clientId: adminUserAuthFields.clientId, clientSecret: adminUserAuthFields.clientSecret, privateKey: adminUserAuthFields.privateKey, }; // Create an auth info object for the new user const newUserAuthInfo: AuthInfo = await AuthInfo.create({ username: fields.username, oauth2Options: oauthOptions, }); // Update the auth info object with created user id. const newUserAuthFields: AuthFields = newUserAuthInfo.getFields(); newUserAuthFields.userId = refreshTokenSecret.userId; // Make sure we can connect and if so save the auth info. await this.describeUserAndSave(newUserAuthInfo); // Let the org know there is a new user. See $HOME/.sfdx/[orgid].json for the mapping. await this.org.addUsername(newUserAuthInfo); return newUserAuthInfo; } /** * Method to retrieve the UserFields for a user. * * @param username The username of the user. * * ``` * const username = 'boris@thecat.com'; * const connection: Connection = await Connection.create({ * authInfo: await AuthInfo.create({ username }) * }); * const org = await Org.create({ connection }); * const user: User = await User.create({ org }); * const fields: UserFields = await user.retrieve(username); * ``` */ public async retrieve(username: string): Promise<UserFields> { return await retrieveUserFields(this.logger, username); } /** * Helper method that verifies the server's User object is available and if so allows persisting the Auth information. * * @param newUserAuthInfo The AuthInfo for the new user. */ private async describeUserAndSave(newUserAuthInfo: AuthInfo): Promise<AuthInfo> { const connection = await Connection.create({ authInfo: newUserAuthInfo }); this.logger.debug(`Created connection for user: ${newUserAuthInfo.getUsername()}`); const userDescribe: DescribeSObjectResult = await connection.describe('User'); if (userDescribe && userDescribe.fields) { await newUserAuthInfo.save(); return newUserAuthInfo; } else { throw SfdxError.create('@salesforce/core', 'user', 'problemsDescribingTheUserObject'); } } /** * Helper that makes a REST request to create the user, and update additional required fields. * * @param fields The configuration the new user should have. */ private async createUserInternal(fields: UserFields): Promise<{ buffer: SecureBuffer<string>; userId: string }> { if (!fields) { throw SfdxError.create('@salesforce/core', 'user', 'missingFields'); } const conn: Connection = this.org.getConnection(); const body = JSON.stringify({ username: fields.username, emails: [fields.email], name: { familyName: fields.lastName, }, nickName: fields.username.substring(0, 40), // nickName has a max length of 40 entitlements: [ { value: fields.profileId, }, ], }); this.logger.debug(`user create request body: ${body}`); const scimUrl = conn.normalizeUrl(scimEndpoint); this.logger.debug(`scimUrl: ${scimUrl}`); const info: RequestInfo = { method: 'POST', url: scimUrl, headers: scimHeaders, body, }; const response = await conn.requestRaw(info); const responseBody = parseJsonMap(ensureString(response['body'])); const statusCode = asNumber(response.statusCode); this.logger.debug(`user create response.statusCode: ${response.statusCode}`); if (!(statusCode === 201 || statusCode === 200)) { const messages = Messages.loadMessages('@salesforce/core', 'user'); let message = messages.getMessage('invalidHttpResponseCreatingUser', [statusCode]); if (responseBody) { const errors = asJsonArray(responseBody.Errors); if (errors && errors.length > 0) { message = `${message} causes:${EOL}`; errors.forEach((singleMessage) => { if (!isJsonMap(singleMessage)) return; message = `${message}${EOL}${singleMessage.description}`; }); } } this.logger.debug(message); throw new SfdxError(message, 'UserCreateHttpError'); } fields.id = ensureString(responseBody.id); await this.updateRequiredUserFields(fields); const buffer = new SecureBuffer<string>(); const headers = ensureJsonMap(response.headers); const autoApproveUser = ensureString(headers['auto-approve-user']); buffer.consume(Buffer.from(autoApproveUser)); return { buffer, userId: fields.id, }; } /** * Update the remaining required fields for the user. * * @param fields The fields for the user. */ private async updateRequiredUserFields(fields: UserFields): Promise<void> { const leftOverRequiredFields = omit(fields, [ REQUIRED_FIELDS.username, REQUIRED_FIELDS.email, REQUIRED_FIELDS.lastName, REQUIRED_FIELDS.profileId, ]); const object = mapKeys(leftOverRequiredFields, (value: unknown, key: string) => upperFirst(key)); await this.org.getConnection().sobject('User').update(object); this.logger.debug(`Successfully Updated additional properties for user: ${fields.username}`); } } export namespace User { /** * Used to initialize default values for fields based on a templateUser user. This user will be part of the * Standard User profile. */ export interface Options { org: Org; } }
the_stack
import * as types from "babel-types"; import * as isFunction from "lodash.isfunction"; import { ErrInvalidIterable, ErrNoSuper, ErrNotDefined, ErrIsNotFunction } from "../error"; import { Path } from "../path"; import { _classCallCheck, _createClass, _inherits, _possibleConstructorReturn, _taggedTemplateLiteral } from "../runtime"; import { ES2015Map, ScopeType } from "../type"; import { Signal } from "../signal"; import { Scope } from "../scope"; import { Stack } from "../stack"; import { MODULE, THIS, REQUIRE, ARGUMENTS, NEW, ANONYMOUS } from "../constant"; import { isCallExpression, isClassMethod, isClassProperty, isIdentifier, isImportDefaultSpecifier, isImportSpecifier, isMemberExpression, isVariableDeclaration } from "../packages/babel-types"; import { defineFunctionLength, defineFunctionName } from "../utils"; function overriteStack(err: Error, stack: Stack, node: types.Node): Error { stack.push({ filename: ANONYMOUS, stack: stack.currentStackName, location: node.loc }); err.stack = err.toString() + "\n" + stack.raw; return err; } export const es2015: ES2015Map = { ArrowFunctionExpression(path) { const { node, scope } = path; const func = (...args) => { const newScope = scope.createChild(ScopeType.Function); for (let i = 0; i < node.params.length; i++) { const { name } = node.params[i] as types.Identifier; newScope.const(name, args[i]); } const lastThis = scope.hasBinding(THIS); newScope.const(THIS, lastThis ? lastThis.value : null); newScope.const(ARGUMENTS, args); const result = path.evaluate(path.createChild(node.body, newScope)); if (Signal.isReturn(result)) { return result.value; } else { return result; } }; defineFunctionLength(func, node.params.length); defineFunctionName(func, node.id ? node.id.name : ""); return func; }, TemplateLiteral(path) { const { node } = path; return ([] as types.Node[]) .concat(node.expressions, node.quasis) .sort((a, b) => a.start - b.start) .map(element => path.evaluate(path.createChild(element))) .join(""); }, TemplateElement(path) { return path.node.value.raw; }, ForOfStatement(path) { const { node, scope, ctx, stack } = path; const labelName: string | void = ctx.labelName; const entity = path.evaluate(path.createChild(node.right)); const SymbolConst: any = (() => { const $var = scope.hasBinding("Symbol"); return $var ? $var.value : undefined; })(); // not support for of, it mean not support native for of if (SymbolConst) { if (!entity || !entity[SymbolConst.iterator]) { // FIXME: how to get function name // for (let value of get()){} throw overriteStack( ErrInvalidIterable((node.right as types.Identifier).name), stack, node.right ); } } if (isVariableDeclaration(node.left)) { /** * for (let value in array){ // value should define in block scope * * } */ const declarator: types.VariableDeclarator = node.left.declarations[0]; const varName = (declarator.id as types.Identifier).name; for (const value of entity) { const forOfScope = scope.createChild(ScopeType.ForOf); forOfScope.invasive = true; forOfScope.isolated = false; forOfScope.declare(node.left.kind, varName, value); // define in current scope const signal = path.evaluate(path.createChild(node.body, forOfScope)); if (Signal.isBreak(signal)) { if (!signal.value) { break; } if (signal.value === labelName) { break; } return signal; } else if (Signal.isContinue(signal)) { if (!signal.value) { continue; } if (signal.value === labelName) { continue; } return signal; } else if (Signal.isReturn(signal)) { return signal; } } } else if (isIdentifier(node.left)) { /** * for (value in array){ // value should define in parent scope * * } */ const varName = node.left.name; for (const value of entity) { const forOfScope = scope.createChild(ScopeType.ForOf); forOfScope.invasive = true; scope.var(varName, value); // define in parent scope const signal = path.evaluate(path.createChild(node.body, forOfScope)); if (Signal.isBreak(signal)) { if (!signal.value) { break; } if (signal.value === labelName) { break; } return signal; } else if (Signal.isContinue(signal)) { if (!signal.value) { continue; } if (signal.value === labelName) { continue; } return signal; } else if (Signal.isReturn(signal)) { return signal; } } } }, ClassDeclaration(path) { const ClassConstructor = path.evaluate( path.createChild(path.node.body, path.scope.createChild(ScopeType.Class)) ); // support class decorators const classDecorators = (path.node.decorators || []) .map(node => path.evaluate(path.createChild(node))) .reverse(); // revers decorators // TODO: support class property decorator // support class method decorators // const propertyDecorators = path.node.body.body.filter( // node => node.decorators && node.decorators.length // ); for (const decorator of classDecorators) { decorator(ClassConstructor); } path.scope.const(path.node.id.name, ClassConstructor); }, ClassBody(path) { const { node, scope, stack } = path; const constructor: types.ClassMethod | void = node.body.find( n => isClassMethod(n) && n.kind === "constructor" ) as types.ClassMethod | void; const methods: types.ClassMethod[] = node.body.filter( n => isClassMethod(n) && n.kind !== "constructor" ) as types.ClassMethod[]; const properties: types.ClassProperty[] = node.body.filter(n => isClassProperty(n) ) as types.ClassProperty[]; const parentNode = (path.parent as Path<types.ClassDeclaration>).node; const Class = (SuperClass => { if (SuperClass) { _inherits(ClassConstructor, SuperClass); } function ClassConstructor(...args) { stack.enter(parentNode.id.name + ".constructor"); _classCallCheck(this, ClassConstructor); const classScope = scope.createChild(ScopeType.Constructor); // define class property properties.forEach(p => { this[p.key.name] = path.evaluate( path.createChild(p.value, classScope) ); }); if (constructor) { // defined the params constructor.params.forEach((param: types.LVal, i) => { classScope.const((param as types.Identifier).name, args[i]); }); if (!SuperClass) { classScope.const(THIS, this); } classScope.const(NEW, { target: ClassConstructor }); for (const n of constructor.body.body) { path.evaluate( path.createChild(n, classScope, { SuperClass, ClassConstructor, ClassConstructorArguments: args, ClassEntity: this, classScope }) ); } } else { classScope.const(THIS, this); // apply super if constructor not exist _possibleConstructorReturn( this, ( (ClassConstructor as any).__proto__ || Object.getPrototypeOf(ClassConstructor) ).apply(this, args) ); } if (!classScope.hasOwnBinding(THIS)) { throw overriteStack(ErrNoSuper(), path.stack, node); } stack.leave(); return this; } // define class name and length defineFunctionLength( ClassConstructor, constructor ? constructor.params.length : 0 ); defineFunctionName(ClassConstructor, parentNode.id.name); const classMethods = methods .map((method: types.ClassMethod) => { const methodName: string = method.id ? method.id.name : method.computed ? path.evaluate(path.createChild(method.key)) : (method.key as types.Identifier).name; const methodScope = scope.createChild(ScopeType.Function); const func = function(...args) { stack.enter(parentNode.id.name + "." + methodName); methodScope.const(THIS, this); methodScope.const(NEW, { target: undefined }); // defined the params method.params.forEach((p: types.LVal, i) => { if (isIdentifier(p)) { methodScope.const(p.name, args[i]); } }); const result = path.evaluate( path.createChild(method.body, methodScope, { SuperClass, ClassConstructor, ClassMethodArguments: args, ClassEntity: this }) ); stack.leave(); if (Signal.isReturn(result)) { return result.value; } }; defineFunctionLength(func, method.params.length); defineFunctionName(func, methodName); return { key: (method.key as any).name, [method.kind === "method" ? "value" : method.kind]: func }; }) .concat([{ key: "constructor", value: ClassConstructor }]); // define class methods _createClass(ClassConstructor, classMethods); return ClassConstructor; })( parentNode.superClass ? (() => { const $var = scope.hasBinding((parentNode.superClass as any).name); return $var ? $var.value : null; })() : null ); return Class; }, ClassMethod(path) { return path.evaluate(path.createChild(path.node.body)); }, // refactor class ClassExpression(path) { // }, Super(path) { const { ctx } = path; const { SuperClass, ClassConstructor, ClassEntity } = ctx; const classScope: Scope = ctx.classScope; const ClassBodyPath = path.findParent("ClassBody"); // make sure it include in ClassDeclaration if (!ClassBodyPath) { throw new Error("super() only can use in ClassDeclaration"); } const parentPath = path.parent; if (parentPath) { // super() if (isCallExpression(parentPath.node)) { if (classScope && !classScope.hasOwnBinding(THIS)) { classScope.const(THIS, ClassEntity); } return function inherits(...args) { _possibleConstructorReturn( ClassEntity, ( (ClassConstructor as any).__proto__ || Object.getPrototypeOf(ClassConstructor) ).apply(ClassEntity, args) ); }.bind(ClassEntity); } else if (isMemberExpression(parentPath.node)) { // super.eat() // then return the superclass prototype return SuperClass.prototype; } } }, SpreadElement(path) { return path.evaluate(path.createChild(path.node.argument)); }, ImportDeclaration(path) { const { node, scope, stack } = path; let defaultImport: string = ""; // default import object const otherImport: string[] = []; // import property const moduleName: string = path.evaluate(path.createChild(node.source)); node.specifiers.forEach(n => { if (isImportDefaultSpecifier(n)) { // defaultImport = visitors.ImportDefaultSpecifier(path.createChild(n)); defaultImport = path.evaluate(path.createChild(n)); } else if (isImportSpecifier(n)) { otherImport.push(path.evaluate(path.createChild(n))); // otherImport.push(visitors.ImportSpecifier(path.createChild(n))); } else { throw n; } }); const requireVar = scope.hasBinding(REQUIRE); if (requireVar === undefined) { throw overriteStack(ErrNotDefined(REQUIRE), stack, node); } const requireFunc = requireVar.value; if (!isFunction(requireFunc)) { throw overriteStack(ErrIsNotFunction(REQUIRE), stack, node); } const targetModule: any = requireFunc(moduleName) || {}; if (defaultImport) { scope.const( defaultImport, targetModule.default ? targetModule.default : targetModule ); } for (const varName of otherImport) { scope.const(varName, targetModule[varName]); } }, ExportDefaultDeclaration(path) { const { node, scope } = path; const moduleVar = scope.hasBinding(MODULE); if (moduleVar) { const moduleObject = moduleVar.value; moduleObject.exports = { ...moduleObject.exports, ...path.evaluate(path.createChild(node.declaration)) }; } }, ExportNamedDeclaration(path) { const { node } = path; node.specifiers.forEach(n => path.evaluate(path.createChild(n))); }, AssignmentPattern(path) { const { node, scope, ctx } = path; const { value } = ctx; scope.const( node.left.name, value === undefined ? path.evaluate(path.createChild(node.right)) : value ); }, RestElement(path) { const { node, scope, ctx } = path; const { value } = ctx; scope.const((node.argument as types.Identifier).name, value); }, YieldExpression(path) { const { next } = path.ctx; next(path.evaluate(path.createChild(path.node.argument))); // call next }, TaggedTemplateExpression(path) { const str = path.node.quasi.quasis.map(v => v.value.cooked); const raw = path.node.quasi.quasis.map(v => v.value.raw); const templateObject = _taggedTemplateLiteral(str, raw); const func = path.evaluate(path.createChild(path.node.tag)); const expressionResultList = path.node.quasi.expressions.map(n => path.evaluate(path.createChild(n)) ) || []; return func(templateObject, ...expressionResultList); }, MetaProperty(path) { const obj = path.evaluate(path.createChild(path.node.meta)); return obj[path.node.property.name]; } };
the_stack
* This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import { HTMLStencilElement, JSXBase } from '@stencil/core/internal'; import { OgCalendarDate, OgCalendarSelectionType, OgDateDecorator, } from './components/og-internal-calendar/interfaces/og-calendar-date-decorator'; import { OgDatatableConfig, } from './components/og-datatable/interfaces/og-datatable-column-def'; import { OgListItemOptions, } from './components/og-list-item'; export namespace Components { interface OgButton { /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * The label of the button */ 'label': string; } interface OgCalendar { 'dateDecorator': OgDateDecorator; 'displayedMonths': number; 'loc': string; 'month': number; 'selection': OgCalendarDate[]; 'selectionType': OgCalendarSelectionType; 'showCalendarWeek': boolean; 'year': number; } interface OgCard { /** * The title for this card (optional) */ 'name': string; } interface OgCheckbox { /** * The value of the checkbox */ 'checked': boolean; /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * The label of the checkbox */ 'label': string; } interface OgCombobox { /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * Set the property for the items to define as label. Default: "label" */ 'itemLabelProperty': string; /** * Set the property for the items to define as value. Default: "value" */ 'itemValueProperty': string; /** * An array of items to choose from */ 'items': any[]; /** * Optional placeholder if no value is selected. */ 'placeholder'?: string; /** * The selected value of the combobox */ 'value': string; } interface OgComboboxOptions { /** * Determines, whether the options are disabled or not */ 'disabled': boolean; /** * Set the property for the items to define as label. Default: "label" */ 'itemLabelProperty': string; /** * Set the property for the items to define as value. Default: "value" */ 'itemValueProperty': string; /** * An array of items to choose from */ 'items': any[]; /** * The selected value */ 'value': string; /** * Determines, whether the options are visible or not */ 'visible': boolean; } interface OgConfirmDialog { /** * Label for cancel button. */ 'cancelLabel': string; /** * Label for confirmation button. */ 'confirmLabel': string; /** * The title for this modal dialog */ 'name': string; /** * Optional SVG Icon as markup. */ 'svgIcon': string; /** * Visibility state of this dialog. */ 'visible': boolean; } interface OgDatatable { /** * Table configuration (type OgDatatableConfig) */ 'config': OgDatatableConfig; /** * Triggers a reload of the table data. */ 'reloadData': () => Promise<void>; /** * Selected row identified by id-property */ 'selected': any; /** * Programatically update selected row by idProperty. */ 'setSelection': (id: any) => Promise<void>; } interface OgDatepicker { /** * The date decorator can be used to highlight special dates like public holidays or meetings. */ 'dateDecorator': OgDateDecorator; /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * Defines the date string format. The value will be parsed and emitted using this format. */ 'format': string; /** * Locale for this datepicker (country code in ISO 3166 format) */ 'loc': string; /** * Optional placeholder if no value is selected. */ 'placeholder'?: string; /** * The selected value of the combobox */ 'value': string; } interface OgDialog { /** * The title for this modal dialog. */ 'name': string; /** * SVG markup that can be styled by orgenic themes. */ 'svgIcon': string; /** * Visibility state of this dialog. */ 'visible': boolean; } interface OgExpander { /** * Sets or unsets the expanded state. */ 'expanded': boolean; /** * Optional group identifier for this expander. Expanders with same group will behave like an accordion, opening one expander will close other expanders. */ 'group': string; /** * The name for this expander */ 'name': string; /** * Use this method to toggle expanded state. Group property is respected when calling this method. */ 'toggleExpandedState': () => Promise<void>; } interface OgFormItem { 'disabled': boolean; /** * The label for the form item */ 'label': string; } interface OgInternalCalendar { 'dateDecorator': OgDateDecorator; 'loc': string; 'month': number; 'selection': OgCalendarDate[]; 'showCalendarWeek': boolean; 'year': number; } interface OgLayoutChild { /** * The maximum size of the layout child. Can be pixel (e.g. 250px) or percent (e.g. 50%). */ 'maxSize': string; /** * The minimum size of the layout child. Can be pixel (e.g. 150px) or percent (e.g. 30%). */ 'minSize': string; /** * The weight defines the resize behavior. A component with weight 2 will be twice as large as a component with weight 1. Default: "1" */ 'weight': number; } interface OgLayoutContainer { /** * If auto responsive is set to true, the horizontal aligned components within this layout will wrap if the available space is insufficient. Default: "false" */ 'autoResponsive': boolean; /** * Scale all layout children to fill available space (fill: "true") or just keep them left aligned (fill: "false"). Default: "true" */ 'fill': boolean; /** * Direction of the layout container ("horizontal" / "vertical"). Default: "horizontal" */ 'orientation': 'vertical' | 'horizontal'; } interface OgList { /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * Set the property for the items to define as disabled. Default: 'disabled' */ 'disabledProperty': string; /** * Set the text that will be displayed if the items array is empty. */ 'emptyListMessage': string; /** * Set the property for the items to define as image url. *Optional* Default: no image */ 'imageUrlProperty'?: string; /** * An array of items to choose from */ 'items': any[]; /** * Set the property for the items to define as value. Default: 'key' */ 'keyProperty': string; /** * Set the property for the items to define as label. Default: 'label' */ 'labelProperty': string; /** * Enables selection of multiple items */ 'multiselect': boolean; /** * Requires a selection of at least one item. If one item is selected it prevents the user from deselecting it */ 'required': boolean; /** * Key(s) of the selected list item(s) */ 'selected': string | string[]; /** * Name of the template (component) we want to use as list item. */ 'template': string; /** * Contains an Object with options to match template properties. Mandatory: {key: any} Default template: {key: any, label: string, subline: string, overline: string, image: string, value: string, disabled: string} */ 'templateOptions': any; /** * Set the property for the items to define as value. *Optional* Default: no value */ 'valueProperty': string; } interface OgListItem { /** * Set the flag, it this list item is in disabled state. * @type {boolean} * @memberof OgListItem */ 'disabled': boolean; /** * Current item data */ 'item': any; /** * Template options * @type {OgListItemOptions} * @memberof OgListItem */ 'options': OgListItemOptions; /** * Set the flag, if this list item is in selected state. * @type {boolean} * @memberof OgListItem */ 'selected': boolean; } interface OgMessageDialog { /** * Label for approve button. */ 'approveLabel': string; /** * The title for this modal dialog */ 'name': string; /** * Optional SVG Icon as markup. */ 'svgIcon': string; /** * Dialog type can be: success / warning / error / info with. An icon as well as the icon color will be automatically assigned. */ 'type': 'success' | 'warning' | 'error' | 'info'; /** * Visibility state of this dialog. */ 'visible': boolean; } interface OgNumberInput { /** * Determines, whether the control is disabled or not. */ 'disabled': boolean; /** * Maximum value for this component. */ 'max': number; /** * Minimum value for this component. */ 'min': number; /** * Optional placeholder text if input is empty. */ 'placeholder'?: string; /** * Increment or decrement steps for the value. */ 'step': number; /** * The initial value. Can be updated at runtime. */ 'value': number; } interface OgPasswordInput { /** * Determines, whether the control is disabled or not. */ 'disabled': boolean; /** * Optional placeholder text if input is empty. */ 'placeholder'?: string; /** * Define, whether a switch should be visible, to show the password in plain text. */ 'showTogglePasswordVisibility': boolean; 'togglePasswordVisibility': () => Promise<void>; /** * The initial value. Can be updated at runtime. */ 'value': string; } interface OgProgress { /** * Determines, whether the bounce animation is shown or not */ 'bounce': boolean; /** * The percent value of the progress buffer (the second bar) */ 'buffer': number; /** * Determines, whether the control is hidden or not */ 'hidden': boolean; /** * Determines, whether the control is an indeterminate bar or not */ 'indeterminate': boolean; /** * The max value of the progress */ 'max': number; /** * Determines, whether the query animation is shown or not */ 'query': boolean; /** * The height (s, m , l) of the progress bar */ 'size': 's' | 'm' | 'l'; /** * Determines, whether the stream animation is shown or not */ 'stream': boolean; /** * The percent value of the progress */ 'value': number; } interface OgRadioButton { /** * Determines, whether the radio button is checked or not */ 'checked': boolean; /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * Determines, whether the control is disabled from the parent group */ 'groupDisabled': boolean; /** * The label of the radio button */ 'label': string; /** * The name of the radio button. All radio buttons with the same name belong to one group. */ 'name': string; /** * The value of the radio button that is set to the parent group if radio button is selected */ 'value': string; } interface OgRadioButtonGroup { /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * name for the radio buttons within this group */ 'name': string; /** * The value of the selected radio button. */ 'value': string; } interface OgSpinner { /** * Determines, whether the control is hidden or not * @type {boolean} */ 'hidden': boolean; /** * The size of the spinner (s/m/l) * @type {'s' | 'm' | 'l'} */ 'size': 's' | 'm' | 'l'; } interface OgTab { /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * The label of the tab */ 'label': string; 'selected': boolean; } interface OgTabContainer { /** * Determines, whether the control is disabled or not */ 'disabled': boolean; 'openTab': (index: number) => Promise<HTMLElement>; } interface OgTextInput { /** * Determines, whether the control is disabled or not. */ 'disabled': boolean; /** * Optional placeholder text if input is empty. */ 'placeholder'?: string; /** * The initial value. Can be updated at runtime. */ 'value': string; } interface OgTextarea { /** * Determines, whether the control is disabled or not. */ 'disabled': boolean; /** * The initial value. Can be updated at runtime. */ 'value': string; } interface OgToggleSwitch { /** * Determines, whether the control is disabled or not */ 'disabled': boolean; /** * The value of the toggle-switch */ 'value': boolean; } } declare global { interface HTMLOgButtonElement extends Components.OgButton, HTMLStencilElement {} var HTMLOgButtonElement: { prototype: HTMLOgButtonElement; new (): HTMLOgButtonElement; }; interface HTMLOgCalendarElement extends Components.OgCalendar, HTMLStencilElement {} var HTMLOgCalendarElement: { prototype: HTMLOgCalendarElement; new (): HTMLOgCalendarElement; }; interface HTMLOgCardElement extends Components.OgCard, HTMLStencilElement {} var HTMLOgCardElement: { prototype: HTMLOgCardElement; new (): HTMLOgCardElement; }; interface HTMLOgCheckboxElement extends Components.OgCheckbox, HTMLStencilElement {} var HTMLOgCheckboxElement: { prototype: HTMLOgCheckboxElement; new (): HTMLOgCheckboxElement; }; interface HTMLOgComboboxElement extends Components.OgCombobox, HTMLStencilElement {} var HTMLOgComboboxElement: { prototype: HTMLOgComboboxElement; new (): HTMLOgComboboxElement; }; interface HTMLOgComboboxOptionsElement extends Components.OgComboboxOptions, HTMLStencilElement {} var HTMLOgComboboxOptionsElement: { prototype: HTMLOgComboboxOptionsElement; new (): HTMLOgComboboxOptionsElement; }; interface HTMLOgConfirmDialogElement extends Components.OgConfirmDialog, HTMLStencilElement {} var HTMLOgConfirmDialogElement: { prototype: HTMLOgConfirmDialogElement; new (): HTMLOgConfirmDialogElement; }; interface HTMLOgDatatableElement extends Components.OgDatatable, HTMLStencilElement {} var HTMLOgDatatableElement: { prototype: HTMLOgDatatableElement; new (): HTMLOgDatatableElement; }; interface HTMLOgDatepickerElement extends Components.OgDatepicker, HTMLStencilElement {} var HTMLOgDatepickerElement: { prototype: HTMLOgDatepickerElement; new (): HTMLOgDatepickerElement; }; interface HTMLOgDialogElement extends Components.OgDialog, HTMLStencilElement {} var HTMLOgDialogElement: { prototype: HTMLOgDialogElement; new (): HTMLOgDialogElement; }; interface HTMLOgExpanderElement extends Components.OgExpander, HTMLStencilElement {} var HTMLOgExpanderElement: { prototype: HTMLOgExpanderElement; new (): HTMLOgExpanderElement; }; interface HTMLOgFormItemElement extends Components.OgFormItem, HTMLStencilElement {} var HTMLOgFormItemElement: { prototype: HTMLOgFormItemElement; new (): HTMLOgFormItemElement; }; interface HTMLOgInternalCalendarElement extends Components.OgInternalCalendar, HTMLStencilElement {} var HTMLOgInternalCalendarElement: { prototype: HTMLOgInternalCalendarElement; new (): HTMLOgInternalCalendarElement; }; interface HTMLOgLayoutChildElement extends Components.OgLayoutChild, HTMLStencilElement {} var HTMLOgLayoutChildElement: { prototype: HTMLOgLayoutChildElement; new (): HTMLOgLayoutChildElement; }; interface HTMLOgLayoutContainerElement extends Components.OgLayoutContainer, HTMLStencilElement {} var HTMLOgLayoutContainerElement: { prototype: HTMLOgLayoutContainerElement; new (): HTMLOgLayoutContainerElement; }; interface HTMLOgListElement extends Components.OgList, HTMLStencilElement {} var HTMLOgListElement: { prototype: HTMLOgListElement; new (): HTMLOgListElement; }; interface HTMLOgListItemElement extends Components.OgListItem, HTMLStencilElement {} var HTMLOgListItemElement: { prototype: HTMLOgListItemElement; new (): HTMLOgListItemElement; }; interface HTMLOgMessageDialogElement extends Components.OgMessageDialog, HTMLStencilElement {} var HTMLOgMessageDialogElement: { prototype: HTMLOgMessageDialogElement; new (): HTMLOgMessageDialogElement; }; interface HTMLOgNumberInputElement extends Components.OgNumberInput, HTMLStencilElement {} var HTMLOgNumberInputElement: { prototype: HTMLOgNumberInputElement; new (): HTMLOgNumberInputElement; }; interface HTMLOgPasswordInputElement extends Components.OgPasswordInput, HTMLStencilElement {} var HTMLOgPasswordInputElement: { prototype: HTMLOgPasswordInputElement; new (): HTMLOgPasswordInputElement; }; interface HTMLOgProgressElement extends Components.OgProgress, HTMLStencilElement {} var HTMLOgProgressElement: { prototype: HTMLOgProgressElement; new (): HTMLOgProgressElement; }; interface HTMLOgRadioButtonElement extends Components.OgRadioButton, HTMLStencilElement {} var HTMLOgRadioButtonElement: { prototype: HTMLOgRadioButtonElement; new (): HTMLOgRadioButtonElement; }; interface HTMLOgRadioButtonGroupElement extends Components.OgRadioButtonGroup, HTMLStencilElement {} var HTMLOgRadioButtonGroupElement: { prototype: HTMLOgRadioButtonGroupElement; new (): HTMLOgRadioButtonGroupElement; }; interface HTMLOgSpinnerElement extends Components.OgSpinner, HTMLStencilElement {} var HTMLOgSpinnerElement: { prototype: HTMLOgSpinnerElement; new (): HTMLOgSpinnerElement; }; interface HTMLOgTabElement extends Components.OgTab, HTMLStencilElement {} var HTMLOgTabElement: { prototype: HTMLOgTabElement; new (): HTMLOgTabElement; }; interface HTMLOgTabContainerElement extends Components.OgTabContainer, HTMLStencilElement {} var HTMLOgTabContainerElement: { prototype: HTMLOgTabContainerElement; new (): HTMLOgTabContainerElement; }; interface HTMLOgTextInputElement extends Components.OgTextInput, HTMLStencilElement {} var HTMLOgTextInputElement: { prototype: HTMLOgTextInputElement; new (): HTMLOgTextInputElement; }; interface HTMLOgTextareaElement extends Components.OgTextarea, HTMLStencilElement {} var HTMLOgTextareaElement: { prototype: HTMLOgTextareaElement; new (): HTMLOgTextareaElement; }; interface HTMLOgToggleSwitchElement extends Components.OgToggleSwitch, HTMLStencilElement {} var HTMLOgToggleSwitchElement: { prototype: HTMLOgToggleSwitchElement; new (): HTMLOgToggleSwitchElement; }; interface HTMLElementTagNameMap { 'og-button': HTMLOgButtonElement; 'og-calendar': HTMLOgCalendarElement; 'og-card': HTMLOgCardElement; 'og-checkbox': HTMLOgCheckboxElement; 'og-combobox': HTMLOgComboboxElement; 'og-combobox-options': HTMLOgComboboxOptionsElement; 'og-confirm-dialog': HTMLOgConfirmDialogElement; 'og-datatable': HTMLOgDatatableElement; 'og-datepicker': HTMLOgDatepickerElement; 'og-dialog': HTMLOgDialogElement; 'og-expander': HTMLOgExpanderElement; 'og-form-item': HTMLOgFormItemElement; 'og-internal-calendar': HTMLOgInternalCalendarElement; 'og-layout-child': HTMLOgLayoutChildElement; 'og-layout-container': HTMLOgLayoutContainerElement; 'og-list': HTMLOgListElement; 'og-list-item': HTMLOgListItemElement; 'og-message-dialog': HTMLOgMessageDialogElement; 'og-number-input': HTMLOgNumberInputElement; 'og-password-input': HTMLOgPasswordInputElement; 'og-progress': HTMLOgProgressElement; 'og-radio-button': HTMLOgRadioButtonElement; 'og-radio-button-group': HTMLOgRadioButtonGroupElement; 'og-spinner': HTMLOgSpinnerElement; 'og-tab': HTMLOgTabElement; 'og-tab-container': HTMLOgTabContainerElement; 'og-text-input': HTMLOgTextInputElement; 'og-textarea': HTMLOgTextareaElement; 'og-toggle-switch': HTMLOgToggleSwitchElement; } } declare namespace LocalJSX { interface OgButton { /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * The label of the button */ 'label'?: string; /** * Event is being emitted when value changes. */ 'onClicked'?: (event: CustomEvent<any>) => void; } interface OgCalendar { 'dateDecorator'?: OgDateDecorator; 'displayedMonths'?: number; 'loc'?: string; 'month'?: number; 'onDateClicked'?: (event: CustomEvent<OgCalendarDate>) => void; 'onSelectionChanged'?: (event: CustomEvent<OgCalendarDate[]>) => void; 'selection'?: OgCalendarDate[]; 'selectionType'?: OgCalendarSelectionType; 'showCalendarWeek'?: boolean; 'year'?: number; } interface OgCard { /** * The title for this card (optional) */ 'name'?: string; } interface OgCheckbox { /** * The value of the checkbox */ 'checked'?: boolean; /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * The label of the checkbox */ 'label'?: string; /** * Event is being emitted when value changes. */ 'onChanged'?: (event: CustomEvent<MouseEvent>) => void; } interface OgCombobox { /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * Set the property for the items to define as label. Default: "label" */ 'itemLabelProperty'?: string; /** * Set the property for the items to define as value. Default: "value" */ 'itemValueProperty'?: string; /** * An array of items to choose from */ 'items'?: any[]; /** * Event is being emitted when input gets focus.. */ 'onFocusGained'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when focus gets lost. */ 'onFocusLost'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when value changes. */ 'onItemSelected'?: (event: CustomEvent<any>) => void; /** * Optional placeholder if no value is selected. */ 'placeholder'?: string; /** * The selected value of the combobox */ 'value'?: string; } interface OgComboboxOptions { /** * Determines, whether the options are disabled or not */ 'disabled'?: boolean; /** * Set the property for the items to define as label. Default: "label" */ 'itemLabelProperty'?: string; /** * Set the property for the items to define as value. Default: "value" */ 'itemValueProperty'?: string; /** * An array of items to choose from */ 'items'?: any[]; /** * Event is being emitted when value changes. */ 'onItemSelected'?: (event: CustomEvent<any>) => void; /** * The selected value */ 'value'?: string; /** * Determines, whether the options are visible or not */ 'visible'?: boolean; } interface OgConfirmDialog { /** * Label for cancel button. */ 'cancelLabel'?: string; /** * Label for confirmation button. */ 'confirmLabel'?: string; /** * The title for this modal dialog */ 'name'?: string; /** * Event is being emitted when value changes. */ 'onCancelled'?: (event: CustomEvent<any>) => void; /** * Event is being emitted when value changes. */ 'onConfirmed'?: (event: CustomEvent<any>) => void; /** * Optional SVG Icon as markup. */ 'svgIcon'?: string; /** * Visibility state of this dialog. */ 'visible'?: boolean; } interface OgDatatable { /** * Table configuration (type OgDatatableConfig) */ 'config'?: OgDatatableConfig; /** * Item selection event. Event.detail contains selected item. */ 'onItemSelected'?: (event: CustomEvent<any>) => void; /** * Selected row identified by id-property */ 'selected'?: any; } interface OgDatepicker { /** * The date decorator can be used to highlight special dates like public holidays or meetings. */ 'dateDecorator'?: OgDateDecorator; /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * Defines the date string format. The value will be parsed and emitted using this format. */ 'format'?: string; /** * Locale for this datepicker (country code in ISO 3166 format) */ 'loc'?: string; /** * Event is being emitted when selected date changes. */ 'onDateSelected'?: (event: CustomEvent<any>) => void; /** * Event is being emitted when input gets focus.. */ 'onFocusGained'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when focus gets lost. */ 'onFocusLost'?: (event: CustomEvent<FocusEvent>) => void; /** * Optional placeholder if no value is selected. */ 'placeholder'?: string; /** * The selected value of the combobox */ 'value'?: string; } interface OgDialog { /** * The title for this modal dialog. */ 'name'?: string; /** * SVG markup that can be styled by orgenic themes. */ 'svgIcon'?: string; /** * Visibility state of this dialog. */ 'visible'?: boolean; } interface OgExpander { /** * Sets or unsets the expanded state. */ 'expanded'?: boolean; /** * Optional group identifier for this expander. Expanders with same group will behave like an accordion, opening one expander will close other expanders. */ 'group'?: string; /** * The name for this expander */ 'name'?: string; } interface OgFormItem { 'disabled'?: boolean; /** * The label for the form item */ 'label'?: string; } interface OgInternalCalendar { 'dateDecorator'?: OgDateDecorator; 'loc'?: string; 'month'?: number; 'onDateClicked'?: (event: CustomEvent<any>) => void; 'selection'?: OgCalendarDate[]; 'showCalendarWeek'?: boolean; 'year'?: number; } interface OgLayoutChild { /** * The maximum size of the layout child. Can be pixel (e.g. 250px) or percent (e.g. 50%). */ 'maxSize'?: string; /** * The minimum size of the layout child. Can be pixel (e.g. 150px) or percent (e.g. 30%). */ 'minSize'?: string; /** * The weight defines the resize behavior. A component with weight 2 will be twice as large as a component with weight 1. Default: "1" */ 'weight'?: number; } interface OgLayoutContainer { /** * If auto responsive is set to true, the horizontal aligned components within this layout will wrap if the available space is insufficient. Default: "false" */ 'autoResponsive'?: boolean; /** * Scale all layout children to fill available space (fill: "true") or just keep them left aligned (fill: "false"). Default: "true" */ 'fill'?: boolean; /** * Direction of the layout container ("horizontal" / "vertical"). Default: "horizontal" */ 'orientation'?: 'vertical' | 'horizontal'; } interface OgList { /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * Set the property for the items to define as disabled. Default: 'disabled' */ 'disabledProperty'?: string; /** * Set the text that will be displayed if the items array is empty. */ 'emptyListMessage'?: string; /** * Set the property for the items to define as image url. *Optional* Default: no image */ 'imageUrlProperty'?: string; /** * An array of items to choose from */ 'items'?: any[]; /** * Set the property for the items to define as value. Default: 'key' */ 'keyProperty'?: string; /** * Set the property for the items to define as label. Default: 'label' */ 'labelProperty'?: string; /** * Enables selection of multiple items */ 'multiselect'?: boolean; /** * Event is being emitted when value changes. */ 'onItemSelected'?: (event: CustomEvent<any>) => void; /** * Requires a selection of at least one item. If one item is selected it prevents the user from deselecting it */ 'required'?: boolean; /** * Key(s) of the selected list item(s) */ 'selected'?: string | string[]; /** * Name of the template (component) we want to use as list item. */ 'template'?: string; /** * Contains an Object with options to match template properties. Mandatory: {key: any} Default template: {key: any, label: string, subline: string, overline: string, image: string, value: string, disabled: string} */ 'templateOptions'?: any; /** * Set the property for the items to define as value. *Optional* Default: no value */ 'valueProperty'?: string; } interface OgListItem { /** * Set the flag, it this list item is in disabled state. * @type {boolean} * @memberof OgListItem */ 'disabled'?: boolean; /** * Current item data */ 'item'?: any; /** * Template options * @type {OgListItemOptions} * @memberof OgListItem */ 'options'?: OgListItemOptions; /** * Set the flag, if this list item is in selected state. * @type {boolean} * @memberof OgListItem */ 'selected'?: boolean; } interface OgMessageDialog { /** * Label for approve button. */ 'approveLabel'?: string; /** * The title for this modal dialog */ 'name'?: string; /** * Event is being emitted when value changes. */ 'onConfirmed'?: (event: CustomEvent<any>) => void; /** * Optional SVG Icon as markup. */ 'svgIcon'?: string; /** * Dialog type can be: success / warning / error / info with. An icon as well as the icon color will be automatically assigned. */ 'type'?: 'success' | 'warning' | 'error' | 'info'; /** * Visibility state of this dialog. */ 'visible'?: boolean; } interface OgNumberInput { /** * Determines, whether the control is disabled or not. */ 'disabled'?: boolean; /** * Maximum value for this component. */ 'max'?: number; /** * Minimum value for this component. */ 'min'?: number; /** * Event is being emitted when input gets focus.. */ 'onFocusGained'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when focus gets lost. */ 'onFocusLost'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when value changes. */ 'onValueChanged'?: (event: CustomEvent<number>) => void; /** * Optional placeholder text if input is empty. */ 'placeholder'?: string; /** * Increment or decrement steps for the value. */ 'step'?: number; /** * The initial value. Can be updated at runtime. */ 'value'?: number; } interface OgPasswordInput { /** * Determines, whether the control is disabled or not. */ 'disabled'?: boolean; /** * Event is being emitted when input gets focus.. */ 'onFocusGained'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when focus gets lost. */ 'onFocusLost'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when value changes. */ 'onValueChanged'?: (event: CustomEvent<string>) => void; /** * Optional placeholder text if input is empty. */ 'placeholder'?: string; /** * Define, whether a switch should be visible, to show the password in plain text. */ 'showTogglePasswordVisibility'?: boolean; /** * The initial value. Can be updated at runtime. */ 'value'?: string; } interface OgProgress { /** * Determines, whether the bounce animation is shown or not */ 'bounce'?: boolean; /** * The percent value of the progress buffer (the second bar) */ 'buffer'?: number; /** * Determines, whether the control is hidden or not */ 'hidden'?: boolean; /** * Determines, whether the control is an indeterminate bar or not */ 'indeterminate'?: boolean; /** * The max value of the progress */ 'max'?: number; /** * Determines, whether the query animation is shown or not */ 'query'?: boolean; /** * The height (s, m , l) of the progress bar */ 'size'?: 's' | 'm' | 'l'; /** * Determines, whether the stream animation is shown or not */ 'stream'?: boolean; /** * The percent value of the progress */ 'value'?: number; } interface OgRadioButton { /** * Determines, whether the radio button is checked or not */ 'checked'?: boolean; /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * Determines, whether the control is disabled from the parent group */ 'groupDisabled'?: boolean; /** * The label of the radio button */ 'label'?: string; /** * The name of the radio button. All radio buttons with the same name belong to one group. */ 'name'?: string; 'onChanged'?: (event: CustomEvent<MouseEvent>) => void; /** * The value of the radio button that is set to the parent group if radio button is selected */ 'value'?: string; } interface OgRadioButtonGroup { /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * name for the radio buttons within this group */ 'name'?: string; 'onValueChanged'?: (event: CustomEvent<string>) => void; /** * The value of the selected radio button. */ 'value'?: string; } interface OgSpinner { /** * Determines, whether the control is hidden or not * @type {boolean} */ 'hidden'?: boolean; /** * The size of the spinner (s/m/l) * @type {'s' | 'm' | 'l'} */ 'size'?: 's' | 'm' | 'l'; } interface OgTab { /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * The label of the tab */ 'label'?: string; 'selected'?: boolean; } interface OgTabContainer { /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * Event is being emitted when value changes. */ 'onTabSelected'?: (event: CustomEvent<number>) => void; } interface OgTextInput { /** * Determines, whether the control is disabled or not. */ 'disabled'?: boolean; /** * Event is being emitted when input gets focus.. */ 'onFocusGained'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when focus gets lost. */ 'onFocusLost'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when value changes. */ 'onValueChanged'?: (event: CustomEvent<string>) => void; /** * Optional placeholder text if input is empty. */ 'placeholder'?: string; /** * The initial value. Can be updated at runtime. */ 'value'?: string; } interface OgTextarea { /** * Determines, whether the control is disabled or not. */ 'disabled'?: boolean; /** * Event is being emitted when input gets focus. */ 'onFocusGained'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when focus gets lost. */ 'onFocusLost'?: (event: CustomEvent<FocusEvent>) => void; /** * Event is being emitted when value changes. */ 'onValueChanged'?: (event: CustomEvent<string>) => void; /** * The initial value. Can be updated at runtime. */ 'value'?: string; } interface OgToggleSwitch { /** * Determines, whether the control is disabled or not */ 'disabled'?: boolean; /** * Event is being emitted when value changes. */ 'onChanged'?: (event: CustomEvent<MouseEvent>) => void; /** * The value of the toggle-switch */ 'value'?: boolean; } interface IntrinsicElements { 'og-button': OgButton; 'og-calendar': OgCalendar; 'og-card': OgCard; 'og-checkbox': OgCheckbox; 'og-combobox': OgCombobox; 'og-combobox-options': OgComboboxOptions; 'og-confirm-dialog': OgConfirmDialog; 'og-datatable': OgDatatable; 'og-datepicker': OgDatepicker; 'og-dialog': OgDialog; 'og-expander': OgExpander; 'og-form-item': OgFormItem; 'og-internal-calendar': OgInternalCalendar; 'og-layout-child': OgLayoutChild; 'og-layout-container': OgLayoutContainer; 'og-list': OgList; 'og-list-item': OgListItem; 'og-message-dialog': OgMessageDialog; 'og-number-input': OgNumberInput; 'og-password-input': OgPasswordInput; 'og-progress': OgProgress; 'og-radio-button': OgRadioButton; 'og-radio-button-group': OgRadioButtonGroup; 'og-spinner': OgSpinner; 'og-tab': OgTab; 'og-tab-container': OgTabContainer; 'og-text-input': OgTextInput; 'og-textarea': OgTextarea; 'og-toggle-switch': OgToggleSwitch; } } export { LocalJSX as JSX }; declare module "@stencil/core" { export namespace JSX { interface IntrinsicElements { 'og-button': LocalJSX.OgButton & JSXBase.HTMLAttributes<HTMLOgButtonElement>; 'og-calendar': LocalJSX.OgCalendar & JSXBase.HTMLAttributes<HTMLOgCalendarElement>; 'og-card': LocalJSX.OgCard & JSXBase.HTMLAttributes<HTMLOgCardElement>; 'og-checkbox': LocalJSX.OgCheckbox & JSXBase.HTMLAttributes<HTMLOgCheckboxElement>; 'og-combobox': LocalJSX.OgCombobox & JSXBase.HTMLAttributes<HTMLOgComboboxElement>; 'og-combobox-options': LocalJSX.OgComboboxOptions & JSXBase.HTMLAttributes<HTMLOgComboboxOptionsElement>; 'og-confirm-dialog': LocalJSX.OgConfirmDialog & JSXBase.HTMLAttributes<HTMLOgConfirmDialogElement>; 'og-datatable': LocalJSX.OgDatatable & JSXBase.HTMLAttributes<HTMLOgDatatableElement>; 'og-datepicker': LocalJSX.OgDatepicker & JSXBase.HTMLAttributes<HTMLOgDatepickerElement>; 'og-dialog': LocalJSX.OgDialog & JSXBase.HTMLAttributes<HTMLOgDialogElement>; 'og-expander': LocalJSX.OgExpander & JSXBase.HTMLAttributes<HTMLOgExpanderElement>; 'og-form-item': LocalJSX.OgFormItem & JSXBase.HTMLAttributes<HTMLOgFormItemElement>; 'og-internal-calendar': LocalJSX.OgInternalCalendar & JSXBase.HTMLAttributes<HTMLOgInternalCalendarElement>; 'og-layout-child': LocalJSX.OgLayoutChild & JSXBase.HTMLAttributes<HTMLOgLayoutChildElement>; 'og-layout-container': LocalJSX.OgLayoutContainer & JSXBase.HTMLAttributes<HTMLOgLayoutContainerElement>; 'og-list': LocalJSX.OgList & JSXBase.HTMLAttributes<HTMLOgListElement>; 'og-list-item': LocalJSX.OgListItem & JSXBase.HTMLAttributes<HTMLOgListItemElement>; 'og-message-dialog': LocalJSX.OgMessageDialog & JSXBase.HTMLAttributes<HTMLOgMessageDialogElement>; 'og-number-input': LocalJSX.OgNumberInput & JSXBase.HTMLAttributes<HTMLOgNumberInputElement>; 'og-password-input': LocalJSX.OgPasswordInput & JSXBase.HTMLAttributes<HTMLOgPasswordInputElement>; 'og-progress': LocalJSX.OgProgress & JSXBase.HTMLAttributes<HTMLOgProgressElement>; 'og-radio-button': LocalJSX.OgRadioButton & JSXBase.HTMLAttributes<HTMLOgRadioButtonElement>; 'og-radio-button-group': LocalJSX.OgRadioButtonGroup & JSXBase.HTMLAttributes<HTMLOgRadioButtonGroupElement>; 'og-spinner': LocalJSX.OgSpinner & JSXBase.HTMLAttributes<HTMLOgSpinnerElement>; 'og-tab': LocalJSX.OgTab & JSXBase.HTMLAttributes<HTMLOgTabElement>; 'og-tab-container': LocalJSX.OgTabContainer & JSXBase.HTMLAttributes<HTMLOgTabContainerElement>; 'og-text-input': LocalJSX.OgTextInput & JSXBase.HTMLAttributes<HTMLOgTextInputElement>; 'og-textarea': LocalJSX.OgTextarea & JSXBase.HTMLAttributes<HTMLOgTextareaElement>; 'og-toggle-switch': LocalJSX.OgToggleSwitch & JSXBase.HTMLAttributes<HTMLOgToggleSwitchElement>; } } }
the_stack
import { Component } from 'vue-property-decorator'; import { histogram, Bin } from 'd3-array'; import { scaleLinear, ScaleBand } from 'd3-scale'; import { select } from 'd3-selection'; import _ from 'lodash'; import $ from 'jquery'; import { injectVisualizationTemplate, Visualization, drawBrushBox, getBrushBox, Scale, PlotMargins, DEFAULT_PLOT_MARGINS, AnyScale, getScale, drawAxis, LABEL_OFFSET_PX, multiplyVisuals, OrdinalScaleType, } from '@/components/visualization'; import FormInput from '@/components/form-input/form-input'; import template from './histogram.html'; import { isNumericalType, isContinuousDomain } from '@/data/util'; import { ValueType } from '@/data/parser'; import { VisualProperties, visualsComparator } from '@/data/visuals'; import { SELECTED_COLOR } from '@/common/constants'; import { getTransform, fadeOut } from '@/common/util'; import ColumnSelect from '@/components/column-select/column-select'; import * as history from './history'; import { SubsetSelection } from '@/data/package'; const DOMAIN_MARGIN = .2; const BAR_INTERVAL = 1; export interface HistogramSelection { selection: SubsetSelection; selectedBars: Set<string>; } interface HistogramSave { column: number | null; numBins: number; maxCount: number | null; selectedBars: string[]; useDatasetRange: boolean; } interface HistogramBinProps { id: string; x0: number; x1: number; y: number; bars: HistogramBarProps[]; } interface HistogramBarProps { id: string; x: number; y: number; dx: number; dy: number; originalVisuals: VisualProperties; // Original visual properties are kept intact during rendering. visuals: VisualProperties; // Rendered isual properties can be modified based on whether bars are selected. members: number[]; hasVisuals: boolean; selected: boolean; } interface HistogramValueBinProps { value: number; index: number; } const DEFAULT_ITEM_VISUALS: VisualProperties = { color: '#555', opacity: 1, }; const SELECTED_ITEM_VISUALS: VisualProperties = { color: 'white', border: SELECTED_COLOR, width: 1.5, }; @Component({ template: injectVisualizationTemplate(template), components: { FormInput, ColumnSelect, }, }) export default class Histogram extends Visualization { protected NODE_TYPE = 'histogram'; protected DEFAULT_WIDTH = 350; protected DEFAULT_HEIGHT = 200; private column: number | null = null; private numBins = 10; private maxCount: number | null = null; private xScale!: Scale; private yScale!: Scale; private valueBins: Array<Bin<HistogramValueBinProps, number>> = []; private bins: HistogramBinProps[] = []; private selectedBars: Set<string> = new Set(); private prevSelectedBars: Set<string> = new Set(); private useDatasetRange = false; private margins: PlotMargins = _.extend({}, DEFAULT_PLOT_MARGINS, { bottom: 20 }); /** * Disables the num bins input when the chosen column is not continuous. */ get isNumBinsDisabled(): boolean { return !this.hasNoDataset() && this.column != null && !isContinuousDomain(this.getDataset().getColumnType(this.column)); } public setHistogramSelection({ selection, selectedBars }: { selection: number[], selectedBars: string[] }) { this.selection.setItems(selection); this.selectedBars = new Set(selectedBars); this.onSelectionUpdate(); } public setColumn(column: number) { this.column = column; this.draw(); } public setUseDatasetRange(value: boolean) { this.useDatasetRange = value; this.draw(); } public applyColumns(columns: number[]) { if (!columns.length) { this.findDefaultColumns(); } else { this.column = columns[0]; } if (this.hasDataset()) { this.draw(); } } public setNumBins(value: number) { this.numBins = value; this.draw(); } public setMaxCount(count: number | null) { this.maxCount = count; this.draw(); } protected created() { this.serializationChain.push((): HistogramSave => ({ column: this.column, numBins: this.numBins, maxCount: this.maxCount, selectedBars: Array.from(this.selectedBars), useDatasetRange: this.useDatasetRange, })); this.deserializationChain.push(nodeSave => { const save = nodeSave as HistogramSave; this.selectedBars = new Set(save.selectedBars); }); } protected brushed(brushPoints: Point[], isBrushStop?: boolean) { if (isBrushStop) { this.computeBrushedItems(brushPoints); this.computeSelection(); this.drawHistogram(); this.propagateSelection(); } drawBrushBox(this.$refs.brush as SVGElement, !isBrushStop ? brushPoints : []); } protected executeSelectAll() { const items = this.inputPortMap.in.getSubsetPackage().getItemIndices(); this.selection.addItems(items); this.bins.forEach(bin => { bin.bars.forEach(bar => { this.selectedBars.add(bar.id); }); }); } protected executeDeselectAll() { this.selectedBars.clear(); this.selection.clear(); } protected commitSelectionHistory(message: string) { if (_.isEqual(this.selectedBars, this.prevSelectedBars)) { return; } this.commitHistory(history.interactiveSelectionEvent(this, { selection: this.selection, selectedBars: this.selectedBars }, { selection: this.prevSelection, selectedBars: this.prevSelectedBars }, message, )); } protected recordPrevSelection() { this.prevSelection = this.selection.clone(); this.prevSelectedBars = _.clone(this.selectedBars); } protected draw() { this.drawHistogram(); this.drawXAxis(); this.drawYAxis(); } protected findDefaultColumns() { if (!this.hasDataset()) { return; } if (this.column !== null) { this.column = this.updateColumnOnDatasetChange(this.column); } else { const numericalColumns = this.getDataset().getColumns().filter(column => isNumericalType(column.type)); this.column = numericalColumns.length ? numericalColumns[0].index : null; } } private drawHistogram() { // First compute the x scale which is solely based on data. this.computeXScale(); // Then compute histogram bins using D3. this.computeBins(); // Based on the bins we can compute the y scale. this.computeYScale(); this.updateLeftMargin(); this.assignItemsIntoBins(); this.applyItemProps(); this.drawBars(); this.moveSelectedBarsToFront(); } private moveSelectedBarsToFront() { const svgBars = $(this.$refs.bars); svgBars.find('rect[has-visuals=true]').each((index, element) => { $(element).appendTo($(element as HTMLElement).closest('g')); }); svgBars.find('rect[is-selected=true]').each((index, element) => { $(element).appendTo($(element as HTMLElement).closest('g')); }); } private computeBrushedItems(brushPoints: Point[]) { if (!this.isShiftPressed || !brushPoints.length) { this.selection.clear(); // reset selection if shift key is not down this.selectedBars.clear(); if (!brushPoints.length) { return; } } const box = getBrushBox(brushPoints); this.bins.forEach(bin => { const xl = bin.x0; const xr = bin.x1; if (xr < box.x || xl > box.x + box.width) { return; } bin.bars.forEach(bar => { const yl = this.yScale(bar.y + bar.dy); const yr = this.yScale(bar.y); if (yr < box.y || yl > box.y + box.height) { return; } this.selectedBars.add(bar.id); this.selection.addItems(bar.members); }); }); } private computeXScale() { const items = this.inputPortMap.in.getSubsetPackage().getItemIndices(); const dataset = this.getDataset(); const xDomain = dataset.getDomain(this.column as number, this.useDatasetRange ? undefined : items); this.xScale = getScale(dataset.getColumnType(this.column as number), xDomain, [this.margins.left, this.svgWidth - this.margins.right], { domainMargin: DOMAIN_MARGIN, ordinal: { type: OrdinalScaleType.BAND, paddingInner: 0, paddingOuter: .5 } }, ); } private computeBins() { // Histogram uses the xScale's range (screen range) as its domain to subdivide bins. const range = this.xScale.range() as number[]; // Bins value for histogram layout. let thresholds: number[] = []; const dataset = this.getDataset(); const columnType = dataset.getColumnType(this.column as number); const continuousDomain = isContinuousDomain(columnType); if (continuousDomain) { // If xScale domain has only a single value, the ticks will return empty // array. That is bins = []. thresholds = (this.xScale as AnyScale).ticks(this.numBins).map(value => this.xScale(value)); // Map dates to POSIX. if (columnType === ValueType.DATE) { // range = range.map(date => new Date(date).getTime()); // thresholds = thresholds.map(date => new Date(date).getTime()); } } else if (!continuousDomain) { const ordinals = this.xScale.domain(); thresholds = ordinals.map(value => this.xScale(value)) as number[]; thresholds.push(this.xScale(_.last(ordinals) as string) + (this.xScale as ScaleBand<string>).bandwidth()); } const pkg = this.inputPortMap.in.getSubsetPackage(); const values = pkg.getItemIndices().map(itemIndex => { const value = dataset.getCellForScale(itemIndex, this.column as number); return { value: this.xScale(value), index: itemIndex, }; }); this.valueBins = histogram<HistogramValueBinProps, number>() .value(d => d.value) .domain(range as [number, number]) .thresholds(thresholds)(values); } private computeYScale() { const maxY = this.maxCount === null ? _.max(this.valueBins.map(d => d.length)) as number : this.maxCount; this.yScale = scaleLinear() .domain([0, maxY]) .nice() .range([this.svgHeight - this.margins.bottom, this.margins.top]) as Scale; } private assignItemsIntoBins() { const pkg = this.inputPortMap.in.getSubsetPackage(); this.bins = this.valueBins.map((valueBin, binIndex) => { // Get d3 histogram coordinates. const x0 = valueBin.x0 as number; const x1 = valueBin.x1 as number; const binLength = valueBin.length; const sorted = valueBin.map(item => ({ visuals: pkg.getItem(item.index).visuals, index: item.index, })).sort((a, b) => visualsComparator(a.visuals, b.visuals)); const bars: HistogramBarProps[] = []; let y = 0; let groupCount = 0; for (let j = 0; j < sorted.length; j++) { let k = j; const members = []; // Get all group members with the same rendering properties. while (k < sorted.length && visualsComparator(sorted[k].visuals, sorted[j].visuals) === 0) { members.push(sorted[k++].index); } bars.push({ id: 'g' + (++groupCount), x: x0, y, dx: x1 - x0, dy: k - j, originalVisuals: sorted[j].visuals, visuals: sorted[j].visuals, hasVisuals: false, selected: false, members, }); y += k - j; // The current accumulative bar height j = k - 1; } return { id: 'b' + binIndex, x0, x1, y: binLength, bars, }; }); } private applyItemProps() { this.bins.forEach(bin => { bin.bars.forEach(bar => { const id = bin.id + ',' + bar.id; _.extend(bar, { id, visuals: _.extend({}, DEFAULT_ITEM_VISUALS, bar.originalVisuals), hasVisuals: !_.isEmpty(bar.originalVisuals), selected: this.selectedBars.has(id), }); if (this.selectedBars.has(id)) { _.extend(bar.visuals, SELECTED_ITEM_VISUALS); multiplyVisuals(bar.visuals); } }); }); } private drawBars() { const numItems = this.inputPortMap.in.getSubsetPackage().numItems(); const binTransform = (bin: HistogramBinProps) => getTransform([bin.x0, 0]); let bins = select(this.$refs.bars as SVGGElement).selectAll<SVGGElement, HistogramBinProps>('g') .data(this.bins); fadeOut(bins.exit()); bins = bins.enter().append<SVGGElement>('g') .attr('id', d => d.id) .style('opacity', 0) .attr('transform', binTransform) .merge(bins); const updatedBins = this.isTransitionFeasible(numItems) ? bins.transition() : bins; updatedBins .attr('transform', binTransform) .style('opacity', 1); const barTransform = (group: HistogramBarProps) => getTransform([BAR_INTERVAL, Math.floor(this.yScale(group.y + group.dy))]); let bars = bins.selectAll<SVGGraphicsElement, HistogramBarProps>('rect') .data(d => d.bars, bar => bar.id); fadeOut(bars.exit()); bars = bars.enter().append<SVGGraphicsElement>('rect') .style('opacity', 0) .attr('id', d => d.id) .attr('transform', barTransform) .merge(bars) .attr('has-visuals', d => d.hasVisuals) .attr('is-selected', d => d.selected); const updatedBars = this.isTransitionFeasible(numItems) ? bars.transition() : bars; updatedBars .attr('transform', barTransform) .attr('width', group => { const width = group.dx - BAR_INTERVAL; // In case interval is larger than width. At least 1 pixel wide. return width < 0 ? 1 : width; }) .attr('height', group => { return Math.ceil(this.yScale(0) - this.yScale(group.dy)); }) .style('fill', d => d.visuals.color as string) .style('stroke', d => d.visuals.border as string) .style('stroke-width', d => d.visuals.width + 'px') .style('opacity', d => d.visuals.opacity as number); } private drawXAxis() { drawAxis(this.$refs.xAxis as SVGElement, this.xScale, { classes: 'x', orient: 'bottom', transform: getTransform([0, this.svgHeight - this.margins.bottom]), label: { text: this.getDataset().getColumnName(this.column as number), transform: getTransform([ this.svgWidth - this.margins.right, -this.svgHeight + this.margins.bottom + this.margins.top + LABEL_OFFSET_PX, ]), }, }); } private drawYAxis() { drawAxis(this.$refs.yAxis as SVGElement, this.yScale, { classes: 'y', orient: 'left', transform: getTransform([this.margins.left, 0]), }); } /** * Determines the maximum length of the y axis ticks and sets the left margin accordingly. */ private updateLeftMargin() { this.drawYAxis(); const prevLeftMargin = this.margins.left; this.updateMargins(() => { const maxTickWidth = _.max($(this.$refs.yAxis as SVGGElement) .find('.y > .tick > text') .map((index: number, element: SVGGraphicsElement) => element.getBBox().width)) || 0; this.margins.left = DEFAULT_PLOT_MARGINS.left + maxTickWidth; if (this.margins.left !== prevLeftMargin) { // Bins are based on left margin, we must update the bins if left margin changes. this.computeXScale(); this.computeBins(); } }); } private onSelectColumn(column: number, prevColumn: number | null) { this.commitHistory(history.selectColumnEvent(this, column, prevColumn)); this.setColumn(column); } private onInputNumBins(value: number, prevValue: number) { this.commitHistory(history.inputNumBinsEvent(this, value, prevValue)); this.setNumBins(value); } private onInputMaxCount(count: number | null, prevCount: number | null) { this.commitHistory(history.inputMaxCountEvent(this, count, prevCount)); this.setMaxCount(count); } private onToggleUseDatasetRange(value: boolean) { this.commitHistory(history.toggleUseDatasetRangeEvent(this, value)); this.setUseDatasetRange(value); } }
the_stack
import { PdfGridColumnCollection } from './pdf-grid-column'; import { PdfGridRow } from './pdf-grid-row'; import { PdfGridCell } from './pdf-grid-cell'; import { PdfGridRowCollection, PdfGridHeaderCollection } from './pdf-grid-row'; import { RectangleF, SizeF, PointF } from './../../drawing/pdf-drawing'; import { PdfPage } from './../../pages/pdf-page'; import { PdfLayoutElement } from './../../graphics/figures/layout-element'; import { PdfLayoutResult, PdfLayoutParams, PdfLayoutFormat } from './../../graphics/figures/base/element-layouter'; import { PdfGridStyle , PdfGridCellStyle} from './styles/style'; import { PdfBorders} from './styles/pdf-borders'; import { PdfGraphics } from './../../graphics/pdf-graphics'; import { PdfGridLayouter, PdfGridLayoutResult } from './../../structured-elements/grid/layout/grid-layouter'; import { PdfGridBeginCellDrawEventArgs, PdfGridEndCellDrawEventArgs} from '../../structured-elements/grid/layout/grid-layouter'; export class PdfGrid extends PdfLayoutElement { //Fields /** * @hidden * @private */ private gridColumns : PdfGridColumnCollection; /** * @hidden * @private */ private gridRows : PdfGridRowCollection; /** * @hidden * @private */ private gridHeaders : PdfGridHeaderCollection; /** * @hidden * @private */ private gridInitialWidth : number ; /** * @hidden * @private */ public isComplete : boolean; /** * @hidden * @private */ private gridSize : SizeF = new SizeF(0, 0); /** * @hidden * @private */ private layoutFormat : PdfLayoutFormat; /** * @hidden * @private */ private gridLocation : RectangleF; /** * @hidden * @private */ private gridStyle : PdfGridStyle; /** * @hidden * @private */ private ispageWidth : boolean; /** * Check weather it is `child grid or not`. * @private */ private ischildGrid : boolean; /** * Check the child grid is ' split or not' */ public isGridSplit : boolean = false; /** * @hidden * @private */ public rowLayoutBoundsWidth : number; /** * @hidden * @private */ public isRearranged : boolean = false; /** * @hidden * @private */ private bRepeatHeader : boolean; /** * @hidden * @private */ private pageBounds : RectangleF = new RectangleF(); //GridLayouter-Fields /** * @hidden * @private */ private currentPage : PdfPage; /** * @hidden * @private */ private currentPageBounds : SizeF; /** * @hidden * @private */ private currentBounds : RectangleF; /** * @hidden * @private */ private currentGraphics : PdfGraphics; /** * @hidden * @private */ public listOfNavigatePages : number[] = []; /** * @hidden * @private */ private startLocation : PointF; /** * @hidden * @private */ public parentCellIndex : number = 0 ; public tempWidth : number = 0; /** * @hidden * @private */ private breakRow : boolean = true; public splitChildRowIndex : number = -1; private rowBreakPageHeightCellIndex : number; //Events /** * The event raised on `starting cell drawing`. * @event * @private */ public beginCellDraw : Function; /** * The event raised on `ending cell drawing`. * @event * @private */ public endCellDraw : Function; /** * The event raised on `begin cell lay outing`. * @event * @private */ //public beginPageLayout : Function; /** * The event raised on `end cell lay outing`. * @event * @private */ //public endPageLayout : Function; public hasRowSpanSpan : boolean = false; public hasColumnSpan : boolean = false; public isSingleGrid : boolean = true; private parentCell : PdfGridCell; //constructor /** * Initialize a new instance for `PdfGrid` class. * @private */ public constructor() { super(); } //Properties /** * Gets a value indicating whether the `start cell layout event` should be raised. * @private */ public get raiseBeginCellDraw() : boolean { return (typeof this.beginCellDraw !== 'undefined' && typeof this.beginCellDraw !== null); } /** * Gets a value indicating whether the `end cell layout event` should be raised. * @private */ public get raiseEndCellDraw() : boolean { return (typeof this.endCellDraw !== 'undefined' && typeof this.endCellDraw !== null); } /** * Gets or sets a value indicating whether to `repeat header`. * @private */ public get repeatHeader() : boolean { if (this.bRepeatHeader == null || typeof this.bRepeatHeader === 'undefined') { this.bRepeatHeader = false; } return this.bRepeatHeader; } public set repeatHeader(value : boolean) { this.bRepeatHeader = value; } /** * Gets or sets a value indicating whether to split or cut rows that `overflow a page`. * @private */ public get allowRowBreakAcrossPages() : boolean { return this.breakRow; } public set allowRowBreakAcrossPages(value : boolean) { this.breakRow = value; } /** * Gets the `column` collection of the PdfGrid.[Read-Only] * @private */ public get columns() : PdfGridColumnCollection { if (this.gridColumns == null || typeof this.gridColumns === 'undefined') { this.gridColumns = new PdfGridColumnCollection(this); } return this.gridColumns; } /** * Gets the `row` collection from the PdfGrid.[Read-Only] * @private */ public get rows() : PdfGridRowCollection { if (this.gridRows == null) { this.gridRows = new PdfGridRowCollection(this); } return (this.gridRows as PdfGridRowCollection); } /** * Gets the `headers` collection from the PdfGrid.[Read-Only] * @private */ public get headers() : PdfGridHeaderCollection { if (this.gridHeaders == null || typeof this.gridHeaders === 'undefined') { this.gridHeaders = new PdfGridHeaderCollection(this); } return this.gridHeaders; } /** * Indicating `initial width` of the page. * @private */ public get initialWidth() : number { return this.gridInitialWidth; } public set initialWidth(value : number) { this.gridInitialWidth = value; } /** * Gets or sets the `grid style`. * @private */ public get style() : PdfGridStyle { if (this.gridStyle == null) { this.gridStyle = new PdfGridStyle(); } return this.gridStyle; } public set style(value : PdfGridStyle) { if (this.gridStyle == null) { this.gridStyle = value; } } /** * Gets a value indicating whether the grid column width is considered to be `page width`. * @private */ public get isPageWidth() : boolean { return this.ispageWidth; } public set isPageWidth(value : boolean) { this.ispageWidth = value; } /** * Gets or set if grid `is nested grid`. * @private */ public get isChildGrid() : boolean { return this.ischildGrid; } public set isChildGrid(value : boolean) { this.ischildGrid = value; } /** * Gets or set if grid ' is split or not' * @public */ // public get isGridSplit() : boolean { // return this.isgridSplit; // } // public set isGridSplit(value : boolean) { // this.isgridSplit = value; // }public get isGridSplit() : boolean { // return this.isgridSplit; // } // public set isGridSplit(value : boolean) { // this.isgridSplit = value; // } /** * Gets the `size`. * @private */ public get size() : SizeF { if ((this.gridSize.width === 0 || typeof this.gridSize.width === 'undefined') && this.gridSize.height === 0) { this.gridSize = this.measure(); } return this.gridSize; // } else { // return this.gridSize; // } } public set size(value : SizeF) { this.gridSize = value; } public get ParentCell() : PdfGridCell{ return this.parentCell; } public set ParentCell(value : PdfGridCell) { this.parentCell = value; } public get LayoutFormat() : PdfLayoutFormat { return this.layoutFormat; } //Implementation /** * `Draws` the element on the page with the specified page and 'PointF' class * @private */ public draw(page : PdfPage, location : PointF) : PdfLayoutResult /** * `Draws` the element on the page with the specified page and pair of coordinates * @private */ public draw(page : PdfPage, x : number, y : number) : PdfLayoutResult /** * `Draws` the element on the page with the specified page and 'RectangleF' class * @private */ public draw(page : PdfPage, layoutRectangle : RectangleF) : PdfLayoutResult /** * `Draws` the element on the page with the specified page, 'PointF' class and layout format * @private */ public draw(page : PdfPage, location : PointF, format : PdfLayoutFormat) : PdfLayoutResult /** * `Draws` the element on the page with the specified page, pair of coordinates and layout format * @private */ public draw(page : PdfPage, x : number, y : number, format : PdfLayoutFormat) : PdfLayoutResult /** * `Draws` the element on the page. * @private */ public draw(page : PdfPage, layoutRectangle : RectangleF, embedFonts : boolean) : PdfLayoutResult /** * `Draws` the element on the page with the specified page, 'RectangleF' class and layout format * @private */ public draw(page : PdfPage, layoutRectangle : RectangleF, format : PdfLayoutFormat) : PdfLayoutResult public draw(arg1 : PdfPage, arg2 : RectangleF|PointF|number, arg3 ?: PdfLayoutFormat|number|boolean, arg4 ?: PdfLayoutFormat) : PdfLayoutResult { if (arg2 instanceof PointF && typeof (arg2 as RectangleF).width === 'undefined' && typeof arg3 === 'undefined') { return this.drawHelper(arg1, arg2.x, arg2.y); } else if (typeof arg2 === 'number' && typeof arg3 === 'number' && typeof arg4 === 'undefined') { return this.drawHelper(arg1, arg2, arg3, null); } else if (arg2 instanceof RectangleF && typeof (arg2 as RectangleF).width !== 'undefined' && typeof arg3 === 'undefined') { return this.drawHelper(arg1, arg2, null); } else if (arg2 instanceof PointF && typeof (arg2 as RectangleF).width === 'undefined' && arg3 instanceof PdfLayoutFormat) { return this.drawHelper(arg1, arg2.x, arg2.y, arg3); } else if (typeof arg2 === 'number' && typeof arg3 === 'number' && (arg4 instanceof PdfLayoutFormat || arg4 == null)) { let width : number = (arg1.graphics.clientSize.width - arg2); let layoutRectangle : RectangleF = new RectangleF(arg2, arg3, width, 0); return this.drawHelper(arg1, layoutRectangle, arg4); } else if (arg2 instanceof RectangleF && typeof (arg2 as RectangleF).width !== 'undefined' && typeof arg3 === 'boolean') { return this.drawHelper(arg1, arg2, null); } else { return this.drawHelper(arg1, (arg2 as RectangleF), arg3 as PdfLayoutFormat); } } /** * `measures` this instance. * @private */ private measure() : SizeF { let height : number = 0; let width : number = this.columns.width; for (let i : number = 0; i < this.headers.count; i++) { let row : PdfGridRow = this.headers.getHeader(i); height += row.height; } for (let i : number = 0; i < this.rows.count; i++) { let row : PdfGridRow = this.rows.getRow(i); height += row.height; } return new SizeF(width, height); } public onBeginCellDraw(args : PdfGridBeginCellDrawEventArgs ): void { if (this.raiseBeginCellDraw) { this.beginCellDraw(this, args); } } public onEndCellDraw(args : PdfGridEndCellDrawEventArgs ): void { if (this.raiseEndCellDraw) { this.endCellDraw(this, args); } } /** * `Layouts` the specified graphics. * @private */ protected layout(param : PdfLayoutParams) : PdfLayoutResult { if (this.rows.count !== 0) { let currentRow : PdfGridCellStyle = this.rows.getRow(0).cells.getCell(0).style; if (currentRow.borders != null && (( currentRow.borders.left != null && currentRow.borders.left.width !== 1) || (currentRow.borders.top != null && currentRow.borders.top.width !== 1))) { let x : number = currentRow.borders.left.width / 2; let y : number = currentRow.borders.top.width / 2; if (param.bounds.x === PdfBorders.default.right.width / 2 && param.bounds.y === PdfBorders.default.right.width / 2) { let newBound : RectangleF = new RectangleF(x, y, this.gridSize.width, this.gridSize.height); param.bounds = newBound; } } } this.setSpan(); this.checkSpan(); this.layoutFormat = param.format; this.gridLocation = param.bounds; let layouter : PdfGridLayouter = new PdfGridLayouter(this); let result : PdfGridLayoutResult = (layouter.Layouter(param)) as PdfGridLayoutResult; return result; } public setSpan() : void { let colSpan : number = 1; let rowSpan : number = 1; let currentCellIndex : number = 0; let currentRowIndex : number = 0; let maxSpan : number = 0; let rowCount : number = this.headers.count; for (let i : number = 0; i < rowCount; i++) { let row : PdfGridRow = this.headers.getHeader(i); maxSpan = 0; let colCount : number = row.cells.count; for (let j : number = 0; j < colCount; j++) { let cell : PdfGridCell = row.cells.getCell(j); maxSpan = Math.max(maxSpan, cell.rowSpan); //Skip setting span map for already coverted rows/columns. if (!cell.isCellMergeContinue && !cell.isRowMergeContinue && (cell.columnSpan > 1 || cell.rowSpan > 1)) { if (cell.columnSpan + j > row.cells.count) { throw new Error('Invalid span specified at row ' + j.toString() + ' column ' + i.toString()); } if (cell.rowSpan + i > this.headers.count) { throw new Error('Invalid span specified at Header ' + j.toString() + ' column ' + i.toString()); } // if (this.rows.count !== 0 && cell.rowSpan + i > this.rows.count) { // throw new Error('Invalid span specified at row ' + j.toString() + ' column ' + i.toString()); // } if (cell.columnSpan > 1 && cell.rowSpan > 1) { colSpan = cell.columnSpan; rowSpan = cell.rowSpan; currentCellIndex = j; currentRowIndex = i; cell.isCellMergeStart = true; cell.isRowMergeStart = true; //Set Column merges for first row while (colSpan > 1) { currentCellIndex++; row.cells.getCell(currentCellIndex).isCellMergeContinue = true; row.cells.getCell(currentCellIndex).isRowMergeContinue = true; row.cells.getCell(currentCellIndex).rowSpan = rowSpan; colSpan--; } currentCellIndex = j; colSpan = cell.columnSpan; //Set Row Merges and column merges foreach subsequent rows. while (rowSpan > 1) { currentRowIndex++; this.headers.getHeader(currentRowIndex).cells.getCell(j).isRowMergeContinue = true; this.headers.getHeader(currentRowIndex).cells.getCell(currentCellIndex).isRowMergeContinue = true; rowSpan--; while (colSpan > 1) { currentCellIndex++; this.headers.getHeader(currentRowIndex).cells.getCell(currentCellIndex).isCellMergeContinue = true; this.headers.getHeader(currentRowIndex).cells.getCell(currentCellIndex).isRowMergeContinue = true; colSpan--; } colSpan = cell.columnSpan; currentCellIndex = j; } } else if (cell.columnSpan > 1 && cell.rowSpan === 1) { colSpan = cell.columnSpan; currentCellIndex = j; cell.isCellMergeStart = true; //Set Column merges. while (colSpan > 1) { currentCellIndex++; row.cells.getCell(currentCellIndex).isCellMergeContinue = true; colSpan--; } } else if (cell.columnSpan === 1 && cell.rowSpan > 1) { rowSpan = cell.rowSpan; currentRowIndex = i; //Set row Merges. while (rowSpan > 1) { currentRowIndex++; this.headers.getHeader(currentRowIndex).cells.getCell(j).isRowMergeContinue = true; rowSpan--; } } } } row.maximumRowSpan = maxSpan; } } public checkSpan() : void { let cellcolSpan : number; let cellrowSpan : number = 1; let cellmaxSpan : number = 0; let currentCellIndex : number; let currentRowIndex : number = 0; cellcolSpan = cellrowSpan = 1; currentCellIndex = currentRowIndex = 0; if (this.hasRowSpanSpan || this.hasColumnSpan) { let rowCount : number = this.rows.count; for (let i : number = 0; i < rowCount; i++) { let row : PdfGridRow = this.rows.getRow(i); cellmaxSpan = 0; let colCount : number = row.cells.count; for (let j : number = 0; j < colCount; j++) { let cell : PdfGridCell = row.cells.getCell(j); cellmaxSpan = Math.max(cellmaxSpan, cell.rowSpan); //Skip setting span map for already coverted rows/columns. if (!cell.isCellMergeContinue && !cell.isRowMergeContinue && (cell.columnSpan > 1 || cell.rowSpan > 1)) { if (cell.columnSpan + j > row.cells.count) { throw new Error('Invalid span specified at row ' + j.toString() + ' column ' + i.toString()); } if (cell.rowSpan + i > this.rows.count) { throw new Error('Invalid span specified at row ' + j.toString() + ' column ' + i.toString()); } if (cell.columnSpan > 1 && cell.rowSpan > 1) { cellcolSpan = cell.columnSpan; cellrowSpan = cell.rowSpan; currentCellIndex = j; currentRowIndex = i; cell.isCellMergeStart = true; cell.isRowMergeStart = true; //Set Column merges for first row while (cellcolSpan > 1) { currentCellIndex++; row.cells.getCell(currentCellIndex).isCellMergeContinue = true; row.cells.getCell(currentCellIndex).isRowMergeContinue = true; cellcolSpan--; } currentCellIndex = j; cellcolSpan = cell.columnSpan; //Set Row Merges and column merges foreach subsequent rows. while (cellrowSpan > 1) { currentRowIndex++; this.rows.getRow(currentRowIndex).cells.getCell(j).isRowMergeContinue = true; this.rows.getRow(currentRowIndex).cells.getCell(currentCellIndex).isRowMergeContinue = true; cellrowSpan--; while (cellcolSpan > 1) { currentCellIndex++; this.rows.getRow(currentRowIndex).cells.getCell(currentCellIndex).isCellMergeContinue = true; this.rows.getRow(currentRowIndex).cells.getCell(currentCellIndex).isRowMergeContinue = true; cellcolSpan--; } cellcolSpan = cell.columnSpan; currentCellIndex = j; } } else if (cell.columnSpan > 1 && cell.rowSpan === 1) { cellcolSpan = cell.columnSpan; currentCellIndex = j; cell.isCellMergeStart = true; //Set Column merges. while (cellcolSpan > 1) { currentCellIndex++; row.cells.getCell(currentCellIndex).isCellMergeContinue = true; cellcolSpan--; } } else if (cell.columnSpan === 1 && cell.rowSpan > 1) { cellrowSpan = cell.rowSpan; currentRowIndex = i; //Set row Merges. while (cellrowSpan > 1) { currentRowIndex++; this.rows.getRow(currentRowIndex).cells.getCell(j).isRowMergeContinue = true; cellrowSpan--; } } } } row.maximumRowSpan = cellmaxSpan; } } } /* tslint:disable */ /** * Calculates the `width` of the columns. * @private */ public measureColumnsWidth() : void /** * Calculates the `width` of the columns. * @private */ public measureColumnsWidth(bounds : RectangleF) : void public measureColumnsWidth(bounds ?: RectangleF) : void { if (typeof bounds !== 'undefined') { this.isPageWidth = false; let widths : number[] = this.columns.getDefaultWidths(bounds.width - bounds.x); //let tempWidth : number = this.columns.getColumn(0).width; for (let i : number = 0, count : number = this.columns.count; i < count; i++) { // if (this.columns.getColumn(i).width < 0) // this.columns.getColumn(i).columnWidth = widths[i]; // else if (this.columns.getColumn(i).width > 0 && !this.columns.getColumn(i).isCustomWidth && widths[i]>0 && this.isComplete) this.columns.getColumn(i).columnWidth = widths[i]; this.tempWidth = widths[i]; } if (this.ParentCell != null && this.style.allowHorizontalOverflow == false && this.ParentCell.row.grid.style.allowHorizontalOverflow == false) { let padding : number = 0; let columnWidth : number = 0; let columnCount : number = this.columns.count; let childGridColumnWidth : number = 0; if (this.ParentCell.style.cellPadding != null || typeof this.ParentCell.style.cellPadding !== 'undefined') { if(typeof this.ParentCell.style.cellPadding.left != 'undefined' && this.ParentCell.style.cellPadding.hasLeftPad){ padding += this.ParentCell.style.cellPadding.left; } if(typeof this.ParentCell.style.cellPadding.right != 'undefined' && this.ParentCell.style.cellPadding.hasRightPad){ padding += this.ParentCell.style.cellPadding.right; } } for (let i : number = 0; i < this.ParentCell.columnSpan; i++) { columnWidth += this.ParentCell.row.grid.columns.getColumn(this.parentCellIndex + i).width; } for (let j : number = 0; j < this.columns.count; j++) { if (this.gridColumns.getColumn(j).width > 0 && this.gridColumns.getColumn(j).isCustomWidth) { columnWidth -= this.gridColumns.getColumn(j).width; columnCount--; } } if((this.ParentCell.row.grid.style.cellPadding != null || typeof this.ParentCell.row.grid.style.cellPadding != 'undefined')) { if(typeof this.ParentCell.row.grid.style.cellPadding.top != 'undefined' && this.ParentCell.row.grid.style.cellPadding.hasTopPad){ padding += this.ParentCell.row.grid.style.cellPadding.top; } if(typeof this.ParentCell.row.grid.style.cellPadding.bottom != 'undefined' && this.ParentCell.row.grid.style.cellPadding.hasBottomPad){ padding += this.ParentCell.row.grid.style.cellPadding.bottom; } } if (this.ParentCell.row.grid.style.cellSpacing != 0){ columnWidth -= this.ParentCell.row.grid.style.cellSpacing * 2; } if (columnWidth > padding) { childGridColumnWidth = (columnWidth - padding) / columnCount; this.tempWidth=childGridColumnWidth; if (this.ParentCell != null ) { for (let j : number = 0; j < this.columns.count; j++) { if (!this.columns.getColumn(j).isCustomWidth) this.columns.getColumn(j).columnWidth = childGridColumnWidth; } } } } // if (this.ParentCell != null && this.ParentCell.row.width > 0) // { // if (this.isChildGrid && this.gridSize.width > this.ParentCell.row.width) // { // widths = this.columns.getDefaultWidths(bounds.width); // for (let i : number = 0; i < this.columns.count; i++) // { // this.columns.getColumn(i).width = widths[i]; // } // } // } } else { let widths : number[] = [this.columns.count]; for(let n : number = 0; n < this.columns.count;n++) { widths[n] = 0; } let cellWidth : number = 0; let cellWidths : number = 0; if((typeof this.isChildGrid === 'undefined' && typeof this.gridLocation !== 'undefined' ) || (this.isChildGrid === null && typeof this.gridLocation !== 'undefined')){ this.initialWidth = this.gridLocation.width; } if (this.headers.count > 0) { let colCount : number = this.headers.getHeader(0).cells.count; let rowCount : number = this.headers.count; for (let i : number = 0; i < colCount; i++) { cellWidth = 0; for (let j : number = 0; j < rowCount; j++) { let rowWidth : number = Math.min(this.initialWidth, this.headers.getHeader(j).cells.getCell(i).width); cellWidth = Math.max(cellWidth, rowWidth); } widths[i] = cellWidth; } } // else { // let colCount : number = this.rows.getRow(0).cells.count; // let rowCount : number = this.rows.count; // for (let i : number = 0; i < colCount; i++) { // cellWidth = 0; // for (let j : number = 0; j < rowCount; j++) { // let rowWidth : number = Math.min(this.initialWidth, this.rows.getRow(j).cells.getCell(i).width); // cellWidth = Math.max(cellWidth, rowWidth); // } // widths[i] = cellWidth; // } // } cellWidth = 0; for (let i : number = 0, colCount : number = this.columns.count; i < colCount; i++) { for (let j : number = 0, rowCount : number = this.rows.count; j < rowCount; j++) { if ((this.rows.getRow(j).cells.getCell(i).columnSpan == 1 && !this.rows.getRow(j).cells.getCell(i).isCellMergeContinue) || (this.rows.getRow(j).cells.getCell(i).value as PdfGrid) != null ) { if ((this.rows.getRow(j).cells.getCell(i).value as PdfGrid) != null && !this.rows.getRow(j).grid.style.allowHorizontalOverflow) { let value : number = this.rows.getRow(j).grid.style.cellPadding.right + this.rows.getRow(j).grid.style.cellPadding.left + this.rows.getRow(j).cells.getCell(i).style.borders.left.width / 2 ; // if (this.initialWidth != 0 ) // (this.rows.getRow(j).cells.getCell(i).value as PdfGrid).initialWidth = this.initialWidth - value; } let rowWidth : number = 0; rowWidth = this.initialWidth > 0.0 ? Math.min(this.initialWidth, this.rows.getRow(j).cells.getCell(i).width) : this.rows.getRow(j).cells.getCell(i).width; // let internalWidth : number = this.rows.getRow(j).cells.getCell(i).width; // internalWidth += this.rows.getRow(j).cells.getCell(i).style.borders.left.width; // internalWidth += this.rows.getRow(j).cells.getCell(i).style.borders.right.width; // let internalHeight : number = this.rows.getRow(j).cells.getCell(i).height; // internalHeight += (this.rows.getRow(j).cells.getCell(i).style.borders.top.width); // internalHeight += (this.rows.getRow(j).cells.getCell(i).style.borders.bottom.width); // let isCorrectWidth : boolean = (internalWidth + this.gridLocation.x) > this.currentGraphics.clientSize.width; // let isCorrectHeight : boolean = (internalHeight + this.gridLocation.y) > this.currentGraphics.clientSize.height; // if (isCorrectWidth || isCorrectHeight) { // throw Error('Image size exceeds client size of the page. Can not insert this image'); // } // rowWidth = Math.min(this.initialWidth, this.rows.getRow(j).cells.getCell(i).width); cellWidth = Math.max(widths[i], Math.max(cellWidth, rowWidth)); cellWidth = Math.max(this.columns.getColumn(i).width, cellWidth); } } if(this.rows.count != 0) widths[i] = cellWidth; cellWidth = 0; } for (let i : number = 0, RowCount = this.rows.count; i < RowCount; i++) { for (let j : number = 0, ColCount = this.columns.count; j < ColCount; j++) { if (this.rows.getRow(i).cells.getCell(j).columnSpan > 1) { let total : number = widths[j]; for (let k : number = 1; k < this.rows.getRow(i).cells.getCell(j).columnSpan; k++) { total += widths[j + k]; } // if (this.rows.getRow(i).cells.getCell(j).width > total) // { // let extendedWidth : number = this.rows.getRow(i).cells.getCell(j).width - total; // extendedWidth = extendedWidth / this.rows.getRow(i).cells.getCell(j).columnSpan; // for (let k : number = j; k < j + this.rows.getRow(i).cells.getCell(j).columnSpan; k++) // widths[k] += extendedWidth; // } } } } // if (this.isChildGrid && this.initialWidth != 0) // { // widths = this.columns.getDefaultWidths(this.initialWidth); // } for (let i : number = 0, count : number = this.columns.count; i < count; i++) { if (this.columns.getColumn(i).width <= 0) this.columns.getColumn(i).columnWidth = widths[i]; else if (this.columns.getColumn(i).width > 0 && !this.columns.getColumn(i).isCustomWidth) this.columns.getColumn(i).columnWidth = widths[i]; } let padding : number = 0; let colWidth : number = 0; let colCount : number = this.columns.count; let childGridColWidth : number = 0; colWidth = this.tempWidth; for (let j : number = 0; j < this.columns.count; j++) { if (this.gridColumns.getColumn(j).width > 0 && this.gridColumns.getColumn(j).isCustomWidth) { colWidth -= this.gridColumns.getColumn(j).width; colCount--; } } // if (this.style.cellSpacing != 0){ // colWidth -= this.style.cellSpacing * 2; // } if (colWidth > 0) { if (this.ParentCell.row.grid.style.cellSpacing != 0){ colWidth -= this.ParentCell.row.grid.style.cellSpacing * 2; } } if (colWidth > padding) { childGridColWidth = (colWidth) / colCount; if (this.ParentCell != null) { for (let j : number = 0; j < this.columns.count; j++) { if (!this.columns.getColumn(j).isCustomWidth) this.columns.getColumn(j).columnWidth = childGridColWidth; } } } } } }
the_stack
'use strict'; import * as path from 'path'; import { commands, ExtensionContext, OutputChannel, TextDocument, Uri, window, workspace, WorkspaceFolder, } from 'vscode'; import { ExecutableOptions, LanguageClient, LanguageClientOptions, Logger, RevealOutputChannelOn, ServerOptions, TransportKind, } from 'vscode-languageclient/node'; import { CommandNames } from './commands/constants'; import { ImportIdentifier } from './commands/importIdentifier'; import { DocsBrowser } from './docsBrowser'; import { downloadHaskellLanguageServer } from './hlsBinaries'; import { directoryExists, executableExists, ExtensionLogger, resolvePathPlaceHolders } from './utils'; // The current map of documents & folders to language servers. // It may be null to indicate that we are in the process of launching a server, // in which case don't try to launch another one for that uri const clients: Map<string, LanguageClient | null> = new Map(); // This is the entrypoint to our extension export async function activate(context: ExtensionContext) { // (Possibly) launch the language server every time a document is opened, so // it works across multiple workspace folders. Eventually, haskell-lsp should // just support // https://microsoft.github.io/language-server-protocol/specifications/specification-3-15/#workspace_workspaceFolders // and then we can just launch one server workspace.onDidOpenTextDocument(async (document: TextDocument) => await activeServer(context, document)); workspace.textDocuments.forEach(async (document: TextDocument) => await activeServer(context, document)); // Stop the server from any workspace folders that are removed. workspace.onDidChangeWorkspaceFolders((event) => { for (const folder of event.removed) { const client = clients.get(folder.uri.toString()); if (client) { const uri = folder.uri.toString(); client.info(`Deleting folder for clients: ${uri}`); clients.delete(uri); client.info('Stopping the server'); client.stop(); } } }); // Register editor commands for HIE, but only register the commands once at activation. const restartCmd = commands.registerCommand(CommandNames.RestartServerCommandName, async () => { for (const langClient of clients.values()) { langClient?.info('Stopping the server'); await langClient?.stop(); langClient?.info('Starting the server'); langClient?.start(); } }); context.subscriptions.push(restartCmd); const stopCmd = commands.registerCommand(CommandNames.StopServerCommandName, async () => { for (const langClient of clients.values()) { langClient?.info('Stopping the server'); await langClient?.stop(); langClient?.info('Server stopped'); } }); context.subscriptions.push(stopCmd); const startCmd = commands.registerCommand(CommandNames.StartServerCommandName, async () => { for (const langClient of clients.values()) { langClient?.info('Starting the server'); langClient?.start(); langClient?.info('Server started'); } }); context.subscriptions.push(startCmd); context.subscriptions.push(ImportIdentifier.registerCommand()); // Set up the documentation browser. const docsDisposable = DocsBrowser.registerDocsBrowser(); context.subscriptions.push(docsDisposable); const openOnHackageDisposable = DocsBrowser.registerDocsOpenOnHackage(); context.subscriptions.push(openOnHackageDisposable); } function findManualExecutable(logger: Logger, uri: Uri, folder?: WorkspaceFolder): string | null { let exePath = workspace.getConfiguration('haskell', uri).serverExecutablePath; if (exePath === '') { return null; } logger.info(`Trying to find the server executable in: ${exePath}`); exePath = resolvePathPlaceHolders(exePath, folder); logger.info(`Location after path variables substitution: ${exePath}`); if (!executableExists(exePath)) { let msg = `serverExecutablePath is set to ${exePath}`; if (directoryExists(exePath)) { msg += ' but it is a directory and the config option should point to the executable full path'; } else { msg += " but it doesn't exist and it is not on the PATH"; } throw new Error(msg); } return exePath; } /** Searches the PATH for whatever is set in serverVariant */ function findLocalServer(context: ExtensionContext, logger: Logger, uri: Uri, folder?: WorkspaceFolder): string | null { const exes: string[] = ['haskell-language-server-wrapper', 'haskell-language-server']; logger.info(`Searching for server executables ${exes.join(',')} in $PATH`); for (const exe of exes) { if (executableExists(exe)) { logger.info(`Found server executable in $PATH: ${exe}`); return exe; } } return null; } async function activeServer(context: ExtensionContext, document: TextDocument) { // We are only interested in Haskell files. if ( (document.languageId !== 'haskell' && document.languageId !== 'cabal' && document.languageId !== 'literate haskell') || (document.uri.scheme !== 'file' && document.uri.scheme !== 'untitled') ) { return; } const uri = document.uri; const folder = workspace.getWorkspaceFolder(uri); activateServerForFolder(context, uri, folder); } async function activateServerForFolder(context: ExtensionContext, uri: Uri, folder?: WorkspaceFolder) { const clientsKey = folder ? folder.uri.toString() : uri.toString(); // Set a unique name per workspace folder (useful for multi-root workspaces). const langName = 'Haskell' + (folder ? ` (${folder.name})` : ''); // If the client already has an LSP server for this uri/folder, then don't start a new one. if (clients.has(clientsKey)) { return; } // Set the key to null to prevent multiple servers being launched at once clients.set(clientsKey, null); const logLevel = workspace.getConfiguration('haskell', uri).trace.server; const clientLogLevel = workspace.getConfiguration('haskell', uri).trace.client; const logFile = workspace.getConfiguration('haskell', uri).logFile; const outputChannel: OutputChannel = window.createOutputChannel(langName); const logger: Logger = new ExtensionLogger('client', clientLogLevel, outputChannel); let serverExecutable; try { // Try and find local installations first serverExecutable = findManualExecutable(logger, uri, folder) ?? findLocalServer(context, logger, uri, folder); if (serverExecutable === null) { // If not, then try to download haskell-language-server binaries if it's selected serverExecutable = await downloadHaskellLanguageServer(context, logger, uri, folder); if (!serverExecutable) { return; } } } catch (e) { if (e instanceof Error) { logger.error(`Error getting the server executable: ${e.message}`); window.showErrorMessage(e.message); } return; } let args: string[] = ['--lsp']; if (logLevel === 'messages') { args = args.concat(['-d']); } if (logFile !== '') { args = args.concat(['-l', logFile]); } const extraArgs: string = workspace.getConfiguration('haskell', uri).serverExtraArgs; if (extraArgs !== '') { args = args.concat(extraArgs.split(' ')); } // If we're operating on a standalone file (i.e. not in a folder) then we need // to launch the server in a reasonable current directory. Otherwise the cradle // guessing logic in hie-bios will be wrong! if (folder) { logger.info(`Activating the language server in the workspace folder: ${folder?.uri.fsPath}`); } else { logger.info(`Activating the language server in the parent dir of the file: ${uri.fsPath}`); } const exeOptions: ExecutableOptions = { cwd: folder ? undefined : path.dirname(uri.fsPath), }; // We don't want empty strings in our args args = args.map((x) => x.trim()).filter((x) => x !== ''); // For our intents and purposes, the server should be launched the same way in // both debug and run mode. const serverOptions: ServerOptions = { run: { command: serverExecutable, transport: TransportKind.stdio, args, options: exeOptions }, debug: { command: serverExecutable, transport: TransportKind.stdio, args, options: exeOptions }, }; logger.info(`run command: ${serverExecutable} ${args.join(' ')}`); logger.info(`debug command: ${serverExecutable} ${args.join(' ')}`); if (exeOptions.cwd) { logger.info(`server cwd: ${exeOptions.cwd}`); } const pat = folder ? `${folder.uri.fsPath}/**/*` : '**/*'; logger.info(`document selector patten: ${pat}`); const clientOptions: LanguageClientOptions = { // Use the document selector to only notify the LSP on files inside the folder // path for the specific workspace. documentSelector: [ { scheme: 'file', language: 'haskell', pattern: pat }, { scheme: 'file', language: 'literate haskell', pattern: pat }, ], synchronize: { // Synchronize the setting section 'haskell' to the server. configurationSection: 'haskell', }, diagnosticCollectionName: langName, revealOutputChannelOn: RevealOutputChannelOn.Never, outputChannel, outputChannelName: langName, middleware: { provideHover: DocsBrowser.hoverLinksMiddlewareHook, provideCompletionItem: DocsBrowser.completionLinksMiddlewareHook, }, // Launch the server in the directory of the workspace folder. workspaceFolder: folder, }; // Create the LSP client. const langClient = new LanguageClient(langName, langName, serverOptions, clientOptions); // Register ClientCapabilities for stuff like window/progress langClient.registerProposedFeatures(); // Finally start the client and add it to the list of clients. logger.info('Starting language server'); langClient.start(); clients.set(clientsKey, langClient); } /* * Deactivate each of the LSP servers. */ export async function deactivate() { const promises: Array<Thenable<void>> = []; for (const client of clients.values()) { if (client) { promises.push(client.stop()); } } await Promise.all(promises); }
the_stack
import { Action, Box, Col, Icon, Image, Row, StatelessTextInput as Input, Text } from '@tlon/indigo-react'; import { Contact, Contacts } from '@urbit/api/contacts'; import { addTag, removeMembers, changePolicy, Group, removeTag, RoleTags } from '@urbit/api/groups'; import { Association } from '@urbit/api/metadata'; import { deSig } from '@urbit/api'; import _ from 'lodash'; import f from 'lodash/fp'; import React, { ChangeEvent, ReactElement, useCallback, useMemo, useState } from 'react'; import { Link } from 'react-router-dom'; import VisibilitySensor from 'react-visibility-sensor'; import styled from 'styled-components'; import { resourceFromPath, roleForShip } from '~/logic/lib/group'; import { Sigil } from '~/logic/lib/sigil'; import { cite, uxToHex } from '~/logic/lib/util'; import useContactState from '~/logic/state/contact'; import useSettingsState, { selectCalmState } from '~/logic/state/settings'; import { Dropdown } from '~/views/components/Dropdown'; import { StatelessAsyncAction } from '~/views/components/StatelessAsyncAction'; import airlock from '~/logic/api'; const TruncText = styled(Text)` white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inline-block; min-width: 0; `; type Participant = Contact & { patp: string; pending: boolean }; type ParticipantsTabId = 'total' | 'pending' | 'admin'; const searchParticipant = (search: string) => (p: Participant) => { if (search.length == 0) { return true; } let s = search.toLowerCase(); s = (s.startsWith('~')) ? s.substr(1) : s; return p.patp.includes(s) || p.nickname.toLowerCase().includes(s); }; const emptyContact = (patp: string, pending: boolean): Participant => ({ nickname: '', bio: '', status: '', color: '0x0', avatar: null, cover: null, groups: [], patp, 'last-updated': 0, pending }); function getParticipants(cs: Contacts, group: Group) { const contacts: Participant[] = _.flow( f.omitBy<Contacts>((_c, patp) => !group.members.has(deSig(patp))), f.toPairs, f.map(([patp, c]: [string, Contact]) => ({ ...c, patp: deSig(patp), pending: false })) )(cs); const members: Participant[] = _.map( Array.from(group.members), s => contacts[s] ?? emptyContact(s, false) ); const allMembers = _.unionBy(contacts, members, 'patp'); const pending: Participant[] = 'invite' in group.policy ? _.map(Array.from(group.policy.invite.pending), m => emptyContact(m, true) ) : []; const incPending = _.unionBy(allMembers, pending, 'patp'); return [ incPending, incPending.length - group.members.size, group.members.size ] as const; } const Tab = ({ selected, id, label, setSelected }) => ( <Box py={2} borderBottom={selected === id ? 1 : 0} borderBottomColor="black" mr={2} cursor="pointer" onClick={() => setSelected(id)} > <Text color={selected === id ? 'black' : 'gray'}>{label}</Text> </Box> ); export function Participants(props: { group: Group; association: Association; }): ReactElement { const tabFilters: Record< ParticipantsTabId, (p: Participant) => boolean > = useMemo( () => ({ total: p => !p.pending, pending: p => p.pending, admin: p => props.group.tags?.role?.admin?.has(p.patp) }), [props.group] ); const ourRole = roleForShip(props.group, window.ship); const [filter, setFilter] = useState<ParticipantsTabId>('total'); const [search, _setSearch] = useState(''); const setSearch = useMemo(() => _.debounce(_setSearch, 200), [_setSearch]); const onSearchChange = useCallback( (e: ChangeEvent<HTMLInputElement>) => { setSearch(e.target.value); }, [setSearch] ); const adminCount = props.group.tags?.role?.admin?.size || 0; const isInvite = 'invite' in props.group.policy; const contacts = useContactState(state => state.contacts); const [participants, pendingCount, memberCount] = getParticipants( contacts, props.group ); const filtered = useMemo( () => f.flow( f.filter(tabFilters[filter]), f.filter(searchParticipant(search)), f.chunk(8) )(participants), [search, filter, participants] ); // Sticky positioning needs to be disabled on safari due to this bug // https://bugs.webkit.org/show_bug.cgi?id=210656 // TODO: remove when resolved const isSafari = useMemo(() => { const ua = window.navigator.userAgent; return ua.includes('Safari') && !ua.includes('Chrome'); }, []); return ( <Col height="100%" overflowY="scroll" p={2} position="relative"> <Row bg="white" border={1} borderColor="washedGray" borderRadius={1} position={isSafari ? 'static' : 'sticky'} top="0px" mb={2} px={2} zIndex={1} flexShrink={0} > <Row mr={4} flexShrink={0}> <Tab selected={filter} setSelected={setFilter} id="total" label={`${memberCount} total`} /> {isInvite && ( <Tab selected={filter} setSelected={setFilter} id="pending" label={`${pendingCount} pending`} /> )} <Tab selected={filter} setSelected={setFilter} id="admin" label={`${adminCount} Admin${adminCount > 1 ? 's' : ''}`} /> </Row> </Row> <Col flexShrink={0} width="100%" height="fit-content"> <Row alignItems="center" bg="washedGray" borderRadius={1} px={2} my={2}> <Icon color="gray" icon="Search" /> <Input maxWidth="256px" color="gray" bg="transparent" border={0} placeholder="Search Participants" onChange={onSearchChange} /> </Row> <Col alignItems="center" > {filtered.map((cs, idx) => ( <VisibilitySensor key={idx} offset={{ top: -800, bottom: -800 }} partialVisibility scrollDelay={150} > {({ isVisible }) => isVisible ? ( cs.map(c => ( <Participant key={c.patp} role={ourRole} group={props.group} contact={c} association={props.association} /> )) ) : ( <BlankParticipant length={cs.length} /> ) } </VisibilitySensor> ))} </Col> </Col> </Col> ); } function Participant(props: { contact: Participant; association: Association; group: Group; role?: RoleTags; }) { const { contact, association, group } = props; const { title } = association.metadata; const { hideAvatars, hideNicknames } = useSettingsState(selectCalmState); const color = uxToHex(contact.color); const isInvite = 'invite' in group.policy; const role = useMemo( () => contact.pending ? 'pending' : roleForShip(group, contact.patp) || 'member', [contact, group] ); const onPromote = useCallback(async () => { const resource = resourceFromPath(association.group); await airlock.poke(addTag(resource, { tag: 'admin' }, [`~${contact.patp}`])); }, [contact.patp, association]); const onDemote = useCallback(async () => { const resource = resourceFromPath(association.group); await airlock.poke(removeTag({ tag: 'admin' }, resource, [`~${contact.patp}`])); }, [association, contact.patp]); const onBan = useCallback(async () => { const resource = resourceFromPath(association.group); await airlock.poke(changePolicy(resource, { open: { banShips: [`~${contact.patp}`] } })); }, [association, contact.patp]); const onKick = useCallback(async () => { const resource = resourceFromPath(association.group); if(contact.pending) { await airlock.poke(changePolicy( resource, { invite: { removeInvites: [`~${contact.patp}`] } } )); } else { await airlock.poke(removeMembers(resource, [`~${contact.patp}`])); } }, [contact, association]); const avatar = contact?.avatar && !hideAvatars ? ( <Image src={contact.avatar} height={32} width={32} display='inline-block' style={{ objectFit: 'cover' }} /> ) : ( <Sigil ship={contact.patp} size={32} color={`#${color}`} /> ); const hasNickname = contact.nickname && !hideNicknames; return ( <> <Row flexDirection={['column', 'row']} gapX={2} alignItems={['flex-start', 'center']} width="100%" justifyContent="space-between" height={['96px', '60px']}> <Row gapX={4} alignItems="center" height="100%"> <Box>{avatar}</Box> <Col alignItems="self-start" justifyContent="center" gapY={1} height="100%" minWidth={0}> {hasNickname && ( <Row minWidth={0} flexShrink={1}> <TruncText title={contact.nickname} color="black"> {contact.nickname} </TruncText> </Row> )} <Text title={contact.patp} color="gray" fontFamily="mono"> {cite(contact.patp)} </Text> </Col> </Row> <Row justifyContent="space-between" width={['100%', '128px']} alignItems="center" gapX={4} > <Col> <Text color="lightGray" mb={1}> Role </Text> <Text>{_.capitalize(role)}</Text> </Col> <Dropdown alignX="right" alignY="top" options={ <Col bg="white" border={1} borderRadius={1} borderColor="lightGray" gapY={2} p={2} > <Action bg="transparent"> <Link to={`/~profile/~${contact.patp}`}> <Text color="black">View Profile</Text> </Link> </Action> <Action bg="transparent"> <Link to={`/~landscape/dm/${contact.patp}`}> <Text color="green">Send Message</Text> </Link> </Action> {props.role === 'admin' && ( <> {(!isInvite && contact.patp !== window.ship) && ( <StatelessAsyncAction onClick={onBan} bg="transparent"> <Text color="red">Ban from {title}</Text> </StatelessAsyncAction> )} {role === 'admin' ? ( group?.tags?.role?.admin?.size > 1 && (<StatelessAsyncAction onClick={onDemote} bg="transparent"> Demote from Admin </StatelessAsyncAction>) ) : ( <> {(contact.patp !== window.ship) && (<StatelessAsyncAction onClick={onKick} bg="transparent"> <Text color="red">Kick from {title}</Text> </StatelessAsyncAction>)} {!contact.pending && <StatelessAsyncAction onClick={onPromote} bg="transparent"> Promote to Admin </StatelessAsyncAction>} </> )} </> )} </Col> } > <Icon display="block" icon="Ellipsis" /> </Dropdown> </Row> </Row> <Box borderBottom={1} borderBottomColor="washedGray" width="100%" /> </> ); } function BlankParticipant({ length }) { const height = [`${length * 97}px`, `${length * 61}px`]; return ( <Box width="100%" height={height} /> ); }
the_stack
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { WorkbenchListFocusContextKey, IListService, WorkbenchListSupportsMultiSelectContextKey, ListWidget, WorkbenchListHasSelectionOrFocus, getSelectionKeyboardEvent, WorkbenchListWidget, WorkbenchListSelectionNavigation } from 'vs/platform/list/browser/listService'; import { PagedList } from 'vs/base/browser/ui/list/listPaging'; import { equals, range } from 'vs/base/common/arrays'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree'; import { DataTree } from 'vs/base/browser/ui/tree/dataTree'; import { ITreeNode } from 'vs/base/browser/ui/tree/tree'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { Table } from 'vs/base/browser/ui/table/tableWidget'; function ensureDOMFocus(widget: ListWidget | undefined): void { // it can happen that one of the commands is executed while // DOM focus is within another focusable control within the // list/tree item. therefor we should ensure that the // list/tree has DOM focus again after the command ran. if (widget && widget.getHTMLElement() !== document.activeElement) { widget.domFocus(); } } async function updateFocus(widget: WorkbenchListWidget, updateFocusFn: (widget: WorkbenchListWidget) => void | Promise<void>): Promise<void> { if (!WorkbenchListSelectionNavigation.getValue(widget.contextKeyService)) { return updateFocusFn(widget); } const focus = widget.getFocus(); const selection = widget.getSelection(); await updateFocusFn(widget); const newFocus = widget.getFocus(); if (selection.length > 1 || !equals(focus, selection) || equals(focus, newFocus)) { return; } const fakeKeyboardEvent = new KeyboardEvent('keydown'); widget.setSelection(newFocus, fakeKeyboardEvent); } async function navigate(widget: WorkbenchListWidget | undefined, updateFocusFn: (widget: WorkbenchListWidget) => void | Promise<void>): Promise<void> { if (!widget) { return; } await updateFocus(widget, updateFocusFn); const listFocus = widget.getFocus(); if (listFocus.length) { widget.reveal(listFocus[0]); } ensureDOMFocus(widget); } KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.focusDown', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.DownArrow, mac: { primary: KeyCode.DownArrow, secondary: [KeyMod.WinCtrl | KeyCode.KEY_N] }, handler: (accessor, arg2) => { navigate(accessor.get(IListService).lastFocusedList, async widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); await widget.focusNext(typeof arg2 === 'number' ? arg2 : 1, false, fakeKeyboardEvent); }); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.focusUp', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.UpArrow, mac: { primary: KeyCode.UpArrow, secondary: [KeyMod.WinCtrl | KeyCode.KEY_P] }, handler: (accessor, arg2) => { navigate(accessor.get(IListService).lastFocusedList, async widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); await widget.focusPrevious(typeof arg2 === 'number' ? arg2 : 1, false, fakeKeyboardEvent); }); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.focusPageDown', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.PageDown, handler: (accessor) => { navigate(accessor.get(IListService).lastFocusedList, async widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); await widget.focusNextPage(fakeKeyboardEvent); }); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.focusPageUp', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.PageUp, handler: (accessor) => { navigate(accessor.get(IListService).lastFocusedList, async widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); await widget.focusPreviousPage(fakeKeyboardEvent); }); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.focusFirst', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.Home, handler: (accessor) => { navigate(accessor.get(IListService).lastFocusedList, async widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); await widget.focusFirst(fakeKeyboardEvent); }); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.focusLast', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.End, handler: (accessor) => { navigate(accessor.get(IListService).lastFocusedList, async widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); await widget.focusLast(fakeKeyboardEvent); }); } }); function expandMultiSelection(focused: WorkbenchListWidget, previousFocus: unknown): void { // List if (focused instanceof List || focused instanceof PagedList || focused instanceof Table) { const list = focused; const focus = list.getFocus() ? list.getFocus()[0] : undefined; const selection = list.getSelection(); if (selection && typeof focus === 'number' && selection.indexOf(focus) >= 0) { list.setSelection(selection.filter(s => s !== previousFocus)); } else { if (typeof focus === 'number') { list.setSelection(selection.concat(focus)); } } } // Tree else if (focused instanceof ObjectTree || focused instanceof DataTree || focused instanceof AsyncDataTree) { const list = focused; const focus = list.getFocus() ? list.getFocus()[0] : undefined; if (previousFocus === focus) { return; } const selection = list.getSelection(); const fakeKeyboardEvent = new KeyboardEvent('keydown', { shiftKey: true }); if (selection && selection.indexOf(focus) >= 0) { list.setSelection(selection.filter(s => s !== previousFocus), fakeKeyboardEvent); } else { list.setSelection(selection.concat(focus), fakeKeyboardEvent); } } } KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.expandSelectionDown', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(WorkbenchListFocusContextKey, WorkbenchListSupportsMultiSelectContextKey), primary: KeyMod.Shift | KeyCode.DownArrow, handler: (accessor, arg2) => { const widget = accessor.get(IListService).lastFocusedList; if (!widget) { return; } // Focus down first const previousFocus = widget.getFocus() ? widget.getFocus()[0] : undefined; const fakeKeyboardEvent = new KeyboardEvent('keydown'); widget.focusNext(typeof arg2 === 'number' ? arg2 : 1, false, fakeKeyboardEvent); // Then adjust selection expandMultiSelection(widget, previousFocus); const focus = widget.getFocus(); if (focus.length) { widget.reveal(focus[0]); } ensureDOMFocus(widget); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.expandSelectionUp', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(WorkbenchListFocusContextKey, WorkbenchListSupportsMultiSelectContextKey), primary: KeyMod.Shift | KeyCode.UpArrow, handler: (accessor, arg2) => { const widget = accessor.get(IListService).lastFocusedList; if (!widget) { return; } // Focus up first const previousFocus = widget.getFocus() ? widget.getFocus()[0] : undefined; const fakeKeyboardEvent = new KeyboardEvent('keydown'); widget.focusPrevious(typeof arg2 === 'number' ? arg2 : 1, false, fakeKeyboardEvent); // Then adjust selection expandMultiSelection(widget, previousFocus); const focus = widget.getFocus(); if (focus.length) { widget.reveal(focus[0]); } ensureDOMFocus(widget); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.collapse', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.LeftArrow, mac: { primary: KeyCode.LeftArrow, secondary: [KeyMod.CtrlCmd | KeyCode.UpArrow] }, handler: (accessor) => { const widget = accessor.get(IListService).lastFocusedList; if (!widget || !(widget instanceof ObjectTree || widget instanceof DataTree || widget instanceof AsyncDataTree)) { return; } const tree = widget; const focusedElements = tree.getFocus(); if (focusedElements.length === 0) { return; } const focus = focusedElements[0]; if (!tree.collapse(focus)) { const parent = tree.getParentElement(focus); if (parent) { navigate(widget, widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); widget.setFocus([parent], fakeKeyboardEvent); }); } } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.collapseAll', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyMod.CtrlCmd | KeyCode.LeftArrow, mac: { primary: KeyMod.CtrlCmd | KeyCode.LeftArrow, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.UpArrow] }, handler: (accessor) => { const focused = accessor.get(IListService).lastFocusedList; if (focused && !(focused instanceof List || focused instanceof PagedList || focused instanceof Table)) { focused.collapseAll(); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.focusParent', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, handler: (accessor) => { const widget = accessor.get(IListService).lastFocusedList; if (!widget || !(widget instanceof ObjectTree || widget instanceof DataTree || widget instanceof AsyncDataTree)) { return; } const tree = widget; const focusedElements = tree.getFocus(); if (focusedElements.length === 0) { return; } const focus = focusedElements[0]; const parent = tree.getParentElement(focus); if (parent) { navigate(widget, widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); widget.setFocus([parent], fakeKeyboardEvent); }); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.expand', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.RightArrow, handler: (accessor) => { const widget = accessor.get(IListService).lastFocusedList; if (!widget) { return; } if (widget instanceof ObjectTree || widget instanceof DataTree) { // TODO@Joao: instead of doing this here, just delegate to a tree method const focusedElements = widget.getFocus(); if (focusedElements.length === 0) { return; } const focus = focusedElements[0]; if (!widget.expand(focus)) { const child = widget.getFirstElementChild(focus); if (child) { const node = widget.getNode(child); if (node.visible) { navigate(widget, widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); widget.setFocus([child], fakeKeyboardEvent); }); } } } } else if (widget instanceof AsyncDataTree) { // TODO@Joao: instead of doing this here, just delegate to a tree method const focusedElements = widget.getFocus(); if (focusedElements.length === 0) { return; } const focus = focusedElements[0]; widget.expand(focus).then(didExpand => { if (focus && !didExpand) { const child = widget.getFirstElementChild(focus); if (child) { const node = widget.getNode(child); if (node.visible) { navigate(widget, widget => { const fakeKeyboardEvent = new KeyboardEvent('keydown'); widget.setFocus([child], fakeKeyboardEvent); }); } } } }); } } }); function selectElement(accessor: ServicesAccessor, retainCurrentFocus: boolean): void { const focused = accessor.get(IListService).lastFocusedList; const fakeKeyboardEvent = getSelectionKeyboardEvent('keydown', retainCurrentFocus); // List if (focused instanceof List || focused instanceof PagedList || focused instanceof Table) { const list = focused; list.setSelection(list.getFocus(), fakeKeyboardEvent); } // Trees else if (focused instanceof ObjectTree || focused instanceof DataTree || focused instanceof AsyncDataTree) { const tree = focused; const focus = tree.getFocus(); if (focus.length > 0) { let toggleCollapsed = true; if (tree.expandOnlyOnTwistieClick === true) { toggleCollapsed = false; } else if (typeof tree.expandOnlyOnTwistieClick !== 'boolean' && tree.expandOnlyOnTwistieClick(focus[0])) { toggleCollapsed = false; } if (toggleCollapsed) { tree.toggleCollapsed(focus[0]); } } tree.setSelection(focus, fakeKeyboardEvent); } } KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.select', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.Enter, mac: { primary: KeyCode.Enter, secondary: [KeyMod.CtrlCmd | KeyCode.DownArrow] }, handler: (accessor) => { selectElement(accessor, false); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.selectAndPreserveFocus', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, handler: accessor => { selectElement(accessor, true); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.selectAll', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(WorkbenchListFocusContextKey, WorkbenchListSupportsMultiSelectContextKey), primary: KeyMod.CtrlCmd | KeyCode.KEY_A, handler: (accessor) => { const focused = accessor.get(IListService).lastFocusedList; // List if (focused instanceof List || focused instanceof PagedList || focused instanceof Table) { const list = focused; const fakeKeyboardEvent = new KeyboardEvent('keydown'); list.setSelection(range(list.length), fakeKeyboardEvent); } // Trees else if (focused instanceof ObjectTree || focused instanceof DataTree || focused instanceof AsyncDataTree) { const tree = focused; const focus = tree.getFocus(); const selection = tree.getSelection(); // Which element should be considered to start selecting all? let start: unknown | undefined = undefined; if (focus.length > 0 && (selection.length === 0 || !selection.includes(focus[0]))) { start = focus[0]; } if (!start && selection.length > 0) { start = selection[0]; } // What is the scope of select all? let scope: unknown | undefined = undefined; if (!start) { scope = undefined; } else { scope = tree.getParentElement(start); } const newSelection: unknown[] = []; const visit = (node: ITreeNode<unknown, unknown>) => { for (const child of node.children) { if (child.visible) { newSelection.push(child.element); if (!child.collapsed) { visit(child); } } } }; // Add the whole scope subtree to the new selection visit(tree.getNode(scope)); // If the scope isn't the tree root, it should be part of the new selection if (scope && selection.length === newSelection.length) { newSelection.unshift(scope); } const fakeKeyboardEvent = new KeyboardEvent('keydown'); tree.setSelection(newSelection, fakeKeyboardEvent); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.toggleSelection', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter, handler: (accessor) => { const widget = accessor.get(IListService).lastFocusedList; if (!widget) { return; } const focus = widget.getFocus(); if (focus.length === 0) { return; } const selection = widget.getSelection(); const index = selection.indexOf(focus[0]); if (index > -1) { widget.setSelection([...selection.slice(0, index), ...selection.slice(index + 1)]); } else { widget.setSelection([...selection, focus[0]]); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.toggleExpand', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.Space, handler: (accessor) => { const focused = accessor.get(IListService).lastFocusedList; // Tree only if (focused instanceof ObjectTree || focused instanceof DataTree || focused instanceof AsyncDataTree) { const tree = focused; const focus = tree.getFocus(); if (focus.length > 0 && tree.isCollapsible(focus[0])) { tree.toggleCollapsed(focus[0]); return; } } selectElement(accessor, true); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.clear', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(WorkbenchListFocusContextKey, WorkbenchListHasSelectionOrFocus), primary: KeyCode.Escape, handler: (accessor) => { const widget = accessor.get(IListService).lastFocusedList; if (!widget) { return; } const fakeKeyboardEvent = new KeyboardEvent('keydown'); widget.setSelection([], fakeKeyboardEvent); widget.setFocus([], fakeKeyboardEvent); widget.setAnchor(undefined); } }); CommandsRegistry.registerCommand({ id: 'list.toggleKeyboardNavigation', handler: (accessor) => { const widget = accessor.get(IListService).lastFocusedList; widget?.toggleKeyboardNavigation(); } }); CommandsRegistry.registerCommand({ id: 'list.toggleFilterOnType', handler: (accessor) => { const focused = accessor.get(IListService).lastFocusedList; // List if (focused instanceof List || focused instanceof PagedList || focused instanceof Table) { // TODO@joao } // Tree else if (focused instanceof ObjectTree || focused instanceof DataTree || focused instanceof AsyncDataTree) { const tree = focused; tree.updateOptions({ filterOnType: !tree.filterOnType }); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.scrollUp', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyMod.CtrlCmd | KeyCode.UpArrow, handler: accessor => { const focused = accessor.get(IListService).lastFocusedList; if (!focused) { return; } focused.scrollTop -= 10; } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.scrollDown', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyMod.CtrlCmd | KeyCode.DownArrow, handler: accessor => { const focused = accessor.get(IListService).lastFocusedList; if (!focused) { return; } focused.scrollTop += 10; } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.scrollLeft', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, handler: accessor => { const focused = accessor.get(IListService).lastFocusedList; if (!focused) { return; } focused.scrollLeft -= 10; } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'list.scrollRight', weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, handler: accessor => { const focused = accessor.get(IListService).lastFocusedList; if (!focused) { return; } focused.scrollLeft += 10; } });
the_stack
import * as builder from 'botbuilder'; import * as teams from './'; import * as sprintf from 'sprintf-js'; export class O365ConnectorCard implements builder.IIsAttachment { protected data = { contentType: 'application/vnd.microsoft.teams.card.o365connector', content: <teams.IO365ConnectorCard> {} }; constructor(protected session?: builder.Session) { } public title(text: string|string[], ...args: any[]): this { if (text) { (<teams.IO365ConnectorCard>this.data.content).title = fmtText(this.session, text, args); } else { delete (<teams.IO365ConnectorCard>this.data.content).title; } return this; } public text(text: string|string[], ...args: any[]): this { if (text) { (<teams.IO365ConnectorCard>this.data.content).text = fmtText(this.session, text, args); } else { delete (<teams.IO365ConnectorCard>this.data.content).text; } return this; } public summary(text: string|string[], ...args: any[]): this { (<teams.IO365ConnectorCard>this.data.content).summary = text ? fmtText(this.session, text, args) : ''; return this; } public themeColor(color: string): this { if (color) { (<teams.IO365ConnectorCard>this.data.content).themeColor = color; } else { delete (<teams.IO365ConnectorCard>this.data.content).themeColor; } return this; } public sections(list: teams.IO365ConnectorCardSection[]|teams.IIsO365ConnectorCardSection[]): this { (<teams.IO365ConnectorCard>this.data.content).sections = []; if (list) { for (let i = 0; i < list.length; i++) { let section = list[i]; (<teams.IO365ConnectorCard>this.data.content).sections.push((<teams.IIsO365ConnectorCardSection>section).toSection ? (<teams.IIsO365ConnectorCardSection>section).toSection() : <teams.IO365ConnectorCardSection>section); } } return this; } public potentialAction(list: teams.IO365ConnectorCardActionBase[]|teams.IIsO365ConnectorCardActionBase[]): this { (<teams.IO365ConnectorCard>this.data.content).potentialAction = []; if (list) { for (let i = 0; i < list.length; i++) { let action = list[i]; let obj = (<teams.IIsO365ConnectorCardActionBase>action).toAction ? (<teams.IIsO365ConnectorCardActionBase>action).toAction() : <teams.IO365ConnectorCardActionBase>action; (<teams.IO365ConnectorCard>this.data.content).potentialAction.push(o365ActionToPayload(obj)); } } return this; } public toAttachment(): builder.IAttachment { return this.data; } } export enum O365ConnectorCardActivityImageTypes { Avatar, Article } export class O365ConnectorCardSection implements teams.IIsO365ConnectorCardSection { private data = <teams.IO365ConnectorCardSection>{}; constructor(protected session?: builder.Session) { } public title(text: string|string[], ...args: any[]): this { if (text) { this.data.title = fmtText(this.session, text, args); } else { delete this.data.title; } return this; } public text(text: string|string[], ...args: any[]): this { if (text) { this.data.text = fmtText(this.session, text, args); } else { delete this.data.text; } return this; } public activityTitle(text: string|string[], ...args: any[]): this { if (text) { this.data.activityTitle = fmtText(this.session, text, args); } else { delete this.data.activityTitle; } return this; } public activitySubtitle(text: string|string[], ...args: any[]): this { if (text) { this.data.activitySubtitle = fmtText(this.session, text, args); } else { delete this.data.activitySubtitle; } return this; } public activityText(text: string|string[], ...args: any[]): this { if (text) { this.data.activityText = fmtText(this.session, text, args); } else { delete this.data.activityText; } return this; } public activityImage(imageUrl: string): this { if (imageUrl) { this.data.activityImage = imageUrl; if (!this.data.activityImageType) { this.data.activityImageType = 'avatar'; } } else { delete this.data.activityImage; delete this.data.activityImageType; } return this; } public activityImageType(imageType: O365ConnectorCardActivityImageTypes): this { if (imageType as O365ConnectorCardActivityImageTypes === O365ConnectorCardActivityImageTypes.Article) { this.data.activityImageType = 'article'; } else { this.data.activityImageType = 'avatar'; } return this; } public markdown(flag: boolean): this { this.data.markdown = !!flag; return this; } public facts(list: teams.IO365ConnectorCardFact[]|teams.IIsO365ConnectorCardFact[]): this { this.data.facts = []; if (list) { for (let i = 0; i < list.length; i++) { let fact = list[i]; this.data.facts.push((<teams.IIsO365ConnectorCardFact>fact).toFact ? (<teams.IIsO365ConnectorCardFact>fact).toFact() : <teams.IO365ConnectorCardFact>fact); } } return this; } public images(list: teams.IO365ConnectorCardImage[]|teams.IIsO365ConnectorCardImage[]): this { this.data.images = []; if (list) { for (let i = 0; i < list.length; i++) { let image = list[i]; this.data.images.push((<teams.IIsO365ConnectorCardImage>image).toImage ? (<teams.IIsO365ConnectorCardImage>image).toImage() : <teams.IO365ConnectorCardImage>image); } } return this; } public potentialAction(list: teams.IO365ConnectorCardActionBase[]|teams.IIsO365ConnectorCardActionBase[]): this { this.data.potentialAction = []; if (list) { for (let i = 0; i < list.length; i++) { let action = list[i]; let obj = (<teams.IIsO365ConnectorCardActionBase>action).toAction ? (<teams.IIsO365ConnectorCardActionBase>action).toAction() : <teams.IO365ConnectorCardActionBase>action; this.data.potentialAction.push(o365ActionToPayload(obj)); } } return this; } public toSection(): teams.IO365ConnectorCardSection { return this.data; } } export class O365ConnectorCardFact implements teams.IIsO365ConnectorCardFact { private data = <teams.IO365ConnectorCardFact>{ name: '' }; constructor(private session?: builder.Session) { } public name(text: string|string[], ...args: any[]): this { if (text) { this.data.name = fmtText(this.session, text, args); } else { delete this.data.name; } return this; } public value(text: string|string[], ...args: any[]): this { if (text) { this.data.value = fmtText(this.session, text, args); } else { delete this.data.value; } return this; } public toFact(): teams.IO365ConnectorCardFact { return this.data; } } export class O365ConnectorCardImage implements teams.IIsO365ConnectorCardImage { private data = <teams.IO365ConnectorCardImage>{}; constructor(private session?: builder.Session) { } public image(url: string): this { if (url) { this.data.image = url; } return this; } public title(text: string|string[], ...args: any[]): this { if (text) { this.data.title = fmtText(this.session, text, args); } else { delete this.data.title; } return this; } public toImage(): teams.IO365ConnectorCardImage { return this.data; } } export abstract class O365ConnectorCardActionBase implements teams.IIsO365ConnectorCardActionBase { protected data = <teams.IO365ConnectorCardActionBase>{} constructor(protected session?: builder.Session) { } public name(text: string|string[], ...args: any[]): this { if (text) { this.data.name = fmtText(this.session, text, args); } else { delete this.data.name; } return this; } public id(actionId: string): this { if (actionId) { this.data.id = actionId; } else { delete this.data.id; } return this; } protected abstract get type(): string; public toAction(): teams.IO365ConnectorCardActionBase { this.data.type = this.type; return this.data; } } export class O365ConnectorCardViewAction extends O365ConnectorCardActionBase { constructor(protected session?: builder.Session) { super(session); } public target(targetUrl: string): this { (<teams.IO365ConnectorCardViewAction>this.data).target = targetUrl ? [targetUrl] : []; return this; } protected get type(): string { return 'ViewAction'; } } export class O365ConnectorCardOpenUri extends O365ConnectorCardActionBase { private targetsData: {[os in teams.O365ConnectorCardOpenUriOS]?: string} = {}; constructor(protected session?: builder.Session) { super(session); } public targets(platformUrlMap: {[os in teams.O365ConnectorCardOpenUriOS]?: string}): this { if (platformUrlMap) { this.targetsData = platformUrlMap; this.update(); } return this; } public default(targetUrl: string): this { if (targetUrl) { this.targetsData.default = targetUrl; } else { delete this.targetsData.default; } this.update(); return this; } public iOS(targetUrl: string): this { if (targetUrl) { this.targetsData.iOS = targetUrl; } else { delete this.targetsData.iOS; } this.update(); return this; } public android(targetUrl: string): this { if (targetUrl) { this.targetsData.android = targetUrl; } else { delete this.targetsData.android; } this.update(); return this; } public windowsPhone(targetUrl: string): this { if (targetUrl) { this.targetsData.windows = targetUrl; } else { delete this.targetsData.windows; } this.update(); return this; } private update(): void { let data: teams.IO365ConnectorCardOpenUriTarget[] = []; for (let key in this.targetsData) { let val: string = this.targetsData[ <teams.O365ConnectorCardOpenUriOS>key ]; if (val) { data.push(<teams.IO365ConnectorCardOpenUriTarget> { os: key, uri: val }); } } (<teams.IO365ConnectorCardOpenUri>this.data).targets = data; } protected get type(): string { return 'OpenUri'; } } export class O365ConnectorCardHttpPOST extends O365ConnectorCardActionBase { constructor(protected session?: builder.Session) { super(session); } public body(text: string): this { if (text) { (<teams.IO365ConnectorCardHttpPOST>this.data).body = text; } else { delete (<teams.IO365ConnectorCardHttpPOST>this.data).body; } return this; } protected get type(): string { return 'HttpPOST'; } } export class O365ConnectorCardActionCard extends O365ConnectorCardActionBase { constructor(protected session?: builder.Session) { super(session); } public actions(list: teams.IO365ConnectorCardActionBase[]|teams.IIsO365ConnectorCardActionBase[]): this { let data = <teams.IO365ConnectorCardActionCard> this.data; data.actions = []; if (list) { for (let i = 0; i < list.length; i++) { let action = list[i]; let obj = (<teams.IIsO365ConnectorCardActionBase>action).toAction ? (<teams.IIsO365ConnectorCardActionBase>action).toAction() : <teams.IO365ConnectorCardActionBase>action; data.actions.push(o365ActionToPayload(obj)); } } return this; } public inputs(list: teams.IO365ConnectorCardInputBase[]|teams.IIsO365ConnectorCardInputBase[]): this { let data = <teams.IO365ConnectorCardActionCard> this.data; data.inputs = []; if (list) { for (let i = 0; i < list.length; i++) { let input = list[i]; let obj = (<teams.IIsO365ConnectorCardInputBase>input).toInput ? (<teams.IIsO365ConnectorCardInputBase>input).toInput() : <teams.IO365ConnectorCardInputBase>input; data.inputs.push(o365InputToPayload(obj)); } } return this; } protected get type(): string { return 'ActionCard'; } } export abstract class O365ConnectorCardInputBase implements teams.IIsO365ConnectorCardInputBase { protected data = <teams.IO365ConnectorCardInputBase>{}; constructor(protected session?: builder.Session) { } public id(inputId: string): this { if (inputId) { this.data.id = inputId; } else { delete this.data.id; } return this; } public isRequired(flag: boolean): this { this.data.isRequired = !!flag; return this; } public title(text: string|string[], ...args: any[]): this { if (text) { this.data.title = fmtText(this.session, text, args); } else { delete this.data.title; } return this; } public value(text: string): this { if (text) { this.data.value = text; } else { delete this.data.value; } return this; } protected abstract get type(): string; public toInput(): teams.IO365ConnectorCardInputBase { this.data.type = this.type; return this.data; } } export class O365ConnectorCardTextInput extends O365ConnectorCardInputBase { constructor(protected session?: builder.Session) { super(session); } public isMultiline(flag: boolean): this { (<teams.IO365ConnectorCardTextInput>this.data).isMultiline = !!flag; return this; } public maxLength(len: number): this { if (len && len > 0) { (<teams.IO365ConnectorCardTextInput>this.data).maxLength = len; } else { delete (<teams.IO365ConnectorCardTextInput>this.data).maxLength; } return this; } protected get type(): string { return 'textInput'; } } export class O365ConnectorCardDateInput extends O365ConnectorCardInputBase { constructor(protected session?: builder.Session) { super(session); } public includeTime(flag: boolean): this { (<teams.IO365ConnectorCardDateInput>this.data).includeTime = !!flag; return this; } protected get type(): string { return 'dateInput'; } } export class O365ConnectorCardMultichoiceInput extends O365ConnectorCardInputBase { constructor(protected session?: builder.Session) { super(session); } public isMultiSelect(flag: boolean): this { (<teams.IO365ConnectorCardMultichoiceInput>this.data).isMultiSelect = !!flag; return this; } public style(s: teams.O365ConnectorCardMultichoiceInputStyle): this { if (s) { (<teams.IO365ConnectorCardMultichoiceInput>this.data).style = s; } else { delete (<teams.IO365ConnectorCardMultichoiceInput>this.data).style; } return this; } public compactStyle(): this { (<teams.IO365ConnectorCardMultichoiceInput>this.data).style = 'compact'; return this; } public expandedStyle(): this { (<teams.IO365ConnectorCardMultichoiceInput>this.data).style = 'expanded'; return this; } public choices(list: teams.IO365ConnectorCardMultichoiceInputChoice[]|teams.IIsO365ConnectorCardMultichoiceInputChoice[]): this { let choicesData: teams.IO365ConnectorCardMultichoiceInputChoice[] = []; if (list) { for (let i = 0; i < list.length; i++) { let item = list[i]; if ((<teams.IIsO365ConnectorCardMultichoiceInputChoice>item).toChoice) { choicesData.push((<teams.IIsO365ConnectorCardMultichoiceInputChoice>item).toChoice()); } else { choicesData.push(<teams.IO365ConnectorCardMultichoiceInputChoice>item); } } } (<teams.IO365ConnectorCardMultichoiceInput>this.data).choices = choicesData; return this; } protected get type(): string { return 'multichoiceInput'; } } export class O365ConnectorCardMultichoiceInputChoice implements teams.IIsO365ConnectorCardMultichoiceInputChoice{ private data = <teams.IO365ConnectorCardMultichoiceInputChoice>{}; constructor(protected session?: builder.Session) { } public display(text: string|string[], ...args: any[]): this { if (text) { this.data.display = fmtText(this.session, text, args); } else { delete this.data.display; } return this; } public value(text: string): this { if (text) { this.data.value = text; } else { delete this.data.value; } return this; } public toChoice(): teams.IO365ConnectorCardMultichoiceInputChoice { return this.data; } } export function fmtText(session: builder.Session, prompts: string|string[], args?: any[]): string { var fmt = builder.Message.randomPrompt(prompts); if (session) { // Run prompt through localizer fmt = session.gettext(fmt); } return args && args.length > 0 ? sprintf.vsprintf(fmt, args) : fmt; } export function o365ActionToPayload(obj: teams.IO365ConnectorCardActionBase): teams.IO365ConnectorCardActionBase{ if (obj.type) { (<any> obj)['@type'] = obj.type; delete obj.type; } if (obj.id) { (<any> obj)['@id'] = obj.id; delete obj.id; } return obj; } export function o365InputToPayload(obj: teams.IO365ConnectorCardInputBase): teams.IO365ConnectorCardInputBase{ if (obj.type) { (<any> obj)['@type'] = obj.type; delete obj.type; } return obj; }
the_stack
import { FocusKeyManager } from '@angular/cdk/a11y'; import { Direction, Directionality } from '@angular/cdk/bidi'; import { coerceNumberProperty } from '@angular/cdk/coercion'; import { DOWN_ARROW, ENTER, hasModifierKey, LEFT_ARROW, RIGHT_ARROW, SPACE, UP_ARROW } from '@angular/cdk/keycodes'; import { ViewportRuler } from '@angular/cdk/overlay'; import { AfterContentChecked, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, Input, NgZone, OnChanges, OnDestroy, Optional, Output, QueryList, SimpleChanges, TemplateRef, ViewChild, ViewEncapsulation } from '@angular/core'; import { animationFrameScheduler, asapScheduler, merge, of, Subject } from 'rxjs'; import { auditTime, takeUntil } from 'rxjs/operators'; import { NzResizeObserver } from 'ng-zorro-antd/cdk/resize-observer'; import { reqAnimFrame } from 'ng-zorro-antd/core/polyfill'; import { NumberInput, NzSafeAny } from 'ng-zorro-antd/core/types'; import { NzTabPositionMode, NzTabScrollEvent, NzTabScrollListOffsetEvent } from './interfaces'; import { NzTabAddButtonComponent } from './tab-add-button.component'; import { NzTabNavItemDirective } from './tab-nav-item.directive'; import { NzTabNavOperationComponent } from './tab-nav-operation.component'; import { NzTabsInkBarDirective } from './tabs-ink-bar.directive'; const RESIZE_SCHEDULER = typeof requestAnimationFrame !== 'undefined' ? animationFrameScheduler : asapScheduler; const CSS_TRANSFORM_TIME = 150; @Component({ selector: 'nz-tabs-nav', exportAs: 'nzTabsNav', preserveWhitespaces: false, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, template: ` <div class="ant-tabs-nav-wrap" [class.ant-tabs-nav-wrap-ping-left]="pingLeft" [class.ant-tabs-nav-wrap-ping-right]="pingRight" [class.ant-tabs-nav-wrap-ping-top]="pingTop" [class.ant-tabs-nav-wrap-ping-bottom]="pingBottom" #navWarp > <div class="ant-tabs-nav-list" #navList nzTabScrollList (offsetChange)="onOffsetChange($event)" (tabScroll)="tabScroll.emit($event)" > <ng-content></ng-content> <button *ngIf="showAddButton" nz-tab-add-button [addIcon]="addIcon" (click)="addClicked.emit()"></button> <div nz-tabs-ink-bar [hidden]="hideBar" [position]="position" [animated]="inkBarAnimated"></div> </div> </div> <nz-tab-nav-operation (addClicked)="addClicked.emit()" (selected)="onSelectedFromMenu($event)" [addIcon]="addIcon" [addable]="addable" [items]="hiddenItems" ></nz-tab-nav-operation> <div class="ant-tabs-extra-content" *ngIf="extraTemplate"> <ng-template [ngTemplateOutlet]="extraTemplate"></ng-template> </div> `, host: { role: 'tablist', class: 'ant-tabs-nav', '(keydown)': 'handleKeydown($event)' } }) export class NzTabNavBarComponent implements AfterViewInit, AfterContentChecked, OnDestroy, OnChanges { static ngAcceptInputType_selectedIndex: NumberInput; @Output() readonly indexFocused: EventEmitter<number> = new EventEmitter<number>(); @Output() readonly selectFocusedIndex: EventEmitter<number> = new EventEmitter<number>(); @Output() readonly addClicked = new EventEmitter<void>(); @Output() readonly tabScroll = new EventEmitter<NzTabScrollEvent>(); @Input() position: NzTabPositionMode = 'horizontal'; @Input() addable: boolean = false; @Input() hideBar: boolean = false; @Input() addIcon: string | TemplateRef<NzSafeAny> = 'plus'; @Input() inkBarAnimated = true; @Input() extraTemplate?: TemplateRef<void>; @Input() get selectedIndex(): number { return this._selectedIndex; } set selectedIndex(value: number) { const newValue = coerceNumberProperty(value); if (this._selectedIndex !== newValue) { this._selectedIndex = value; this.selectedIndexChanged = true; if (this.keyManager) { this.keyManager.updateActiveItem(value); } } } @ViewChild('navWarp', { static: true }) navWarpRef!: ElementRef<HTMLElement>; @ViewChild('navList', { static: true }) navListRef!: ElementRef<HTMLElement>; @ViewChild(NzTabNavOperationComponent, { static: true }) operationRef!: NzTabNavOperationComponent; @ViewChild(NzTabAddButtonComponent, { static: false }) addBtnRef!: NzTabAddButtonComponent; @ViewChild(NzTabsInkBarDirective, { static: true }) inkBar!: NzTabsInkBarDirective; @ContentChildren(NzTabNavItemDirective, { descendants: true }) items!: QueryList<NzTabNavItemDirective>; /** Tracks which element has focus; used for keyboard navigation */ get focusIndex(): number { return this.keyManager ? this.keyManager.activeItemIndex! : 0; } /** When the focus index is set, we must manually send focus to the correct label */ set focusIndex(value: number) { if (!this.isValidIndex(value) || this.focusIndex === value || !this.keyManager) { return; } this.keyManager.setActiveItem(value); } get showAddButton(): boolean { return this.hiddenItems.length === 0 && this.addable; } translate: null | string = null; transformX = 0; transformY = 0; pingLeft = false; pingRight = false; pingTop = false; pingBottom = false; hiddenItems: NzTabNavItemDirective[] = []; private keyManager!: FocusKeyManager<NzTabNavItemDirective>; private destroy$ = new Subject<void>(); private _selectedIndex = 0; private wrapperWidth = 0; private wrapperHeight = 0; private scrollListWidth = 0; private scrollListHeight = 0; private operationWidth = 0; private operationHeight = 0; private addButtonWidth = 0; private addButtonHeight = 0; private selectedIndexChanged = false; private lockAnimationTimeoutId = -1; private cssTransformTimeWaitingId = -1; constructor( private cdr: ChangeDetectorRef, private ngZone: NgZone, private viewportRuler: ViewportRuler, private nzResizeObserver: NzResizeObserver, @Optional() private dir: Directionality ) {} ngAfterViewInit(): void { const dirChange = this.dir ? this.dir.change : of(null); const resize = this.viewportRuler.change(150); const realign = () => { this.updateScrollListPosition(); this.alignInkBarToSelectedTab(); }; this.keyManager = new FocusKeyManager<NzTabNavItemDirective>(this.items) .withHorizontalOrientation(this.getLayoutDirection()) .withWrap(); this.keyManager.updateActiveItem(this.selectedIndex); reqAnimFrame(realign); merge(this.nzResizeObserver.observe(this.navWarpRef), this.nzResizeObserver.observe(this.navListRef)) .pipe(takeUntil(this.destroy$), auditTime(16, RESIZE_SCHEDULER)) .subscribe(() => { realign(); }); merge(dirChange, resize, this.items.changes) .pipe(takeUntil(this.destroy$)) .subscribe(() => { Promise.resolve().then(realign); this.keyManager.withHorizontalOrientation(this.getLayoutDirection()); }); this.keyManager.change.pipe(takeUntil(this.destroy$)).subscribe(newFocusIndex => { this.indexFocused.emit(newFocusIndex); this.setTabFocus(newFocusIndex); this.scrollToTab(this.keyManager.activeItem!); }); } ngAfterContentChecked(): void { if (this.selectedIndexChanged) { this.updateScrollListPosition(); this.alignInkBarToSelectedTab(); this.selectedIndexChanged = false; this.cdr.markForCheck(); } } ngOnDestroy(): void { clearTimeout(this.lockAnimationTimeoutId); clearTimeout(this.cssTransformTimeWaitingId); this.destroy$.next(); this.destroy$.complete(); } onSelectedFromMenu(tab: NzTabNavItemDirective): void { const tabIndex = this.items.toArray().findIndex(e => e === tab); if (tabIndex !== -1) { this.keyManager.updateActiveItem(tabIndex); if (this.focusIndex !== this.selectedIndex) { this.selectFocusedIndex.emit(this.focusIndex); this.scrollToTab(tab); } } } onOffsetChange(e: NzTabScrollListOffsetEvent): void { if (this.position === 'horizontal') { if (this.lockAnimationTimeoutId === -1) { if (this.transformX >= 0 && e.x > 0) { return; } if (this.transformX <= this.wrapperWidth - this.scrollListWidth && e.x < 0) { return; } } e.event.preventDefault(); this.transformX = this.clampTransformX(this.transformX + e.x); this.setTransform(this.transformX, 0); } else { if (this.lockAnimationTimeoutId === -1) { if (this.transformY >= 0 && e.y > 0) { return; } if (this.transformY <= this.wrapperHeight - this.scrollListHeight && e.y < 0) { return; } } e.event.preventDefault(); this.transformY = this.clampTransformY(this.transformY + e.y); this.setTransform(0, this.transformY); } this.lockAnimation(); this.setVisibleRange(); this.setPingStatus(); } handleKeydown(event: KeyboardEvent): void { const inNavigationList = this.navWarpRef.nativeElement.contains(event.target as HTMLElement); if (hasModifierKey(event) || !inNavigationList) { return; } switch (event.keyCode) { case LEFT_ARROW: case UP_ARROW: case RIGHT_ARROW: case DOWN_ARROW: this.lockAnimation(); this.keyManager.onKeydown(event); break; case ENTER: case SPACE: if (this.focusIndex !== this.selectedIndex) { this.selectFocusedIndex.emit(this.focusIndex); } break; default: this.keyManager.onKeydown(event); } } private isValidIndex(index: number): boolean { if (!this.items) { return true; } const tab = this.items ? this.items.toArray()[index] : null; return !!tab && !tab.disabled; } private scrollToTab(tab: NzTabNavItemDirective): void { if (!this.items.find(e => e === tab)) { return; } const tabs = this.items.toArray(); if (this.position === 'horizontal') { let newTransform = this.transformX; if (this.getLayoutDirection() === 'rtl') { const right = tabs[0].left + tabs[0].width - tab.left - tab.width; if (right < this.transformX) { newTransform = right; } else if (right + tab.width > this.transformX + this.wrapperWidth) { newTransform = right + tab.width - this.wrapperWidth; } } else if (tab.left < -this.transformX) { newTransform = -tab.left; } else if (tab.left + tab.width > -this.transformX + this.wrapperWidth) { newTransform = -(tab.left + tab.width - this.wrapperWidth); } this.transformX = newTransform; this.transformY = 0; this.setTransform(newTransform, 0); } else { let newTransform = this.transformY; if (tab.top < -this.transformY) { newTransform = -tab.top; } else if (tab.top + tab.height > -this.transformY + this.wrapperHeight) { newTransform = -(tab.top + tab.height - this.wrapperHeight); } this.transformY = newTransform; this.transformX = 0; this.setTransform(0, newTransform); } clearTimeout(this.cssTransformTimeWaitingId); this.cssTransformTimeWaitingId = setTimeout(() => { this.setVisibleRange(); }, CSS_TRANSFORM_TIME); } private lockAnimation(): void { if (this.lockAnimationTimeoutId === -1) { this.ngZone.runOutsideAngular(() => { this.navListRef.nativeElement.style.transition = 'none'; this.lockAnimationTimeoutId = setTimeout(() => { this.navListRef.nativeElement.style.transition = ''; this.lockAnimationTimeoutId = -1; }, CSS_TRANSFORM_TIME); }); } } private setTransform(x: number, y: number): void { this.navListRef.nativeElement.style.transform = `translate(${x}px, ${y}px)`; } private clampTransformX(transform: number): number { const scrollWidth = this.wrapperWidth - this.scrollListWidth; if (this.getLayoutDirection() === 'rtl') { return Math.max(Math.min(scrollWidth, transform), 0); } else { return Math.min(Math.max(scrollWidth, transform), 0); } } private clampTransformY(transform: number): number { return Math.min(Math.max(this.wrapperHeight - this.scrollListHeight, transform), 0); } private updateScrollListPosition(): void { this.resetSizes(); this.transformX = this.clampTransformX(this.transformX); this.transformY = this.clampTransformY(this.transformY); this.setVisibleRange(); this.setPingStatus(); if (this.keyManager) { this.keyManager.updateActiveItem(this.keyManager.activeItemIndex!); if (this.keyManager.activeItem) { this.scrollToTab(this.keyManager.activeItem); } } } private resetSizes(): void { this.addButtonWidth = this.addBtnRef ? this.addBtnRef.getElementWidth() : 0; this.addButtonHeight = this.addBtnRef ? this.addBtnRef.getElementHeight() : 0; this.operationWidth = this.operationRef.getElementWidth(); this.operationHeight = this.operationRef.getElementHeight(); this.wrapperWidth = this.navWarpRef.nativeElement.offsetWidth || 0; this.wrapperHeight = this.navWarpRef.nativeElement.offsetHeight || 0; this.scrollListHeight = this.navListRef.nativeElement.offsetHeight || 0; this.scrollListWidth = this.navListRef.nativeElement.offsetWidth || 0; } private alignInkBarToSelectedTab(): void { const selectedItem = this.items && this.items.length ? this.items.toArray()[this.selectedIndex] : null; const selectedItemElement = selectedItem ? selectedItem.elementRef.nativeElement : null; if (selectedItemElement) { /** * .ant-tabs-nav-list - Target offset parent element * └──.ant-tabs-tab * └──.ant-tabs-tab-btn - Currently focused element */ this.inkBar.alignToElement(selectedItemElement.parentElement!); } } private setPingStatus(): void { const ping = { top: false, right: false, bottom: false, left: false }; const navWarp = this.navWarpRef.nativeElement; if (this.position === 'horizontal') { if (this.getLayoutDirection() === 'rtl') { ping.right = this.transformX > 0; ping.left = this.transformX + this.wrapperWidth < this.scrollListWidth; } else { ping.left = this.transformX < 0; ping.right = -this.transformX + this.wrapperWidth < this.scrollListWidth; } } else { ping.top = this.transformY < 0; ping.bottom = -this.transformY + this.wrapperHeight < this.scrollListHeight; } (Object.keys(ping) as Array<'top' | 'right' | 'bottom' | 'left'>).forEach(pos => { const className = `ant-tabs-nav-wrap-ping-${pos}`; if (ping[pos]) { navWarp.classList.add(className); } else { navWarp.classList.remove(className); } }); } private setVisibleRange(): void { let unit: 'width' | 'height'; let position: 'left' | 'top' | 'right'; let transformSize: number; let basicSize: number; let tabContentSize: number; let addSize: number; const tabs = this.items.toArray(); const DEFAULT_SIZE = { width: 0, height: 0, left: 0, top: 0, right: 0 }; const getOffset = (index: number): number => { let offset: number; const size = tabs[index] || DEFAULT_SIZE; if (position === 'right') { offset = tabs[0].left + tabs[0].width - tabs[index].left - tabs[index].width; } else { offset = size[position]; } return offset; }; if (this.position === 'horizontal') { unit = 'width'; basicSize = this.wrapperWidth; tabContentSize = this.scrollListWidth - (this.hiddenItems.length ? this.operationWidth : 0); addSize = this.addButtonWidth; transformSize = Math.abs(this.transformX); if (this.getLayoutDirection() === 'rtl') { position = 'right'; this.pingRight = this.transformX > 0; this.pingLeft = this.transformX + this.wrapperWidth < this.scrollListWidth; } else { this.pingLeft = this.transformX < 0; this.pingRight = -this.transformX + this.wrapperWidth < this.scrollListWidth; position = 'left'; } } else { unit = 'height'; basicSize = this.wrapperHeight; tabContentSize = this.scrollListHeight - (this.hiddenItems.length ? this.operationHeight : 0); addSize = this.addButtonHeight; position = 'top'; transformSize = -this.transformY; this.pingTop = this.transformY < 0; this.pingBottom = -this.transformY + this.wrapperHeight < this.scrollListHeight; } let mergedBasicSize = basicSize; if (tabContentSize + addSize > basicSize) { mergedBasicSize = basicSize - addSize; } if (!tabs.length) { this.hiddenItems = []; this.cdr.markForCheck(); return; } const len = tabs.length; let endIndex = len; for (let i = 0; i < len; i += 1) { const offset = getOffset(i); const size = tabs[i] || DEFAULT_SIZE; if (offset + size[unit] > transformSize + mergedBasicSize) { endIndex = i - 1; break; } } let startIndex = 0; for (let i = len - 1; i >= 0; i -= 1) { const offset = getOffset(i); if (offset < transformSize) { startIndex = i + 1; break; } } const startHiddenTabs = tabs.slice(0, startIndex); const endHiddenTabs = tabs.slice(endIndex + 1); this.hiddenItems = [...startHiddenTabs, ...endHiddenTabs]; this.cdr.markForCheck(); } private getLayoutDirection(): Direction { return this.dir && this.dir.value === 'rtl' ? 'rtl' : 'ltr'; } private setTabFocus(_tabIndex: number): void {} ngOnChanges(changes: SimpleChanges): void { const { position } = changes; // The first will be aligning in ngAfterViewInit if (position && !position.isFirstChange()) { this.alignInkBarToSelectedTab(); this.lockAnimation(); this.updateScrollListPosition(); } } }
the_stack
import uuid from "uuid/v4"; import QueueStorageContext from "../context/QueueStorageContext"; import StorageErrorFactory from "../errors/StorageErrorFactory"; import * as Models from "../generated/artifacts/models"; import Context from "../generated/Context"; import IMessagesHandler from "../generated/handlers/IMessagesHandler"; import { MessageModel } from "../persistence/IQueueMetadataStore"; import { DEFUALT_DEQUEUE_VISIBILITYTIMEOUT, DEFUALT_MESSAGETTL, DEQUEUE_NUMOFMESSAGES_MAX, DEQUEUE_NUMOFMESSAGES_MIN, DEQUEUE_VISIBILITYTIMEOUT_MAX, DEQUEUE_VISIBILITYTIMEOUT_MIN, EMPTY_EXTENT_CHUNK, ENQUEUE_VISIBILITYTIMEOUT_MAX, ENQUEUE_VISIBILITYTIMEOUT_MIN, MESSAGETEXT_LENGTH_MAX, MESSAGETTL_MIN, NEVER_EXPIRE_DATE, QUEUE_API_VERSION } from "../utils/constants"; import { getPopReceipt, getUTF8ByteSize, parseXMLwithEmpty, readStreamToString } from "../utils/utils"; import BaseHandler from "./BaseHandler"; /** * MessagesHandler handles Azure Storage messages related requests. * * @export * @class MessagesHandler * @implements {IMessagesHandler} */ export default class MessagesHandler extends BaseHandler implements IMessagesHandler { /** * Dequeue the messages. * * @param {Models.MessagesDequeueOptionalParams} options * @param {Context} context * @returns {Promise<Models.MessagesDequeueResponse>} * @memberof MessagesHandler */ public async dequeue( options: Models.MessagesDequeueOptionalParams, context: Context ): Promise<Models.MessagesDequeueResponse> { const queueCtx = new QueueStorageContext(context); const accountName = queueCtx.account!; const queueName = queueCtx.queue!; const popReceipt = getPopReceipt(context.startTime!); // Validate the query parameters. const timeNextVisible = new Date( context.startTime!.getTime() + DEFUALT_DEQUEUE_VISIBILITYTIMEOUT * 1000 // 30s as default, convert to ms ); if (options.visibilitytimeout !== undefined) { if ( options.visibilitytimeout < DEQUEUE_VISIBILITYTIMEOUT_MIN || options.visibilitytimeout > DEQUEUE_VISIBILITYTIMEOUT_MAX ) { throw StorageErrorFactory.getOutOfRangeQueryParameterValue( context.contextID, { QueryParameterName: "visibilitytimeout", QueryParameterValue: `${options.visibilitytimeout}`, MinimumAllowed: `${DEQUEUE_VISIBILITYTIMEOUT_MIN}`, MaximumAllowed: `${DEQUEUE_VISIBILITYTIMEOUT_MAX}` } ); } timeNextVisible.setTime( context.startTime!.getTime() + options.visibilitytimeout * 1000 ); } let numberOfMessages = 1; if (options.numberOfMessages !== undefined) { if ( options.numberOfMessages < DEQUEUE_NUMOFMESSAGES_MIN || options.numberOfMessages > DEQUEUE_NUMOFMESSAGES_MAX ) { throw StorageErrorFactory.getOutOfRangeQueryParameterValue( context.contextID, { QueryParameterName: "numofmessages", QueryParameterValue: `${options.numberOfMessages}`, MinimumAllowed: `${DEQUEUE_NUMOFMESSAGES_MIN}`, MaximumAllowed: `${DEQUEUE_NUMOFMESSAGES_MAX}` } ); } numberOfMessages = options.numberOfMessages; } // Get metadata. const messages = await this.metadataStore.getMessages( accountName, queueName, timeNextVisible, popReceipt, numberOfMessages, context.startTime!, context ); const response: any = []; const responseArray = response as Models.DequeuedMessageItem[]; const responseObject = response as Models.MessagesDequeueHeaders & { statusCode: 200; }; // Read the message text from file system. for (const message of messages) { const textStream = await this.extentStore.readExtent( message.persistency, context.contextID ); const text = await readStreamToString(textStream); const dequeuedMessage: Models.DequeuedMessageItem = { ...message, messageText: text }; responseArray.push(dequeuedMessage); } responseObject.date = context.startTime!; responseObject.requestId = context.contextID; responseObject.version = QUEUE_API_VERSION; responseObject.statusCode = 200; responseObject.clientRequestId = options.requestId; return response; } /** * Clear the messages in a queue * * @param {Models.MessagesClearOptionalParams} options * @param {Context} context * @returns {Promise<Models.MessagesClearResponse>} * @memberof MessagesHandler */ public async clear( options: Models.MessagesClearOptionalParams, context: Context ): Promise<Models.MessagesClearResponse> { const queueCtx = new QueueStorageContext(context); const accountName = queueCtx.account!; const queueName = queueCtx.queue!; await this.metadataStore.clearMessages(accountName, queueName, context); const response: Models.MessagesClearResponse = { date: context.startTime, requestId: queueCtx.contextID, statusCode: 204, version: QUEUE_API_VERSION, clientRequestId: options.requestId }; return response; } /** * Enqueue a message * * @param {Models.QueueMessage} queueMessage * @param {Models.MessagesEnqueueOptionalParams} options * @param {Context} context * @returns {Promise<Models.MessagesEnqueueResponse>} * @memberof MessagesHandler */ public async enqueue( queueMessage: Models.QueueMessage, options: Models.MessagesEnqueueOptionalParams, context: Context ): Promise<Models.MessagesEnqueueResponse> { const queueCtx = new QueueStorageContext(context); const accountName = queueCtx.account!; const queueName = queueCtx.queue!; if (queueMessage.messageText === undefined) { const body = queueCtx.request!.getBody(); // TODO: deserialize does not support the message text with only empty character. // If the text is undefined, try to retrive it from the XML body here. const parsedBody = await parseXMLwithEmpty(body || ""); for (const text in parsedBody) { if ( parsedBody.hasOwnProperty(text) && text.toLowerCase() === "messagetext" ) { queueMessage.messageText = parsedBody[text]; break; } } } if (queueMessage.messageText === undefined) { throw StorageErrorFactory.getInvalidXmlDocument(queueCtx.contextID!); } if (getUTF8ByteSize(queueMessage.messageText) > MESSAGETEXT_LENGTH_MAX) { throw StorageErrorFactory.getRequestBodyTooLarge(queueCtx.contextID!, { MaxLimit: `${MESSAGETEXT_LENGTH_MAX}` }); } const message: MessageModel = { accountName, queueName, messageId: uuid(), insertionTime: new Date(context.startTime!), expirationTime: new Date( context.startTime!.getTime() + DEFUALT_MESSAGETTL * 1000 ), // Default ttl is 7 days. dequeueCount: 0, timeNextVisible: new Date(context.startTime!), popReceipt: getPopReceipt(context.startTime!), persistency: EMPTY_EXTENT_CHUNK // Provide an empty item to initialize the whole object. }; if (options.visibilitytimeout !== undefined) { if ( options.visibilitytimeout < ENQUEUE_VISIBILITYTIMEOUT_MIN || options.visibilitytimeout > ENQUEUE_VISIBILITYTIMEOUT_MAX ) { throw StorageErrorFactory.getOutOfRangeQueryParameterValue( context.contextID, { QueryParameterName: "visibilitytimeout", QueryParameterValue: `${options.visibilitytimeout}`, MinimumAllowed: `${ENQUEUE_VISIBILITYTIMEOUT_MIN}`, MaximumAllowed: `${ENQUEUE_VISIBILITYTIMEOUT_MAX}` } ); } message.timeNextVisible.setTime( context.startTime!.getTime() + options.visibilitytimeout * 1000 ); } if (options.messageTimeToLive !== undefined) { if (options.messageTimeToLive === -1) { message.expirationTime = new Date(NEVER_EXPIRE_DATE); } else if (options.messageTimeToLive < MESSAGETTL_MIN) { throw StorageErrorFactory.getInvalidQueryParameterValue( context.contextID, { QueryParameterName: "messagettl", QueryParameterValue: `${options.messageTimeToLive}`, Reason: `Value must be greater than or equal to 1, or -1 to indicate an infinite TTL.` } ); } else if ( options.visibilitytimeout !== undefined && options.visibilitytimeout >= options.messageTimeToLive ) { throw StorageErrorFactory.getInvalidQueryParameterValue( context.contextID, { QueryParameterName: "visibilitytimeout", QueryParameterValue: `${options.visibilitytimeout}`, Reason: `messagettl must be greater than visibilitytimeout.` } ); } else { if ( new Date(NEVER_EXPIRE_DATE).getTime() - context.startTime!.getTime() < options.messageTimeToLive * 1000 ) { message.expirationTime = new Date(NEVER_EXPIRE_DATE); } else { message.expirationTime.setTime( context.startTime!.getTime() + options.messageTimeToLive * 1000 ); } } } // Write data to file system after the validation pass. const extentChunk = await this.extentStore.appendExtent( Buffer.from(queueMessage.messageText), context.contextID ); message.persistency = extentChunk; await this.metadataStore.insertMessage(message); const response: any = []; const responseArray = response as Models.EnqueuedMessage[]; const responseObject = response as Models.MessagesEnqueueHeaders & { statusCode: 201; }; const enqueuedMessage: Models.EnqueuedMessage = message; responseArray.push(enqueuedMessage); responseObject.date = context.startTime!; responseObject.requestId = context.contextID; responseObject.version = QUEUE_API_VERSION; responseObject.statusCode = 201; responseObject.clientRequestId = options.requestId; return response; } /** * get the peek messages without altering the visibility * * @param {Models.MessagesPeekOptionalParams} options * @param {Context} context * @returns {Promise<Models.MessagesPeekResponse>} * @memberof MessagesHandler */ public async peek( options: Models.MessagesPeekOptionalParams, context: Context ): Promise<Models.MessagesPeekResponse> { const queueCtx = new QueueStorageContext(context); const accountName = queueCtx.account!; const queueName = queueCtx.queue!; let numberOfMessages = 1; if (options.numberOfMessages !== undefined) { if ( options.numberOfMessages < DEQUEUE_NUMOFMESSAGES_MIN || options.numberOfMessages > DEQUEUE_NUMOFMESSAGES_MAX ) { throw StorageErrorFactory.getOutOfRangeQueryParameterValue( context.contextID, { QueryParameterName: "numofmessages", QueryParameterValue: `${options.numberOfMessages}`, MinimumAllowed: `${DEQUEUE_NUMOFMESSAGES_MIN}`, MaximumAllowed: `${DEQUEUE_NUMOFMESSAGES_MAX}` } ); } numberOfMessages = options.numberOfMessages; } const messages = await this.metadataStore.peekMessages( accountName, queueName, numberOfMessages, context.startTime!, context ); const response: any = []; const responseArray = response as Models.DequeuedMessageItem[]; const responseObject = response as Models.MessagesDequeueHeaders & { statusCode: 200; }; for (const message of messages) { const textStream = await this.extentStore.readExtent( message.persistency, context.contextID ); const text = await readStreamToString(textStream); const dequeuedMessage: Models.DequeuedMessageItem = { ...message, messageText: text }; responseArray.push(dequeuedMessage); } responseObject.date = context.startTime!; responseObject.requestId = context.contextID; responseObject.version = QUEUE_API_VERSION; responseObject.statusCode = 200; responseObject.clientRequestId = options.requestId; return response; } }
the_stack
import { Argument } from '../Argument'; import { Expression } from '../Expression'; import { mXparserConstants } from '../mXparserConstants'; import { mXparser } from '../mXparser'; import { javaemul } from 'j4ts/j4ts'; import { NumberTheory } from './NumberTheory'; import { MathFunctions } from './MathFunctions'; /** * Statistics - i.e.: mean, variance, standard deviation, etc. * * @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.3.0 * @class */ export class Statistics { public static avg$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double$double$double(f: Expression, index: Argument, from: number, to: number, delta: number): number { if ((/* isNaN */isNaN(delta)) || (/* isNaN */isNaN(from)) || (/* isNaN */isNaN(to)) || (delta === 0))return javaemul.internal.DoubleHelper.NaN; let sum: number = 0; let n: number = 0; if ((to >= from) && (delta > 0)){ let i: number; for(i = from; i < to; i += delta) {{ if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; sum += mXparser.getFunctionValue(f, index, i); n++; };} if (delta - (i - to) > 0.5 * delta){ if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; sum += mXparser.getFunctionValue(f, index, to); n++; } } else if ((to <= from) && (delta < 0)){ let i: number; for(i = from; i > to; i += delta) {{ if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; sum += mXparser.getFunctionValue(f, index, i); n++; };} if (-delta - (to - i) > -0.5 * delta){ if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; sum += mXparser.getFunctionValue(f, index, to); n++; } } else if (from === to)return mXparser.getFunctionValue(f, index, from); return sum / n; } /** * Average from sample function values - iterative operator. * * @param {Expression} f the expression * @param {Argument} index the name of index argument * @param {number} from FROM index = form * @param {number} to TO index = to * @param {number} delta BY delta * * @return {number} product operation (for empty product operations returns 1). * * @see Expression * @see Argument */ public static avg(f?: any, index?: any, from?: any, to?: any, delta?: any): any { if (((f != null && f instanceof <any>Expression) || f === null) && ((index != null && index instanceof <any>Argument) || index === null) && ((typeof from === 'number') || from === null) && ((typeof to === 'number') || to === null) && ((typeof delta === 'number') || delta === null)) { return <any>Statistics.avg$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double$double$double(f, index, from, to, delta); } else if (((f != null && f instanceof <any>Array && (f.length == 0 || f[0] == null ||(typeof f[0] === 'number'))) || f === null) && index === undefined && from === undefined && to === undefined && delta === undefined) { return <any>Statistics.avg$double_A(...f); } else throw new Error('invalid overload'); } public static var$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double$double$double(f: Expression, index: Argument, from: number, to: number, delta: number): number { if ((/* isNaN */isNaN(delta)) || (/* isNaN */isNaN(from)) || (/* isNaN */isNaN(to)) || (delta === 0))return javaemul.internal.DoubleHelper.NaN; return Statistics.var$double_A.apply(this, mXparser.getFunctionValues(f, index, from, to, delta)); } /** * Bias-corrected variance from sample function values - iterative operator. * * @param {Expression} f the expression * @param {Argument} index the name of index argument * @param {number} from FROM index = form * @param {number} to TO index = to * @param {number} delta BY delta * * @return {number} product operation (for empty product operations returns 1). * * @see Expression * @see Argument */ public static var(f?: any, index?: any, from?: any, to?: any, delta?: any): any { if (((f != null && f instanceof <any>Expression) || f === null) && ((index != null && index instanceof <any>Argument) || index === null) && ((typeof from === 'number') || from === null) && ((typeof to === 'number') || to === null) && ((typeof delta === 'number') || delta === null)) { return <any>Statistics.var$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double$double$double(f, index, from, to, delta); } else if (((f != null && f instanceof <any>Array && (f.length == 0 || f[0] == null ||(typeof f[0] === 'number'))) || f === null) && index === undefined && from === undefined && to === undefined && delta === undefined) { return <any>Statistics.var$double_A(...f); } else throw new Error('invalid overload'); } public static std$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double$double$double(f: Expression, index: Argument, from: number, to: number, delta: number): number { if ((/* isNaN */isNaN(delta)) || (/* isNaN */isNaN(from)) || (/* isNaN */isNaN(to)) || (delta === 0))return javaemul.internal.DoubleHelper.NaN; return Statistics.std$double_A.apply(this, mXparser.getFunctionValues(f, index, from, to, delta)); } /** * Bias-corrected standard deviation from sample function values - iterative operator. * * @param {Expression} f the expression * @param {Argument} index the name of index argument * @param {number} from FROM index = form * @param {number} to TO index = to * @param {number} delta BY delta * * @return {number} product operation (for empty product operations returns 1). * * @see Expression * @see Argument */ public static std(f?: any, index?: any, from?: any, to?: any, delta?: any): any { if (((f != null && f instanceof <any>Expression) || f === null) && ((index != null && index instanceof <any>Argument) || index === null) && ((typeof from === 'number') || from === null) && ((typeof to === 'number') || to === null) && ((typeof delta === 'number') || delta === null)) { return <any>Statistics.std$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double$double$double(f, index, from, to, delta); } else if (((f != null && f instanceof <any>Array && (f.length == 0 || f[0] == null ||(typeof f[0] === 'number'))) || f === null) && index === undefined && from === undefined && to === undefined && delta === undefined) { return <any>Statistics.std$double_A(...f); } else throw new Error('invalid overload'); } public static avg$double_A(...numbers: number[]): number { if (numbers == null)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 0)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 1)return numbers[0]; let sum: number = 0; for(let index131=0; index131 < numbers.length; index131++) { let xi = numbers[index131]; { if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(xi))return javaemul.internal.DoubleHelper.NaN; sum += xi; } } return sum / numbers.length; } public static var$double_A(...numbers: number[]): number { if (numbers == null)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 0)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 1){ if (/* isNaN */isNaN(numbers[0]))return javaemul.internal.DoubleHelper.NaN; return 0; } const m: number = Statistics.avg$double_A.apply(this, numbers); let sum: number = 0; for(let index132=0; index132 < numbers.length; index132++) { let xi = numbers[index132]; { if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(xi))return javaemul.internal.DoubleHelper.NaN; sum += (xi - m) * (xi - m); } } return sum / (numbers.length - 1); } public static std$double_A(...numbers: number[]): number { if (numbers == null)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 0)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 1){ if (/* isNaN */isNaN(numbers[0]))return javaemul.internal.DoubleHelper.NaN; return 0; } return MathFunctions.sqrt(Statistics.var$double_A.apply(this, numbers)); } /** * Sample median * @param {double[]} numbers List of number * @return {number} Sample median, if table was empty or null then Double.NaN is returned. */ public static median(...numbers: number[]): number { if (numbers == null)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 0)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 1)return numbers[0]; if (numbers.length === 2)return (numbers[0] + numbers[1]) / 2.0; for(let index133=0; index133 < numbers.length; index133++) { let v = numbers[index133]; { if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(v))return javaemul.internal.DoubleHelper.NaN; } } NumberTheory.sortAsc$double_A(numbers); if ((numbers.length % 2) === 1){ const i: number = ((numbers.length - 1) / 2|0); return numbers[i]; } else { const i: number = ((numbers.length / 2|0)) - 1; return (numbers[i] + numbers[i + 1]) / 2.0; } } /** * Sample mode * @param {double[]} numbers List of number * @return {number} Sample median, if table was empty or null then Double.NaN is returned. */ public static mode(...numbers: number[]): number { if (numbers == null)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 0)return javaemul.internal.DoubleHelper.NaN; if (numbers.length === 1)return numbers[0]; for(let index134=0; index134 < numbers.length; index134++) { let v = numbers[index134]; { if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(v))return javaemul.internal.DoubleHelper.NaN; } } const dist: number[][] = NumberTheory.getDistValues(numbers, true); return dist[0][0]; } } Statistics["__class"] = "org.mariuszgromada.math.mxparser.mathcollection.Statistics";
the_stack
import { join } from 'path'; // @ts-ignore import reduceCalc from 'reduce-css-calc'; import classnames from './config/classnames'; import defaultScreens from './config/screens'; import defaultTokens from './config/tokens'; import { IClasses, IClassesByType, IConfig, IEvaluatedClassnames, IEvaluatedConfig, IEvaluatedThemes, IExtractedClass, IExtractedClasses, IGlobalTokens, IToken, } from './types'; export const allowedPseudoDecorators = [ 'hover', 'focus', 'active', 'disabled', 'visited', 'firstChild', 'lastChild', 'oddChild', 'evenChild', 'focusWithin', ]; export const allowedPseudoElementDecorators = ['before', 'after', 'firstLine', 'firstLetter', 'selection']; export const getClassesFromConfig = (classnameKey: string, config: IEvaluatedConfig) => { const classname = config.classnames[classnameKey]; return Object.keys(classname.tokens).reduce((aggr, tokenKey) => { const id = `${camelToDash(classnameKey)}-${tokenKey}`; const cssDeriver = config.classnames[classnameKey].css; return { ...aggr, [id]: { id, classname: classnameKey, token: tokenKey, derived: Array.isArray(cssDeriver) ? cssDeriver : null, variable: classname.tokens[tokenKey] !== classname.tokensWithoutVariables[tokenKey] ? { value: classname.tokens[tokenKey].value, originalValue: classname.tokensWithoutVariables[tokenKey].value, } : null, }, }; }, {} as IClasses); }; export const deepAssign = ( a: { [key: string]: { [key: string]: string } }, b: { [key: string]: { [key: string]: string } }, ) => { Object.keys(b).forEach(key => { if (!a[key]) { a[key] = {}; } Object.keys(b[key]).forEach(subKey => { a[key][subKey] = b[key][subKey]; }); }); return a; }; const getCategoryTokens = (config: IConfig, category: string): { [token: string]: IToken } => { const rawTokens = config.tokens && (config.tokens as any)[category] ? (config.tokens as any)[category] : config.tokens ? {} : (defaultTokens as any)[category]; return Object.keys(rawTokens).reduce<{ [token: string]: IToken }>((categoryTokens, tokenKey) => { categoryTokens[tokenKey] = typeof rawTokens[tokenKey] === 'string' ? { value: rawTokens[tokenKey], } : rawTokens[tokenKey]; return categoryTokens; }, {}); }; export const evaluateConfig = (config: IConfig): IEvaluatedConfig => { const originalTokens = Object.keys(defaultTokens).reduce<IGlobalTokens<IToken>>((currentTokens, category) => { (currentTokens as any)[category] = getCategoryTokens(config, category); return currentTokens; }, {} as IGlobalTokens<IToken>); // Reverse themes lookup to tokens instead const configThemes = config.themes || {}; const themesByTokens = Object.keys(configThemes).reduce((aggr, themeKey) => { Object.keys(configThemes[themeKey]).forEach(tokenKey => { if (!aggr[tokenKey]) { aggr[tokenKey] = {}; } Object.keys((configThemes[themeKey] as any)[tokenKey]).forEach(valueKey => { if (!aggr[tokenKey][valueKey]) { aggr[tokenKey][valueKey] = {}; } aggr[tokenKey][valueKey][themeKey] = (configThemes[themeKey] as any)[tokenKey][valueKey]; }); }); return aggr; }, {} as IEvaluatedThemes); // Evaluated variables where values are replaced by CSS variable const tokens = Object.keys(originalTokens).reduce<IGlobalTokens<IToken>>((currentTokens, categoryKey) => { (currentTokens as any)[categoryKey] = Object.keys((originalTokens as any)[categoryKey]).reduce<{ [token: string]: IToken; }>((categoryTokens, tokenKey) => { categoryTokens[tokenKey] = { ...(originalTokens as any)[categoryKey][tokenKey], value: themesByTokens[categoryKey] && themesByTokens[categoryKey][tokenKey] ? `var(--${categoryKey}-${tokenKey})` : (originalTokens as any)[categoryKey][tokenKey].value, }; return categoryTokens; }, {}); return currentTokens; }, {} as IGlobalTokens<IToken>); // Call any dynamic classname tokens with both the original variables and // the ones who have been evaluated with CSS variables const evaluatedClassnames = Object.keys(classnames).reduce((aggr, key) => { aggr[key] = { ...classnames[key], tokensWithoutVariables: typeof (classnames[key] as any).tokens === 'function' ? (classnames[key] as any).tokens(originalTokens, { negative }) : (classnames[key] as any).tokens, tokens: typeof (classnames[key] as any).tokens === 'function' ? (classnames[key] as any).tokens(tokens, { negative }) : (classnames[key] as any).tokens, description: (classnames[key] as any).description, } as any; return aggr; }, {} as IEvaluatedClassnames); return { tokens, screens: config.screens || defaultScreens, classnames: evaluatedClassnames, themes: themesByTokens, themeNames: Object.keys(config.themes || {}), }; }; export const getUserConfig = () => { try { const config = require(join(process.cwd(), 'classy-ui.config.js')); if (typeof config === 'function') { return config({ tokens: defaultTokens, screens: defaultScreens }); } else { return config; } } catch (error) { if (!error.toString().includes('Cannot find module')) { // tslint:disable-next-line throw error; } return {}; } }; export const getScreens = (config: IEvaluatedConfig) => { return Object.keys(config.tokens.breakpoints).reduce((breakAggr, key) => { breakAggr[key] = config.tokens.breakpoints[key].value; return breakAggr; }, {} as any); }; export const createProductionCss = (productionClassesByType: IClassesByType, config: IEvaluatedConfig) => { let css = ''; const variableKeys = Object.keys(productionClassesByType.rootTokens); if (variableKeys.length) { css += ':root{'; variableKeys.forEach(key => { css += `${key}:${productionClassesByType.rootTokens[key]};`; }); css += '}'; } Object.keys(productionClassesByType.themeTokens).forEach(theme => { const variables = Object.keys(productionClassesByType.themeTokens[theme]).reduce( (aggr, variableKey) => `${aggr}${productionClassesByType.themeTokens[theme][variableKey]}`, '', ); css += `.themes-${theme}{${variables}}`; }); css += Object.keys(productionClassesByType.common).reduce( (aggr, name) => aggr + productionClassesByType.common[name], '', ); // We end with media queries in order as they need to override everything else const screenKeys = Object.keys(config.screens).reverse(); screenKeys.forEach(screen => { if (productionClassesByType.screens[screen] && productionClassesByType.screens[screen].length) { const screenCss = productionClassesByType.screens[screen].reduce((aggr, classCss) => { return aggr + classCss; }, ''); css += config.screens[screen](screenCss, getScreens(config)); } }); return css; }; export const camelToDash = (str: string) => { return str .replace(/[\w]([A-Z])/g, m => { return `${m[0]}-${m[1]}`; }) .toLowerCase(); }; export const createClassEntry = (name: string, decorators: string[], css: (name: string) => string) => { const groupDecorators = decorators .filter(decorator => decorator.startsWith('group') && decorator !== 'group') .map(decorator => camelToDash(decorator.substr(5))); const pseudoDecorators = decorators .filter(decorator => allowedPseudoDecorators.includes(decorator)) .map(decorator => camelToDash(decorator)); const pseudoElementDecorators = decorators .filter(decorator => allowedPseudoElementDecorators.includes(decorator)) .map(decorator => camelToDash(decorator)); const evaluatedName = `.${name.replace(/\:/g, '\\:')}${ pseudoDecorators.length ? `:${pseudoDecorators.join(':')}` : '' }${pseudoElementDecorators.length ? `::${pseudoElementDecorators.join('::')}` : ''}`; return `${groupDecorators.length ? `.group:${groupDecorators.join(':')} ` : ''}${css(evaluatedName)}`; }; export const flat = (array: any[]) => array.reduce((aggr, item) => aggr.concat(item), []); export const injectProduction = ( productionClassesByType: IClassesByType, classCollection: IExtractedClasses, classes: IClasses, config: IEvaluatedConfig, ) => { Object.keys(classCollection).forEach(composition => { Object.keys(classCollection[composition]).forEach(id => { const extractedClass = classCollection[composition][id]; const evaluatedClass = classes[extractedClass.id as string]; const configClass = config.classnames[evaluatedClass.classname]; const classEntry = createClassEntry(extractedClass.name, extractedClass.decorators, evaluatedName => (configClass.css as any)(evaluatedName, configClass.tokens[evaluatedClass.token].value), ); if (composition in config.screens) { productionClassesByType.screens[extractedClass.composition] = productionClassesByType.screens[extractedClass.composition] || []; productionClassesByType.screens[extractedClass.composition].push(classEntry); } else { productionClassesByType.common[extractedClass.name] = classEntry; } if (evaluatedClass.variable) { const themes = config.themes || {}; const variableValue = evaluatedClass.variable.value; const originalValue = evaluatedClass.variable.originalValue; const variables = (variableValue.match(/var\(.*\)/) || []).map(varString => varString.replace(/var\(|\)/g, '')); config.themeNames.forEach(theme => { productionClassesByType.themeTokens[theme] = productionClassesByType.themeTokens[theme] || {}; variables.forEach(variable => { const variableParts = variable.substr(2).split('-'); const variableKey = variableParts.shift() as string; const variableValueKey = variableParts.join('-'); productionClassesByType.themeTokens[theme][ variable ] = `${variable}:${themes[variableKey][variableValueKey][theme]};`; productionClassesByType.rootTokens[variable] = originalValue; }); }); } }); }); return productionClassesByType; }; export const injectDevelopment = (classCollection: IExtractedClasses, classes: IClasses, config: IEvaluatedConfig) => { return Object.keys(classCollection).reduce((aggr, composition) => { return aggr.concat( Object.keys(classCollection[composition]).reduce((subAggr, id) => { const extractedClass = classCollection[composition][id]; const evaluatedClass = classes[extractedClass.id]; const configClass = config.classnames[evaluatedClass.classname]; const classEntry = createClassEntry(extractedClass.name, extractedClass.decorators, evaluatedName => (configClass.css as any)(evaluatedName, configClass.tokens[evaluatedClass.token].value), ); let css = ''; if (composition in config.screens) { css += config.screens[extractedClass.composition](classEntry, getScreens(config)); } else { css = classEntry; } if (evaluatedClass.variable) { const themes = config.themes || {}; const variableValue = evaluatedClass.variable.value; const originalValue = evaluatedClass.variable.originalValue; const variables = (variableValue.match(/var\(.*\)/) || []).map(varString => varString.replace(/var\(|\)/g, ''), ); variables.forEach(variable => { const variableParts = variable.substr(2).split('-'); const variableKey = variableParts.shift() as string; const variableValueKey = variableParts.join('-'); config.themeNames.forEach(theme => { css += `:root{${variable}:${originalValue};}\n.themes-${theme}{${variable}:${themes[variableKey][variableValueKey][theme]};}`; }); }); } return subAggr.concat([ extractedClass.name, css, // We reverse the keys so that the first key takes highest // presedence Object.keys(config.screens) .reverse() .indexOf(composition), ]); }, [] as Array<string | number>), ); }, [] as Array<string | number>); }; export const negative = (scale: { [key: string]: IToken }) => { return Object.keys(scale) .filter(key => scale[key].value !== '0') .reduce( (negativeScale, key) => ({ ...negativeScale, [`NEGATIVE_${key}`]: { ...scale[key], value: negateValue(scale[key].value), }, }), {}, ); }; export const negateValue = (value: string) => { try { return reduceCalc(`calc(${value} * -1)`); } catch (e) { return value; } }; export const createName = (decorators: string[], name: string) => { return [decorators.sort().join(':'), name] .filter(Boolean) .filter(i => i!.length > 0) .join(':'); }; export const createExtractedClasses = (extractedClasses: IExtractedClass[]) => { return extractedClasses.reduce<IExtractedClasses>((aggr, extractedClass) => { if (!aggr[extractedClass.composition]) { aggr[extractedClass.composition] = {}; } aggr[extractedClass.composition][extractedClass.id] = extractedClass; return aggr; }, {}); }; export const createProductionClassObjects = ( { composition, baseClass, token, decorators, }: { composition: string; baseClass: string; token: string; decorators: string[]; }, classes: IClasses, evaluatedProductionShortnames: { classnames: string[]; tokens: string[]; decorators: string[]; }, ) => { const id = `${camelToDash(baseClass)}-${token}`; if (id && !(id in classes)) { throw new Error(`The token "${token}" does not exist on property "${baseClass}"`); } if (classes[id].derived) { return classes[id].derived!.reduce((aggr, key) => { const derivedShortClassname = generateCharsFromNumber( evaluatedProductionShortnames.classnames.indexOf(key) === -1 ? evaluatedProductionShortnames.classnames.push(key) : evaluatedProductionShortnames.classnames.indexOf(key) + 1, ); const derivedShortToken = generateCharsFromNumber( evaluatedProductionShortnames.tokens.indexOf(token) === -1 ? evaluatedProductionShortnames.tokens.push(token) : evaluatedProductionShortnames.tokens.indexOf(token) + 1, ); const derivedShortDecorators = decorators .concat(composition === 'compose' ? [] : composition) .sort() .map(decorator => generateCharsFromNumber( evaluatedProductionShortnames.decorators.indexOf(decorator) === -1 ? evaluatedProductionShortnames.decorators.push(decorator) : evaluatedProductionShortnames.decorators.indexOf(decorator) + 1, ), ) .join(''); return aggr.concat({ id: `${camelToDash(key)}-${token}`, name: `${ derivedShortDecorators.length ? `${derivedShortDecorators}-` : '' }${derivedShortClassname}_${derivedShortToken}`, decorators, composition, }); }, [] as IExtractedClass[]); } const shortClassname = generateCharsFromNumber( evaluatedProductionShortnames.classnames.indexOf(baseClass) === -1 ? evaluatedProductionShortnames.classnames.push(baseClass) : evaluatedProductionShortnames.classnames.indexOf(baseClass) + 1, ); const shortToken = generateCharsFromNumber( evaluatedProductionShortnames.tokens.indexOf(token) === -1 ? evaluatedProductionShortnames.tokens.push(token) : evaluatedProductionShortnames.tokens.indexOf(token) + 1, ); const shortDecorators = decorators .concat(composition === 'compose' ? [] : composition) .sort() .map(decorator => generateCharsFromNumber( evaluatedProductionShortnames.decorators.indexOf(decorator) === -1 ? evaluatedProductionShortnames.decorators.push(decorator) : evaluatedProductionShortnames.decorators.indexOf(decorator) + 1, ), ) .join(''); return [ { id, name: `${shortDecorators.length ? `${shortDecorators}-` : ''}${shortClassname}_${shortToken}`, decorators, composition, }, ]; }; export const createClassObjects = ( { composition, baseClass, token, decorators, }: { composition: string; baseClass: string; token: string; decorators: string[] }, classes: IClasses, ): IExtractedClass[] => { const id = `${camelToDash(baseClass)}-${token}`; if (id && !(id in classes)) { throw new Error(`The token ${token} does not exist on property ${baseClass}`); } if (classes[id].derived) { return classes[id].derived!.reduce((aggr, key) => { return aggr.concat({ id: `${camelToDash(key)}-${token}`, name: createName( decorators.concat(composition === 'compose' ? [] : composition), `${camelToDash(key)}__${token}`, ), decorators, composition, }); }, [] as IExtractedClass[]); } return [ { id, name: createName( decorators.concat(composition === 'compose' ? [] : composition), `${camelToDash(baseClass)}__${token}`, ), decorators, composition, }, ]; }; export const generateCharsFromNumber = (num: number) => { const baseChar = 'A'.charCodeAt(0); let letters = ''; do { num -= 1; letters = String.fromCharCode(baseChar + (num % 26)) + letters; num = (num / 26) >> 0; } while (num > 0); return letters; }; export const hyphenToCamelCase = (str: string) => str.replace(/-([a-z])/g, g => { return g[1].toUpperCase(); });
the_stack
import { IEventDispatcher } from "../../events/api/IEventDispatcher"; import { ILifecycle } from "../api/ILifecycle"; import { LifecycleError } from "../api/LifecycleError"; import { LifecycleEvent } from "../api/LifecycleEvent"; import { LifecycleState } from "../api/LifecycleState"; import { LifecycleTransition } from "./LifecycleTransition"; /*[Event(name="destroy", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="error", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="initialize", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="postDestroy", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="postInitialize", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="postResume", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="postSuspend", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="preDestroy", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="preInitialize", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="preResume", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="preSuspend", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="resume", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="stateChange", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /*[Event(name="suspend", type="robotlegs.bender.framework.api.LifecycleEvent")]*/ /** * Default object lifecycle * * @private */ export class Lifecycle implements ILifecycle { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ private _state: string = LifecycleState.UNINITIALIZED; /** * @inheritDoc */ public get state(): string { return this._state; } private _target: IEventDispatcher; /** * @inheritDoc */ public get target(): IEventDispatcher { return this._target; } /** * @inheritDoc */ public get uninitialized(): boolean { return this._state === LifecycleState.UNINITIALIZED; } /** * @inheritDoc */ public get initialized(): boolean { return this._state !== LifecycleState.UNINITIALIZED && this._state !== LifecycleState.INITIALIZING; } /** * @inheritDoc */ public get active(): boolean { return this._state === LifecycleState.ACTIVE; } /** * @inheritDoc */ public get suspended(): boolean { return this._state === LifecycleState.SUSPENDED; } /** * @inheritDoc */ public get destroyed(): boolean { return this._state === LifecycleState.DESTROYED; } /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private _reversedEventTypes: Map<any, boolean> = new Map<any, boolean>(); private _reversePriority: number = 0; private _initialize: LifecycleTransition; private _suspend: LifecycleTransition; private _resume: LifecycleTransition; private _destroy: LifecycleTransition; private _dispatcher: IEventDispatcher; /*============================================================================*/ /* Constructor */ /*============================================================================*/ /** * Creates a lifecycle for a given target object * @param target The target object */ constructor(target: IEventDispatcher) { this._target = target; this._dispatcher = target; // || new EventDispatcher(this); this.configureTransitions(); } /*============================================================================*/ /* Public Functions */ /*============================================================================*/ /** * @inheritDoc */ public initialize(callback?: Function): void { this._initialize.enter(callback); } /** * @inheritDoc */ public suspend(callback?: Function): void { this._suspend.enter(callback); } /** * @inheritDoc */ public resume(callback?: Function): void { this._resume.enter(callback); } /** * @inheritDoc */ public destroy(callback?: Function): void { this._destroy.enter(callback); } /** * @inheritDoc */ public beforeInitializing(handler: Function): ILifecycle { if (!this.uninitialized) { this.reportError(LifecycleError.LATE_HANDLER_ERROR_MESSAGE); } this._initialize.addBeforeHandler(handler); return this; } /** * @inheritDoc */ public whenInitializing(handler: Function): ILifecycle { if (this.initialized) { this.reportError(LifecycleError.LATE_HANDLER_ERROR_MESSAGE); } this.addEventListener(LifecycleEvent.INITIALIZE, this.createSyncLifecycleListener(handler, true)); return this; } /** * @inheritDoc */ public afterInitializing(handler: Function): ILifecycle { if (this.initialized) { this.reportError(LifecycleError.LATE_HANDLER_ERROR_MESSAGE); } this.addEventListener(LifecycleEvent.POST_INITIALIZE, this.createSyncLifecycleListener(handler, true)); return this; } /** * @inheritDoc */ public beforeSuspending(handler: Function): ILifecycle { this._suspend.addBeforeHandler(handler); return this; } /** * @inheritDoc */ public whenSuspending(handler: Function): ILifecycle { this.addEventListener(LifecycleEvent.SUSPEND, this.createSyncLifecycleListener(handler)); return this; } /** * @inheritDoc */ public afterSuspending(handler: Function): ILifecycle { this.addEventListener(LifecycleEvent.POST_SUSPEND, this.createSyncLifecycleListener(handler)); return this; } /** * @inheritDoc */ public beforeResuming(handler: Function): ILifecycle { this._resume.addBeforeHandler(handler); return this; } /** * @inheritDoc */ public whenResuming(handler: Function): ILifecycle { this.addEventListener(LifecycleEvent.RESUME, this.createSyncLifecycleListener(handler)); return this; } /** * @inheritDoc */ public afterResuming(handler: Function): ILifecycle { this.addEventListener(LifecycleEvent.POST_RESUME, this.createSyncLifecycleListener(handler)); return this; } /** * @inheritDoc */ public beforeDestroying(handler: Function): ILifecycle { this._destroy.addBeforeHandler(handler); return this; } /** * @inheritDoc */ public whenDestroying(handler: Function): ILifecycle { this.addEventListener(LifecycleEvent.DESTROY, this.createSyncLifecycleListener(handler, true)); return this; } /** * @inheritDoc */ public afterDestroying(handler: Function): ILifecycle { this.addEventListener(LifecycleEvent.POST_DESTROY, this.createSyncLifecycleListener(handler, true)); return this; } /** * @inheritDoc */ public addEventListener( type: string, listener: Function, useCapture: boolean = false, priority: number = 0, useWeakReference: boolean = false ): void { priority = this.flipPriority(type, priority); // this._dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); this._dispatcher.addEventListener(type, listener, undefined, useCapture, priority); } /** * @inheritDoc */ public removeEventListener(type: string, listener: Function, useCapture: boolean = false): void { this._dispatcher.removeEventListener(type, listener); } /** * @inheritDoc */ public dispatchEvent(event: any): boolean { return this._dispatcher.dispatchEvent(event); } /** * @inheritDoc */ public hasEventListener(type: string): boolean { return this._dispatcher.hasEventListener(type); } /** * @inheritDoc */ public willTrigger(type: string): boolean { return this._dispatcher.willTrigger(type); } /*============================================================================*/ /* Internal Functions */ /*============================================================================*/ public setCurrentState(state: string): void { if (this._state !== state) { this._state = state; this.dispatchEvent(new LifecycleEvent(LifecycleEvent.STATE_CHANGE)); } } public addReversedEventTypes(...types: any[]): void { types.forEach((type: any) => { this._reversedEventTypes.set(type, true); }); } /*============================================================================*/ /* Private Functions */ /*============================================================================*/ private configureTransitions(): void { this._initialize = new LifecycleTransition(LifecycleEvent.PRE_INITIALIZE, this) .fromStates(LifecycleState.UNINITIALIZED) .toStates(LifecycleState.INITIALIZING, LifecycleState.ACTIVE) .withEvents(LifecycleEvent.PRE_INITIALIZE, LifecycleEvent.INITIALIZE, LifecycleEvent.POST_INITIALIZE); this._suspend = new LifecycleTransition(LifecycleEvent.PRE_SUSPEND, this) .fromStates(LifecycleState.ACTIVE) .toStates(LifecycleState.SUSPENDING, LifecycleState.SUSPENDED) .withEvents(LifecycleEvent.PRE_SUSPEND, LifecycleEvent.SUSPEND, LifecycleEvent.POST_SUSPEND) .inReverse(); this._resume = new LifecycleTransition(LifecycleEvent.PRE_RESUME, this) .fromStates(LifecycleState.SUSPENDED) .toStates(LifecycleState.RESUMING, LifecycleState.ACTIVE) .withEvents(LifecycleEvent.PRE_RESUME, LifecycleEvent.RESUME, LifecycleEvent.POST_RESUME); this._destroy = new LifecycleTransition(LifecycleEvent.PRE_DESTROY, this) .fromStates(LifecycleState.SUSPENDED, LifecycleState.ACTIVE) .toStates(LifecycleState.DESTROYING, LifecycleState.DESTROYED) .withEvents(LifecycleEvent.PRE_DESTROY, LifecycleEvent.DESTROY, LifecycleEvent.POST_DESTROY) .inReverse(); } private flipPriority(type: string, priority: number): number { return priority === 0 && this._reversedEventTypes.get(type) ? this._reversePriority++ : priority; } private createSyncLifecycleListener(handler: Function, once: boolean = false): Function { // When and After handlers can not be asynchronous if (handler.length > 1) { throw new LifecycleError(LifecycleError.SYNC_HANDLER_ARG_MISMATCH); } // A handler that accepts 1 argument is provided with the event type if (handler.length === 1) { return function(event: LifecycleEvent): void { if (once) { // (<IEventDispatcher>event.target).removeEventListener(event.type, arguments.callee); (<IEventDispatcher>event.target).removeEventListener(event.type, handler); } handler(event.type); }; } // Or, just call the handler return function(event: LifecycleEvent): void { if (once) { // (<IEventDispatcher>event.target).removeEventListener(event.type, arguments.callee); (<IEventDispatcher>event.target).removeEventListener(event.type, handler); } handler(); }; } private reportError(message: string): void { let error: LifecycleError = new LifecycleError(message); if (this.hasEventListener(LifecycleEvent.ERROR)) { let event: LifecycleEvent = new LifecycleEvent(LifecycleEvent.ERROR, error); this.dispatchEvent(event); } else { throw error; } } }
the_stack
import * as _ from 'lodash'; import { escapeRegExp } from 'lodash'; import {} from 'vscode'; import { Position, Range, Selection } from 'vscode'; import { sorted } from '../../common/motion/position'; import { configuration } from '../../configuration/configuration'; import { VimError, ErrorCode } from '../../error'; import { Mode } from '../../mode/mode'; import { Register } from '../../register/register'; import { globalState } from '../../state/globalState'; import { SearchState } from '../../state/searchState'; import { VimState } from '../../state/vimState'; import { StatusBar } from '../../statusBar'; import { TextEditor } from '../../textEditor'; import { TextObject } from '../../textobject/textobject'; import { reportSearch } from '../../util/statusBarTextUtils'; import { SearchDirection } from '../../vimscript/pattern'; import { RegisterAction, BaseCommand } from '../base'; import { failedMovement, IMovement } from '../baseMotion'; /** * Search for the word under the cursor; used by [g]* and [g]# */ async function searchCurrentWord( position: Position, vimState: VimState, direction: SearchDirection, isExact: boolean ): Promise<void> { let currentWord = TextEditor.getWord(vimState.document, position); if (currentWord) { if (/\W/.test(currentWord[0]) || /\W/.test(currentWord[currentWord.length - 1])) { // TODO: this kind of sucks. JS regex does not consider the boundary between a special // character and whitespace to be a "word boundary", so we can't easily do an exact search. isExact = false; } if (isExact) { currentWord = _.escapeRegExp(currentWord); } // If the search is going left then use `getWordLeft()` on position to start // at the beginning of the word. This ensures that any matches happen // outside of the currently selected word. const searchStartCursorPosition = direction === SearchDirection.Backward ? vimState.cursorStopPosition.prevWordStart(vimState.document, { inclusive: true }) : vimState.cursorStopPosition; await createSearchStateAndMoveToMatch({ needle: currentWord, vimState, direction, isExact, searchStartCursorPosition, }); } else { StatusBar.displayError(vimState, VimError.fromCode(ErrorCode.NoStringUnderCursor)); } } /** * Search for the word under the cursor; used by [g]* and [g]# in visual mode when `visualstar` is enabled */ async function searchCurrentSelection(vimState: VimState, direction: SearchDirection) { const currentSelection = vimState.document.getText(vimState.editor.selection); // Go back to Normal mode, otherwise the selection grows to the next match. await vimState.setCurrentMode(Mode.Normal); const [start, end] = sorted(vimState.cursorStartPosition, vimState.cursorStopPosition); // Ensure that any matches happen outside of the currently selected word. const searchStartCursorPosition = direction === SearchDirection.Backward ? start.getLeft() : end.getRight(); await createSearchStateAndMoveToMatch({ needle: currentSelection, vimState, direction, isExact: false, searchStartCursorPosition, }); } /** * Used by [g]* and [g]# */ async function createSearchStateAndMoveToMatch(args: { needle: string; vimState: VimState; direction: SearchDirection; isExact: boolean; searchStartCursorPosition: Position; }): Promise<void> { const { needle, vimState, isExact } = args; if (needle.length === 0) { return; } const searchString = isExact ? `\\<${escapeRegExp(needle)}\\>` : escapeRegExp(needle); // Start a search for the given term. globalState.searchState = new SearchState( args.direction, vimState.cursorStopPosition, searchString, { ignoreSmartcase: true }, vimState.currentMode ); Register.setReadonlyRegister('/', globalState.searchState.searchString); globalState.addSearchStateToHistory(globalState.searchState); // Turn one of the highlighting flags back on (turned off with :nohl) globalState.hl = true; const nextMatch = globalState.searchState.getNextSearchMatchPosition( vimState.editor, args.searchStartCursorPosition ); if (nextMatch) { vimState.cursorStopPosition = nextMatch.pos; reportSearch( nextMatch.index, globalState.searchState.getMatchRanges(vimState.editor).length, vimState ); } else { StatusBar.displayError( vimState, VimError.fromCode( args.direction === SearchDirection.Forward ? ErrorCode.SearchHitBottom : ErrorCode.SearchHitTop, globalState.searchState.searchString ) ); } } @RegisterAction class CommandSearchCurrentWordExactForward extends BaseCommand { modes = [Mode.Normal]; keys = ['*']; override isMotion = true; override runsOnceForEachCountPrefix = true; override isJump = true; public override async exec(position: Position, vimState: VimState): Promise<void> { await searchCurrentWord(position, vimState, SearchDirection.Forward, true); } } @RegisterAction class CommandSearchCurrentWordForward extends BaseCommand { modes = [Mode.Normal, Mode.Visual, Mode.VisualLine]; keys = ['g', '*']; override isMotion = true; override runsOnceForEachCountPrefix = true; override isJump = true; public override async exec(position: Position, vimState: VimState): Promise<void> { await searchCurrentWord(position, vimState, SearchDirection.Forward, false); } } @RegisterAction class CommandSearchVisualForward extends BaseCommand { modes = [Mode.Visual, Mode.VisualLine]; keys = ['*']; override isMotion = true; override runsOnceForEachCountPrefix = true; override isJump = true; public override async exec(position: Position, vimState: VimState): Promise<void> { if (configuration.visualstar) { await searchCurrentSelection(vimState, SearchDirection.Forward); } else { await searchCurrentWord(position, vimState, SearchDirection.Forward, true); } } } @RegisterAction class CommandSearchCurrentWordExactBackward extends BaseCommand { modes = [Mode.Normal]; keys = ['#']; override isMotion = true; override runsOnceForEachCountPrefix = true; override isJump = true; public override async exec(position: Position, vimState: VimState): Promise<void> { await searchCurrentWord(position, vimState, SearchDirection.Backward, true); } } @RegisterAction class CommandSearchCurrentWordBackward extends BaseCommand { modes = [Mode.Normal, Mode.Visual, Mode.VisualLine]; keys = ['g', '#']; override isMotion = true; override runsOnceForEachCountPrefix = true; override isJump = true; public override async exec(position: Position, vimState: VimState): Promise<void> { await searchCurrentWord(position, vimState, SearchDirection.Backward, false); } } @RegisterAction class CommandSearchVisualBackward extends BaseCommand { modes = [Mode.Visual, Mode.VisualLine]; keys = ['#']; override isMotion = true; override runsOnceForEachCountPrefix = true; override isJump = true; public override async exec(position: Position, vimState: VimState): Promise<void> { if (configuration.visualstar) { await searchCurrentSelection(vimState, SearchDirection.Backward); } else { await searchCurrentWord(position, vimState, SearchDirection.Backward, true); } } } @RegisterAction class CommandSearchForwards extends BaseCommand { modes = [Mode.Normal, Mode.Visual, Mode.VisualLine, Mode.VisualBlock]; keys = ['/']; override isMotion = true; override isJump = true; override runsOnceForEveryCursor() { return false; } public override async exec(position: Position, vimState: VimState): Promise<void> { globalState.searchState = new SearchState( SearchDirection.Forward, vimState.cursorStopPosition, '', {}, vimState.currentMode ); await vimState.setCurrentMode(Mode.SearchInProgressMode); // Reset search history index globalState.searchStateIndex = globalState.searchStatePrevious.length; } } @RegisterAction class CommandSearchBackwards extends BaseCommand { modes = [Mode.Normal, Mode.Visual, Mode.VisualLine, Mode.VisualBlock]; keys = ['?']; override isMotion = true; override isJump = true; override runsOnceForEveryCursor() { return false; } public override async exec(position: Position, vimState: VimState): Promise<void> { globalState.searchState = new SearchState( SearchDirection.Backward, vimState.cursorStopPosition, '', {}, vimState.currentMode ); await vimState.setCurrentMode(Mode.SearchInProgressMode); // Reset search history index globalState.searchStateIndex = globalState.searchStatePrevious.length; } } abstract class SearchObject extends TextObject { override modes = [Mode.Normal, Mode.Visual, Mode.VisualBlock]; protected abstract readonly direction: SearchDirection; public async execAction(position: Position, vimState: VimState): Promise<IMovement> { const searchState = globalState.searchState; if (!searchState || searchState.searchString === '') { return failedMovement(vimState); } const newSearchState = new SearchState( this.direction, vimState.cursorStopPosition, searchState.searchString, {}, vimState.currentMode ); let result: | { range: Range; index: number; } | undefined; // At first, try to search for current word, and stop searching if matched. // Try to search for the next word if not matched or // if the cursor is at the end of a match string in visual-mode. result = newSearchState.findContainingMatchRange(vimState.editor, vimState.cursorStopPosition); if ( result && vimState.currentMode === Mode.Visual && vimState.cursorStopPosition.isEqual(result.range.end.getLeftThroughLineBreaks()) ) { result = undefined; } if (result === undefined) { // Try to search for the next word result = newSearchState.getNextSearchMatchRange(vimState.editor, vimState.cursorStopPosition); if (result === undefined) { return failedMovement(vimState); } } reportSearch(result.index, searchState.getMatchRanges(vimState.editor).length, vimState); let [start, stop] = [ vimState.currentMode === Mode.Normal ? result.range.start : vimState.cursorStopPosition, result.range.end.getLeftThroughLineBreaks(), ]; if (vimState.recordedState.operator) { stop = stop.getLeft(); } // Move the cursor, this is a bit hacky... vimState.cursorStartPosition = start; vimState.cursorStopPosition = stop; vimState.editor.selection = new Selection(start, stop); await vimState.setCurrentMode(Mode.Visual); return { start, stop, }; } } @RegisterAction class SearchObjectForward extends SearchObject { keys = ['g', 'n']; direction = SearchDirection.Forward; } @RegisterAction class SearchObjectBackward extends SearchObject { keys = ['g', 'N']; direction = SearchDirection.Backward; }
the_stack
import { DebugElement } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { SearchResult } from 'app/search/interfaces'; import { SearchResultsComponent } from './search-results.component'; describe('SearchResultsComponent', () => { let component: SearchResultsComponent; let fixture: ComponentFixture<SearchResultsComponent>; let guideA: SearchResult; let apiD: SearchResult; let guideB: SearchResult; let guideAC: SearchResult; let apiC: SearchResult; let guideN: SearchResult; let guideM: SearchResult; let guideL: SearchResult; let guideK: SearchResult; let guideJ: SearchResult; let guideI: SearchResult; let guideH: SearchResult; let guideG: SearchResult; let guideF: SearchResult; let guideE: SearchResult; let standardResults: SearchResult[]; /** Get all text from component element. */ function getText() { return fixture.debugElement.nativeElement.textContent; } /** Pass the given search results to the component and trigger change detection. */ function setSearchResults(query: string, results: SearchResult[]) { component.searchResults = {query, results}; component.ngOnChanges(); fixture.detectChanges(); } /** Get a full set of test results. "Take" what you need */ beforeEach(() => { /* eslint-disable max-len */ apiD = { path: 'api/d', title: 'API D', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; apiC = { path: 'api/c', title: 'API C', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideA = { path: 'guide/a', title: 'Guide A', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideB = { path: 'guide/b', title: 'Guide B', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideAC = { path: 'guide/a/c', title: 'Guide A - C', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideE = { path: 'guide/e', title: 'Guide e', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideF = { path: 'guide/f', title: 'Guide f', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideG = { path: 'guide/g', title: 'Guide g', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideH = { path: 'guide/h', title: 'Guide h', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideI = { path: 'guide/i', title: 'Guide i', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideJ = { path: 'guide/j', title: 'Guide j', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideK = { path: 'guide/k', title: 'Guide k', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideL = { path: 'guide/l', title: 'Guide l', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideM = { path: 'guide/m', title: 'Guide m', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; guideN = { path: 'guide/n', title: 'Guide n', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' }; /* eslint-enable max-len */ standardResults = [ guideA, apiD, guideB, guideAC, apiC, guideN, guideM, guideL, guideK, guideJ, guideI, guideH, guideG, guideF, guideE, ]; }); beforeEach(() => { TestBed.configureTestingModule({ declarations: [ SearchResultsComponent ] }); }); beforeEach(() => { fixture = TestBed.createComponent(SearchResultsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should map the search results into groups based on their containing folder', () => { const startA = { path: 'start/a', title: 'Start A', deprecated: false, keywords: '', titleWords: '', type: '', topics: '', }; const tutorialA = { path: 'tutorial/a', title: 'Tutorial A', deprecated: false, keywords: '', titleWords: '', type: '', topics: '', }; setSearchResults('', [guideA, apiD, guideB, startA, tutorialA]); expect(component.searchAreas).toEqual([ { name: 'api', priorityPages: [apiD], pages: [] }, { name: 'guides', priorityPages: [guideA, guideB], pages: [] }, { name: 'tutorials', priorityPages: [startA, tutorialA], pages: [] }, ]); }); it('should special case results that are top level folders', () => { setSearchResults('', [ { path: 'docs', title: 'Docs introduction', type: '', keywords: '', titleWords: '', deprecated: false, topics: '', }, { path: 'start', title: 'Getting started', type: '', keywords: '', titleWords: '', deprecated: false, topics: '', }, { path: 'tutorial', title: 'Tutorial index', type: '', keywords: '', titleWords: '', deprecated: false, topics: '', }, { path: 'tutorial/toh-pt1', title: 'Tutorial - part 1', type: '', keywords: '', titleWords: '', deprecated: false, topics: '', }, ]); expect(component.searchAreas).toEqual([ { name: 'guides', priorityPages: [ { path: 'docs', title: 'Docs introduction', type: '', keywords: '', titleWords: '', deprecated: false, topics: '', }, ], pages: [], }, { name: 'tutorials', priorityPages: [ { path: 'start', title: 'Getting started', type: '', keywords: '', titleWords: '', deprecated: false, topics: '', }, { path: 'tutorial', title: 'Tutorial index', type: '', keywords: '', titleWords: '', deprecated: false, topics: '', }, { path: 'tutorial/toh-pt1', title: 'Tutorial - part 1', type: '', keywords: '', titleWords: '', deprecated: false, topics: '', }, ], pages: [], }, ]); }); it('should put, at most, the first 5 results for each area into priorityPages, not sorted', () => { setSearchResults('', standardResults); expect(component.searchAreas[0].priorityPages).toEqual([apiD, apiC]); expect(component.searchAreas[1].priorityPages).toEqual([guideA, guideB, guideAC, guideN, guideM]); }); it('should put the nonPriorityPages into the pages array, sorted by title', () => { setSearchResults('', standardResults); expect(component.searchAreas[0].pages).toEqual([]); expect(component.searchAreas[1].pages).toEqual([ guideE, guideF, guideG, guideH, guideI, guideJ, guideK, guideL ]); }); it('should put a total count in the header of each area of search results', () => { setSearchResults('', standardResults); fixture.detectChanges(); const headers = fixture.debugElement.queryAll(By.css('h3')); expect(headers.length).toEqual(2); expect(headers[0].nativeElement.textContent).toContain('(2)'); expect(headers[1].nativeElement.textContent).toContain('(13)'); }); it('should put search results with no containing folder into the default area (other)', () => { const results = [ { path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' } ]; setSearchResults('', results); expect(component.searchAreas).toEqual([ { name: 'other', priorityPages: [ { path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' } ], pages: [] } ]); }); it('should omit search results with no title', () => { const results = [ { path: 'news', title: '', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' } ]; setSearchResults('something', results); expect(component.searchAreas).toEqual([]); }); describe('when there are deprecated items', () => { beforeEach(() => { apiD.deprecated = true; guideAC.deprecated = true; guideJ.deprecated = true; guideE.deprecated = true; setSearchResults('something', standardResults); }); // eslint-disable-next-line max-len it('should include deprecated items in priority pages unless there are fewer than 5 non-deprecated priority pages', () => { // Priority pages do not include deprecated items: expect(component.searchAreas[1].priorityPages).not.toContain(guideAC); expect(component.searchAreas[1].priorityPages).not.toContain(guideJ); // Except where there are too few priority pages: expect(component.searchAreas[0].priorityPages).toContain(apiD); }); it('should move the non-priority deprecated pages to the bottom of the pages list, unsorted', () => { // Bottom pages are the deprecated ones (in original order) expect(component.searchAreas[1].pages.slice(-3)).toEqual([guideAC, guideJ, guideE]); }); it('should sort the non-deprecated, non-priority pages by title', () => { // The rest of the pages are non-deprecated, sorted by title expect(component.searchAreas[1].pages.slice(0, -3)).toEqual([ guideF, guideG, guideH, guideI, guideK, ]); }); }); it('should display "Searching ..." while waiting for search results', () => { fixture.detectChanges(); expect(getText()).toContain('Searching ...'); }); it('should not display default links while searching', () => { fixture.detectChanges(); const resultLinks = fixture.debugElement.queryAll(By.css('.search-page a')); expect(resultLinks.length).toEqual(0); }); describe('when a search result anchor is clicked', () => { let searchResult: SearchResult; let selected: SearchResult|null; let anchor: DebugElement; beforeEach(() => { component.resultSelected.subscribe((result: SearchResult) => selected = result); selected = null; searchResult = { path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '', }; setSearchResults('something', [searchResult]); fixture.detectChanges(); anchor = fixture.debugElement.query(By.css('a')); expect(selected).toBeNull(); }); it('should emit a "resultSelected" event', () => { anchor.triggerEventHandler('click', {button: 0, ctrlKey: false, metaKey: false}); fixture.detectChanges(); expect(selected).toBe(searchResult); }); it('should not emit an event if mouse button is not zero (middle or right)', () => { anchor.triggerEventHandler('click', {button: 1, ctrlKey: false, metaKey: false}); fixture.detectChanges(); expect(selected).toBeNull(); }); it('should not emit an event if the `ctrl` key is pressed', () => { anchor.triggerEventHandler('click', {button: 0, ctrlKey: true, metaKey: false}); fixture.detectChanges(); expect(selected).toBeNull(); }); it('should not emit an event if the `meta` key is pressed', () => { anchor.triggerEventHandler('click', {button: 0, ctrlKey: false, metaKey: true}); fixture.detectChanges(); expect(selected).toBeNull(); }); }); describe('when no query results', () => { beforeEach(() => { setSearchResults('something', []); }); it('should display "not found" message', () => { expect(getText()).toContain('No results'); }); it('should contain reference links', () => { const resultLinks = fixture.debugElement.queryAll(By.css('.search-page a')); const resultHrefs = resultLinks.map(a => a.nativeNode.getAttribute('href')); expect(resultHrefs.length).toEqual(5); expect(resultHrefs).toEqual([ 'api', 'resources', 'guide/glossary', 'guide/cheatsheet', 'https://blog.angular.io/', ]); }); }); });
the_stack
import { getScope } from "@core/lib/blob"; import { getFetchActionBackgroundLogTargetIdsFn } from "./../models/logs"; import produce from "immer"; import { v4 as uuid } from "uuid"; import { apiAction } from "../handler"; import { Api, Blob, Model, Auth, Client, Rbac } from "@core/types"; import * as R from "ramda"; import { getFetchActionLogTargetIdsFn } from "../models/logs"; import { getEnvironmentsByEnvParentId, getEnvironmentPermissions, getConnectedBlocksForApp, deleteGraphObjects, authz, getDeleteEnvironmentProducer, environmentCompositeId, getConnectedActiveGeneratedEnvkeys, getAllConnectedKeyableParents, getActiveGeneratedEnvkeysByKeyableParentId, getConnectedBlockEnvironmentsForApp, } from "@core/lib/graph"; import { pick } from "@core/lib/utils/pick"; import * as graphKey from "../graph_key"; import { log } from "@core/lib/utils/logger"; import { setEnvsUpdatedFields } from "../graph"; apiAction< Api.Action.RequestActions["UpdateEnvs"], Api.Net.ApiResultTypes["UpdateEnvs"] >({ type: Api.ActionType.UPDATE_ENVS, graphAction: true, authenticated: true, // no graphAuthorizer needed here since blob updates are authorized at the handler level graphHandler: async ({ payload }, orgGraph, auth, now) => { const { updatedGraph, updatingEnvironmentIds } = setEnvsUpdatedFields( auth, orgGraph, payload.blobs, now ); const hardDeleteSecondaryIndices: string[] = []; const hardDeleteTertiaryIndices: string[] = []; // for any base environment we're updating, clear out any inheritance overrides // set for it on sibling environments that are not included in the update for (let environmentId of updatingEnvironmentIds) { const environment = orgGraph[environmentId] as Model.Environment; if (environment.isSub) { continue; } const envParent = orgGraph[environment.envParentId] as Model.EnvParent, envParentEnvironments = getEnvironmentsByEnvParentId(orgGraph)[environment.envParentId] ?? []; for (let envParentEnvironment of envParentEnvironments) { if (envParentEnvironment.id == environment.id) { continue; } if ( R.path( [ envParent.id, "environments", envParentEnvironment.id, "inheritanceOverrides", environment.id, ], payload.blobs ) ) { continue; } // inheritance overrides encrypted blobs const index = `inheritanceOverrides|${envParent.id}|${environment.id}`; hardDeleteSecondaryIndices.push(index); if (envParent.type == "block") { hardDeleteTertiaryIndices.push(index); } } } const logTargetIds = new Set<string>(); const updatedGeneratedEnvkeyIds = new Set<string>(); for (let envParentId in payload.blobs) { logTargetIds.add(envParentId); const { environments, locals } = payload.blobs[envParentId]; if (environments) { for (let environmentId in environments) { const environment = orgGraph[environmentId] as Model.Environment; logTargetIds.add(environment.environmentRoleId); if (environment.isSub) { logTargetIds.add(environmentCompositeId(environment)); } const connectedGeneratedEnvkeys = getConnectedActiveGeneratedEnvkeys( orgGraph, environmentId ); for (let { id } of connectedGeneratedEnvkeys) { updatedGeneratedEnvkeyIds.add(id); } const update = environments[environmentId]; if (update.inheritanceOverrides) { for (let overrideEnvironmentId in update.inheritanceOverrides) { const overrideConnectedGeneratedEnvkeys = getConnectedActiveGeneratedEnvkeys( orgGraph, overrideEnvironmentId ); for (let { id } of overrideConnectedGeneratedEnvkeys) { updatedGeneratedEnvkeyIds.add(id); } } } } } if (locals) { const localsEnvironment = ( getEnvironmentsByEnvParentId(orgGraph)[envParentId] ?? [] ).find( ({ environmentRoleId }) => (orgGraph[environmentRoleId] as Rbac.EnvironmentRole).hasLocalKeys ); for (let localsUserId in locals) { logTargetIds.add("locals"); logTargetIds.add(localsUserId); if (localsEnvironment) { for (let keyableParent of getAllConnectedKeyableParents( orgGraph, localsEnvironment.id )) { if ( keyableParent.type == "localKey" && keyableParent.userId == localsUserId ) { const generatedEnvkey = getActiveGeneratedEnvkeysByKeyableParentId(orgGraph)[ keyableParent.id ]; if (generatedEnvkey) { updatedGeneratedEnvkeyIds.add(generatedEnvkey.id); } } } } } } } return { type: "graphHandlerResult", graph: updatedGraph, transactionItems: { hardDeleteSecondaryIndices, hardDeleteTertiaryIndices, }, logTargetIds: Array.from(logTargetIds), updatedGeneratedEnvkeyIds: Array.from(updatedGeneratedEnvkeyIds), }; }, }); apiAction< Api.Action.RequestActions["FetchEnvs"], Api.Net.ApiResultTypes["FetchEnvs"] >({ type: Api.ActionType.FETCH_ENVS, graphAction: true, authenticated: true, graphScopes: [ (auth, { payload: { byEnvParentId } }) => () => [ auth.user.skey + "$", "g|block|", "g|environment|", "g|group|", "g|groupMembership|", "g|appGroupBlockGroup|", "g|appGroupBlock|", "g|appGroupUserGroup|", "g|appGroupUser|", ...Object.keys(byEnvParentId).flatMap((envParentId) => [ graphKey.app(auth.org.id, envParentId).skey + "$", `g|appBlock|${envParentId}`, `g|appBlockGroup|${envParentId}`, `g|appUserGrant|${envParentId}`, `g|appUserGroup|${envParentId}`, ]), ], ], graphResponse: "envsAndOrChangesets", graphAuthorizer: async (action, orgGraph, userGraph, auth) => { for (let envParentId in action.payload.byEnvParentId) { if (!userGraph[envParentId]) { return false; } } return true; }, graphHandler: async ({ payload }, orgGraph, auth, now) => { let envs: Api.HandlerEnvsResponse | undefined, inheritanceOverrides: Api.HandlerEnvsResponse | undefined, changesets: Api.HandlerChangesetsResponse | undefined; const envEnvParentIds: string[] = []; const changesetEnvParentIds: string[] = []; const changesetsCreatedAfterByEnvParentId: Record< string, number | undefined > = {}; for (let envParentId in payload.byEnvParentId) { const envParentParams = payload.byEnvParentId[envParentId]; if (envParentParams.envs) { envEnvParentIds.push(envParentId); } if (envParentParams.changesets) { changesetEnvParentIds.push(envParentId); changesetsCreatedAfterByEnvParentId[envParentId] = envParentParams.changesetOptions?.createdAfter; } } if (envEnvParentIds.length > 0) { envs = getHandlerEnvsResponse(orgGraph, envEnvParentIds, "env"); inheritanceOverrides = getHandlerEnvsResponse( orgGraph, envEnvParentIds, "inheritanceOverrides" ); } if (changesetEnvParentIds.length > 0) { changesets = getHandlerEnvsResponse( orgGraph, changesetEnvParentIds, "changeset", changesetsCreatedAfterByEnvParentId ); } return { type: "graphHandlerResult", graph: orgGraph, envs, changesets, inheritanceOverrides, logTargetIds: getFetchActionLogTargetIdsFn(orgGraph), backgroundLogTargetIds: getFetchActionBackgroundLogTargetIdsFn(orgGraph), }; }, }); apiAction< Api.Action.RequestActions["CreateVariableGroup"], Api.Net.ApiResultTypes["CreateVariableGroup"] >({ type: Api.ActionType.CREATE_VARIABLE_GROUP, graphAction: true, authenticated: true, graphAuthorizer: async ( { payload: { envParentId, subEnvironmentId } }, orgGraph, userGraph, auth ) => canCreateOrDeleteVariableGroup( userGraph, auth, envParentId, subEnvironmentId ), graphHandler: async ({ payload }, orgGraph, auth, now) => { const id = uuid(), variableGroup: Api.Db.VariableGroup = { type: "variableGroup", id, ...graphKey.variableGroup(auth.org.id, payload.envParentId, id), ...pick(["envParentId", "subEnvironmentId", "name"], payload), createdAt: now, updatedAt: now, }; return { type: "graphHandlerResult", graph: { ...orgGraph, [variableGroup.id]: variableGroup, }, logTargetIds: [], }; }, }); apiAction< Api.Action.RequestActions["DeleteVariableGroup"], Api.Net.ApiResultTypes["DeleteVariableGroup"] >({ type: Api.ActionType.DELETE_VARIABLE_GROUP, graphAction: true, authenticated: true, graphAuthorizer: async ({ payload: { id } }, orgGraph, userGraph, auth) => { const variableGroup = userGraph[id]; if (!variableGroup || variableGroup.type != "variableGroup") { return false; } return canCreateOrDeleteVariableGroup( userGraph, auth, variableGroup.envParentId, variableGroup.subEnvironmentId ); }, graphHandler: async (action, orgGraph, auth, now) => { return { type: "graphHandlerResult", graph: deleteGraphObjects(orgGraph, [action.payload.id], now), logTargetIds: [], }; }, }); apiAction< Api.Action.RequestActions["CreateEnvironment"], Api.Net.ApiResultTypes["CreateEnvironment"] >({ type: Api.ActionType.CREATE_ENVIRONMENT, graphAction: true, authenticated: true, graphAuthorizer: async ({ payload }, orgGraph, userGraph, auth) => payload.isSub ? authz.canCreateSubEnvironment( userGraph, auth.user.id, payload.parentEnvironmentId ) : authz.canCreateBaseEnvironment( userGraph, auth.user.id, payload.envParentId, payload.environmentRoleId ), graphHandler: async ({ payload }, orgGraph, auth, now) => { const id = uuid(), environment: Api.Db.Environment = { ...graphKey.environment(auth.org.id, payload.envParentId, id), ...(pick( [ "envParentId", "environmentRoleId", "isSub", "parentEnvironmentId", "subName", ], payload ) as Model.Environment), type: "environment", id, createdAt: now, updatedAt: now, }, envParent = orgGraph[environment.envParentId] as Model.EnvParent, updatedGraph = { ...orgGraph, [environment.id]: environment, }; return { type: "graphHandlerResult", graph: updatedGraph, logTargetIds: [ envParent.id, environment.environmentRoleId, environment.isSub ? environmentCompositeId(environment) : undefined, ].filter((id): id is string => Boolean(id)), }; }, }); apiAction< Api.Action.RequestActions["DeleteEnvironment"], Api.Net.ApiResultTypes["DeleteEnvironment"] >({ type: Api.ActionType.DELETE_ENVIRONMENT, graphAction: true, authenticated: true, graphAuthorizer: async ({ payload: { id } }, orgGraph, userGraph, auth) => authz.canDeleteEnvironment(userGraph, auth.user.id, id), graphHandler: async (action, orgGraph, auth, now) => { const environment = orgGraph[action.payload.id] as Model.Environment; const envParent = orgGraph[environment.envParentId] as Model.EnvParent; let updatedGeneratedEnvkeyIds: string[] | undefined; let clearEnvkeySockets: Api.ClearEnvkeySocketParams[] | undefined; if (envParent.type == "app") { const generatedEnvkeys = getConnectedActiveGeneratedEnvkeys( orgGraph, environment.id ); clearEnvkeySockets = generatedEnvkeys.map( ({ id: generatedEnvkeyId }) => ({ orgId: auth.org.id, generatedEnvkeyId, }) ); } else { const ids = new Set<string>(); const generatedEnvkeys = getConnectedActiveGeneratedEnvkeys( orgGraph, environment.id ); for (let generatedEnvkey of generatedEnvkeys) { const blockEnvironments = getConnectedBlockEnvironmentsForApp( orgGraph, generatedEnvkey.appId, generatedEnvkey.environmentId ); if ( blockEnvironments.some(({ envUpdatedAt }) => Boolean(envUpdatedAt)) ) { ids.add(generatedEnvkey.id); } } updatedGeneratedEnvkeyIds = Array.from(ids); } const updatedGraph = produce( orgGraph, getDeleteEnvironmentProducer(action.payload.id, now) ) as Api.Graph.OrgGraph; return { type: "graphHandlerResult", graph: updatedGraph, transactionItems: { hardDeleteEncryptedBlobParams: [ { orgId: auth.org.id, envParentId: environment.envParentId, environmentId: environment.id, blobType: "env", }, { orgId: auth.org.id, envParentId: environment.envParentId, environmentId: environment.id, blobType: "changeset", }, ], hardDeleteScopes: [ { pkey: `encryptedKeys|${auth.org.id}`, pkeyPrefix: true, scope: getScope({ envParentId: environment.envParentId, environmentId: environment.id, blobType: "env", }), }, { pkey: `encryptedKeys|${auth.org.id}`, pkeyPrefix: true, scope: getScope({ envParentId: environment.envParentId, environmentId: environment.id, blobType: "changeset", }), }, ], }, logTargetIds: [ envParent.id, environment.environmentRoleId, environment.isSub ? environmentCompositeId(environment) : undefined, ].filter((id): id is string => Boolean(id)), updatedGeneratedEnvkeyIds, clearEnvkeySockets, }; }, }); apiAction< Api.Action.RequestActions["UpdateEnvironmentSettings"], Api.Net.ApiResultTypes["UpdateEnvironmentSettings"] >({ type: Api.ActionType.UPDATE_ENVIRONMENT_SETTINGS, authenticated: true, graphAction: true, graphAuthorizer: async ({ payload }, orgGraph, userGraph, auth) => { const environment = userGraph[payload.id]; if ( !environment || environment.type != "environment" || environment.isSub ) { return false; } const envParent = orgGraph[environment.envParentId] as Model.EnvParent; return envParent.type == "app" ? authz.hasAppPermission( orgGraph, auth.user.id, environment.envParentId, "app_manage_environments" ) : authz.hasOrgPermission( orgGraph, auth.user.id, "blocks_manage_environments" ); }, graphHandler: async ({ payload }, orgGraph, auth, now) => { const environment = orgGraph[payload.id] as Api.Db.Environment; return { type: "graphHandlerResult", graph: { ...orgGraph, [payload.id]: { ...environment, settings: payload.settings, updatedAt: now, }, }, logTargetIds: [ environment.envParentId, environment.environmentRoleId, environment.isSub ? environmentCompositeId(environment) : undefined, ].filter((id): id is string => Boolean(id)), }; }, }); const canCreateOrDeleteVariableGroup = ( userGraph: Client.Graph.UserGraph, auth: Auth.DefaultAuthContext, envParentId: string, subEnvironmentId?: string ) => { const envParent = userGraph[envParentId]; if (!envParent) { return false; } if (subEnvironmentId) { const subEnvironment = userGraph[subEnvironmentId]; if (!subEnvironment) { return false; } const permissions = getEnvironmentPermissions( userGraph, subEnvironmentId, auth.user.id ); return permissions.has("write"); } const environments = getEnvironmentsByEnvParentId(userGraph)[envParentId] || []; if (environments.length == 0) { return false; } for (let environment of environments) { const permissions = getEnvironmentPermissions( userGraph, environment.id, auth.user.id ); if (!permissions.has("write")) { return false; } } return true; }, getHandlerEnvsResponse = < BlobType extends "env" | "inheritanceOverrides" | "changeset" >( orgGraph: Api.Graph.OrgGraph, envParentIds: string[], blobType: BlobType, changesetsCreatedAfterByEnvParentId?: Record<string, number | undefined> ) => { return { scopes: R.flatten( envParentIds.map((envParentId) => { const envParent = orgGraph[envParentId] as Model.EnvParent; let connectedScopes: Blob.ScopeParams[]; if (envParent.type == "app") { const blockIds = getConnectedBlocksForApp( orgGraph, envParentId ).map(R.prop("id")); connectedScopes = blockIds.map( (blockId) => ({ blobType, envParentId: blockId, ...(blobType == "changeset" && changesetsCreatedAfterByEnvParentId?.[blockId] ? { createdAfter: changesetsCreatedAfterByEnvParentId[blockId], } : {}), } as Blob.ScopeParams) ); } else { connectedScopes = []; } return [ { blobType, envParentId, ...(blobType == "changeset" && changesetsCreatedAfterByEnvParentId?.[envParentId] ? { createdAfter: changesetsCreatedAfterByEnvParentId[envParentId], } : {}), }, ...connectedScopes, ]; }) ), } as BlobType extends "changeset" ? Api.HandlerChangesetsResponse : Api.HandlerEnvsResponse; };
the_stack
import * as coreClient from "@azure/core-client"; /** Result of the request to list operations. */ export interface ResourceProviderOperationList { /** List of operations supported by this resource provider. */ value?: ResourceProviderOperation[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Supported operation of this resource provider. */ export interface ResourceProviderOperation { /** Operation name, in format of {provider}/{resource}/{operation} */ name?: string; /** Display metadata associated with the operation. */ display?: ResourceProviderOperationDisplay; /** Is a data action. */ isDataAction?: boolean; /** Properties of the operation */ properties?: OperationProperties; } /** Display metadata associated with the operation. */ export interface ResourceProviderOperationDisplay { /** Resource provider: Microsoft Desktop Virtualization. */ provider?: string; /** Resource on which the operation is performed. */ resource?: string; /** Type of operation: get, read, delete, etc. */ operation?: string; /** Description of this operation. */ description?: string; } /** Properties of the operation */ export interface OperationProperties { /** Service specification payload */ serviceSpecification?: ServiceSpecification; } /** Service specification payload */ export interface ServiceSpecification { /** Specifications of the Log for Azure Monitoring */ logSpecifications?: LogSpecification[]; } /** Specifications of the Log for Azure Monitoring */ export interface LogSpecification { /** Name of the log */ name?: string; /** Localized friendly display name of the log */ displayName?: string; /** Blob duration of the log */ blobDuration?: string; } /** Cloud error object. */ export interface CloudError { /** Cloud error object properties. */ error?: CloudErrorProperties; } /** Cloud error object properties. */ export interface CloudErrorProperties { /** Error code */ code?: string; /** Error message indicating why the operation failed. */ message?: string; } /** Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** The identity that created the resource. */ createdBy?: string; /** The type of identity that created the resource. */ createdByType?: CreatedByType; /** The timestamp of resource creation (UTC). */ createdAt?: Date; /** The identity that last modified the resource. */ lastModifiedBy?: string; /** The type of identity that last modified the resource. */ lastModifiedByType?: CreatedByType; /** The timestamp of resource last modification (UTC) */ lastModifiedAt?: Date; } /** The resource model definition containing the full set of allowed properties for a resource. Except properties bag, there cannot be a top level property outside of this set. */ export interface ResourceModelWithAllowedPropertySet { /** * Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the resource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** The geo-location where the resource lives */ location?: string; /** The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another Azure resource. If this is present, complete mode deployment will not delete the resource if it is removed from the template since it is managed by another resource. */ managedBy?: string; /** Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. If supported, the resource provider must validate and persist this value. */ kind?: string; /** * The etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly etag?: string; /** Resource tags. */ tags?: { [propertyName: string]: string }; identity?: ResourceModelWithAllowedPropertySetIdentity; sku?: ResourceModelWithAllowedPropertySetSku; plan?: ResourceModelWithAllowedPropertySetPlan; } /** Identity for the resource. */ export interface Identity { /** * The principal ID of resource identity. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly principalId?: string; /** * The tenant ID of resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly tenantId?: string; /** The identity type. */ type?: "SystemAssigned"; } /** The resource model definition representing SKU */ export interface Sku { /** The name of the SKU. Ex - P3. It is typically a letter+number code */ name: string; /** This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. */ tier?: SkuTier; /** The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. */ size?: string; /** If the service has different generations of hardware, for the same SKU, then that can be captured here. */ family?: string; /** If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. */ capacity?: number; } /** Plan for the resource. */ export interface Plan { /** A user defined name of the 3rd Party Artifact that is being procured. */ name: string; /** The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic */ publisher: string; /** The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. */ product: string; /** A publisher provided promotion code as provisioned in Data Market for the said product/artifact. */ promotionCode?: string; /** The version of the desired product/artifact. */ version?: string; } /** Workspace properties that can be patched. */ export interface WorkspacePatch { /** tags to be updated */ tags?: { [propertyName: string]: string }; /** Description of Workspace. */ description?: string; /** Friendly name of Workspace. */ friendlyName?: string; /** List of applicationGroup links. */ applicationGroupReferences?: string[]; /** Enabled to allow this resource to be access from the public network */ publicNetworkAccess?: PublicNetworkAccess; } /** List of Workspace definitions. */ export interface WorkspaceList { /** List of Workspace definitions. */ value?: Workspace[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Scaling plan schedule. */ export interface ScalingSchedule { /** Name of the scaling schedule. */ name?: string; /** Set of days of the week on which this schedule is active. */ daysOfWeek?: ScalingScheduleDaysOfWeekItem[]; /** Starting time for ramp up period. */ rampUpStartTime?: Time; /** Load balancing algorithm for ramp up period. */ rampUpLoadBalancingAlgorithm?: SessionHostLoadBalancingAlgorithm; /** Minimum host percentage for ramp up period. */ rampUpMinimumHostsPct?: number; /** Capacity threshold for ramp up period. */ rampUpCapacityThresholdPct?: number; /** Starting time for peak period. */ peakStartTime?: Time; /** Load balancing algorithm for peak period. */ peakLoadBalancingAlgorithm?: SessionHostLoadBalancingAlgorithm; /** Starting time for ramp down period. */ rampDownStartTime?: Time; /** Load balancing algorithm for ramp down period. */ rampDownLoadBalancingAlgorithm?: SessionHostLoadBalancingAlgorithm; /** Minimum host percentage for ramp down period. */ rampDownMinimumHostsPct?: number; /** Capacity threshold for ramp down period. */ rampDownCapacityThresholdPct?: number; /** Should users be logged off forcefully from hosts. */ rampDownForceLogoffUsers?: boolean; /** Specifies when to stop hosts during ramp down period. */ rampDownStopHostsWhen?: StopHostsWhen; /** Number of minutes to wait to stop hosts during ramp down period. */ rampDownWaitTimeMinutes?: number; /** Notification message for users during ramp down period. */ rampDownNotificationMessage?: string; /** Starting time for off-peak period. */ offPeakStartTime?: Time; /** Load balancing algorithm for off-peak period. */ offPeakLoadBalancingAlgorithm?: SessionHostLoadBalancingAlgorithm; } /** The time for a scaling action to occur. */ export interface Time { /** The hour. */ hour: number; /** The minute. */ minute: number; } /** Scaling plan reference to hostpool. */ export interface ScalingHostPoolReference { /** Arm path of referenced hostpool. */ hostPoolArmPath?: string; /** Is the scaling plan enabled for this hostpool. */ scalingPlanEnabled?: boolean; } /** Scaling plan properties that can be patched. */ export interface ScalingPlanPatch { /** tags to be updated */ tags?: { [propertyName: string]: string }; /** Description of scaling plan. */ description?: string; /** User friendly name of scaling plan. */ friendlyName?: string; /** Timezone of the scaling plan. */ timeZone?: string; /** Exclusion tag for scaling plan. */ exclusionTag?: string; /** List of ScalingSchedule definitions. */ schedules?: ScalingSchedule[]; /** List of ScalingHostPoolReference definitions. */ hostPoolReferences?: ScalingHostPoolReference[]; } /** List of scaling plan definitions. */ export interface ScalingPlanList { /** List of scaling plan definitions. */ value?: ScalingPlan[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Properties for arm migration. */ export interface MigrationRequestProperties { /** The type of operation for migration. */ operation?: Operation; /** The path to the legacy object to migrate. */ migrationPath?: string; } /** Common fields that are returned in the response for all Azure Resource Manager resources */ export interface Resource { /** * Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The name of the resource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** List of ApplicationGroup definitions. */ export interface ApplicationGroupList { /** List of ApplicationGroup definitions. */ value?: ApplicationGroup[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** List of StartMenuItem definitions. */ export interface StartMenuItemList { /** List of StartMenuItem definitions. */ value?: StartMenuItem[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Application properties that can be patched. */ export interface ApplicationPatch { /** tags to be updated */ tags?: { [propertyName: string]: string }; /** Description of Application. */ description?: string; /** Friendly name of Application. */ friendlyName?: string; /** Specifies a path for the executable file for the application. */ filePath?: string; /** Specifies whether this published application can be launched with command line arguments provided by the client, command line arguments specified at publish time, or no command line arguments at all. */ commandLineSetting?: CommandLineSetting; /** Command Line Arguments for Application. */ commandLineArguments?: string; /** Specifies whether to show the RemoteApp program in the RD Web Access server. */ showInPortal?: boolean; /** Path to icon. */ iconPath?: string; /** Index of the icon. */ iconIndex?: number; /** Specifies the package family name for MSIX applications */ msixPackageFamilyName?: string; /** Specifies the package application Id for MSIX applications */ msixPackageApplicationId?: string; /** Resource Type of Application. */ applicationType?: RemoteApplicationType; } /** List of Application definitions. */ export interface ApplicationList { /** List of Application definitions. */ value?: Application[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Desktop properties that can be patched. */ export interface DesktopPatch { /** tags to be updated */ tags?: { [propertyName: string]: string }; /** Description of Desktop. */ description?: string; /** Friendly name of Desktop. */ friendlyName?: string; } /** List of Desktop definitions. */ export interface DesktopList { /** List of Desktop definitions. */ value?: Desktop[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Represents a RegistrationInfo definition. */ export interface RegistrationInfo { /** Expiration time of registration token. */ expirationTime?: Date; /** The registration token base64 encoded string. */ token?: string; /** The type of resetting the token. */ registrationTokenOperation?: RegistrationTokenOperation; } /** Represents a RegistrationInfo definition. */ export interface RegistrationInfoPatch { /** Expiration time of registration token. */ expirationTime?: Date; /** The type of resetting the token. */ registrationTokenOperation?: RegistrationTokenOperation; } /** List of HostPool definitions. */ export interface HostPoolList { /** List of HostPool definitions. */ value?: HostPool[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** List of UserSession definitions. */ export interface UserSessionList { /** List of UserSession definitions. */ value?: UserSession[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The report for session host information. */ export interface SessionHostHealthCheckReport { /** * Represents the name of the health check operation performed. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly healthCheckName?: HealthCheckName; /** * Represents the Health state of the health check we performed. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly healthCheckResult?: HealthCheckResult; /** * Additional detailed information on the failure. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly additionalFailureDetails?: SessionHostHealthCheckFailureDetails; } /** Contains details on the failure. */ export interface SessionHostHealthCheckFailureDetails { /** * Failure message: hints on what is wrong and how to recover. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * Error code corresponding for the failure. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly errorCode?: number; /** * The timestamp of the last update. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastHealthCheckDateTime?: Date; } /** List of SessionHost definitions. */ export interface SessionHostList { /** List of SessionHost definitions. */ value?: SessionHost[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Schema for MSIX Package Dependencies properties. */ export interface MsixPackageDependencies { /** Name of package dependency. */ dependencyName?: string; /** Name of dependency publisher. */ publisher?: string; /** Dependency version required. */ minVersion?: string; } /** Schema for MSIX Package Application properties. */ export interface MsixPackageApplications { /** Package Application Id, found in appxmanifest.xml. */ appId?: string; /** Description of Package Application. */ description?: string; /** Used to activate Package Application. Consists of Package Name and ApplicationID. Found in appxmanifest.xml. */ appUserModelID?: string; /** User friendly name. */ friendlyName?: string; /** User friendly name. */ iconImageName?: string; /** the icon a 64 bit string as a byte array. */ rawIcon?: Uint8Array; /** the icon a 64 bit string as a byte array. */ rawPng?: Uint8Array; } /** List of MSIX Package definitions. */ export interface MsixPackageList { /** List of MSIX Package definitions. */ value?: MsixPackage[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Represents URI referring to MSIX Image */ export interface MsixImageURI { /** URI to Image */ uri?: string; } /** List of MSIX package properties retrieved from MSIX Image expansion. */ export interface ExpandMsixImageList { /** List of MSIX package properties from give MSIX Image. */ value?: ExpandMsixImage[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Represents message sent to a UserSession. */ export interface SendMessage { /** Title of message. */ messageTitle?: string; /** Body of message. */ messageBody?: string; } /** List of private endpoint connection associated with the specified storage account */ export interface PrivateEndpointConnectionListResultWithSystemData { /** Array of private endpoint connections */ value?: PrivateEndpointConnectionWithSystemData[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The Private Endpoint resource. */ export interface PrivateEndpoint { /** * The ARM identifier for Private Endpoint * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; } /** A collection of information about the state of the connection between service consumer and provider. */ export interface PrivateLinkServiceConnectionState { /** Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. */ status?: PrivateEndpointServiceConnectionStatus; /** The reason for approval/rejection of the connection. */ description?: string; /** A message indicating if changes on the service provider require any updates on the consumer. */ actionsRequired?: string; } /** A list of private link resources */ export interface PrivateLinkResourceListResult { /** Array of private link resources */ value?: PrivateLinkResource[]; /** * Link to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Represents a Workspace definition. */ export type Workspace = ResourceModelWithAllowedPropertySet & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * ObjectId of Workspace. (internal use) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** Description of Workspace. */ description?: string; /** Friendly name of Workspace. */ friendlyName?: string; /** List of applicationGroup resource Ids. */ applicationGroupReferences?: string[]; /** * Is cloud pc resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly cloudPcResource?: boolean; /** Enabled allows this resource to be accessed from both public and private networks, Disabled allows this resource to only be accessed via private endpoints */ publicNetworkAccess?: PublicNetworkAccess; }; /** Represents a scaling plan definition. */ export type ScalingPlan = ResourceModelWithAllowedPropertySet & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * ObjectId of scaling plan. (internal use) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** Description of scaling plan. */ description?: string; /** User friendly name of scaling plan. */ friendlyName?: string; /** Timezone of the scaling plan. */ timeZone?: string; /** HostPool type for desktop. */ hostPoolType?: ScalingHostPoolType; /** Exclusion tag for scaling plan. */ exclusionTag?: string; /** List of ScalingSchedule definitions. */ schedules?: ScalingSchedule[]; /** List of ScalingHostPoolReference definitions. */ hostPoolReferences?: ScalingHostPoolReference[]; }; /** Represents a ApplicationGroup definition. */ export type ApplicationGroup = ResourceModelWithAllowedPropertySet & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * ObjectId of ApplicationGroup. (internal use) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** Description of ApplicationGroup. */ description?: string; /** Friendly name of ApplicationGroup. */ friendlyName?: string; /** HostPool arm path of ApplicationGroup. */ hostPoolArmPath: string; /** * Workspace arm path of ApplicationGroup. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly workspaceArmPath?: string; /** Resource Type of ApplicationGroup. */ applicationGroupType: ApplicationGroupType; /** The registration info of HostPool. */ migrationRequest?: MigrationRequestProperties; /** * Is cloud pc resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly cloudPcResource?: boolean; }; /** Represents a HostPool definition. */ export type HostPool = ResourceModelWithAllowedPropertySet & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * ObjectId of HostPool. (internal use) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** Friendly name of HostPool. */ friendlyName?: string; /** Description of HostPool. */ description?: string; /** HostPool type for desktop. */ hostPoolType: HostPoolType; /** PersonalDesktopAssignment type for HostPool. */ personalDesktopAssignmentType?: PersonalDesktopAssignmentType; /** Custom rdp property of HostPool. */ customRdpProperty?: string; /** The max session limit of HostPool. */ maxSessionLimit?: number; /** The type of the load balancer. */ loadBalancerType: LoadBalancerType; /** The ring number of HostPool. */ ring?: number; /** Is validation environment. */ validationEnvironment?: boolean; /** The registration info of HostPool. */ registrationInfo?: RegistrationInfo; /** VM template for sessionhosts configuration within hostpool. */ vmTemplate?: string; /** * List of applicationGroup links. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly applicationGroupReferences?: string[]; /** URL to customer ADFS server for signing WVD SSO certificates. */ ssoadfsAuthority?: string; /** ClientId for the registered Relying Party used to issue WVD SSO certificates. */ ssoClientId?: string; /** Path to Azure KeyVault storing the secret used for communication to ADFS. */ ssoClientSecretKeyVaultPath?: string; /** The type of single sign on Secret Type. */ ssoSecretType?: SSOSecretType; /** The type of preferred application group type, default to Desktop Application Group */ preferredAppGroupType: PreferredAppGroupType; /** The flag to turn on/off StartVMOnConnect feature. */ startVMOnConnect?: boolean; /** The registration info of HostPool. */ migrationRequest?: MigrationRequestProperties; /** * Is cloud pc resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly cloudPcResource?: boolean; /** Enabled allows this resource to be accessed from both public and private networks, Disabled allows this resource to only be accessed via private endpoints */ publicNetworkAccess?: PublicNetworkAccess; }; export type ResourceModelWithAllowedPropertySetIdentity = Identity & {}; export type ResourceModelWithAllowedPropertySetSku = Sku & {}; export type ResourceModelWithAllowedPropertySetPlan = Plan & {}; /** ApplicationGroup properties that can be patched. */ export type ApplicationGroupPatch = Resource & { /** tags to be updated */ tags?: { [propertyName: string]: string }; /** Description of ApplicationGroup. */ description?: string; /** Friendly name of ApplicationGroup. */ friendlyName?: string; }; /** Represents a StartMenuItem definition. */ export type StartMenuItem = Resource & { /** Alias of StartMenuItem. */ appAlias?: string; /** Path to the file of StartMenuItem. */ filePath?: string; /** Command line arguments for StartMenuItem. */ commandLineArguments?: string; /** Path to the icon. */ iconPath?: string; /** Index of the icon. */ iconIndex?: number; }; /** Schema for Application properties. */ export type Application = Resource & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * ObjectId of Application. (internal use) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** Description of Application. */ description?: string; /** Friendly name of Application. */ friendlyName?: string; /** Specifies a path for the executable file for the application. */ filePath?: string; /** Specifies the package family name for MSIX applications */ msixPackageFamilyName?: string; /** Specifies the package application Id for MSIX applications */ msixPackageApplicationId?: string; /** Resource Type of Application. */ applicationType?: RemoteApplicationType; /** Specifies whether this published application can be launched with command line arguments provided by the client, command line arguments specified at publish time, or no command line arguments at all. */ commandLineSetting: CommandLineSetting; /** Command Line Arguments for Application. */ commandLineArguments?: string; /** Specifies whether to show the RemoteApp program in the RD Web Access server. */ showInPortal?: boolean; /** Path to icon. */ iconPath?: string; /** Index of the icon. */ iconIndex?: number; /** * Hash of the icon. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly iconHash?: string; /** * the icon a 64 bit string as a byte array. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly iconContent?: Uint8Array; }; /** Schema for Desktop properties. */ export type Desktop = Resource & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * ObjectId of Desktop. (internal use) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** Description of Desktop. */ description?: string; /** Friendly name of Desktop. */ friendlyName?: string; /** * Hash of the icon. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly iconHash?: string; /** * The icon a 64 bit string as a byte array. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly iconContent?: Uint8Array; }; /** HostPool properties that can be patched. */ export type HostPoolPatch = Resource & { /** tags to be updated */ tags?: { [propertyName: string]: string }; /** Friendly name of HostPool. */ friendlyName?: string; /** Description of HostPool. */ description?: string; /** Custom rdp property of HostPool. */ customRdpProperty?: string; /** The max session limit of HostPool. */ maxSessionLimit?: number; /** PersonalDesktopAssignment type for HostPool. */ personalDesktopAssignmentType?: PersonalDesktopAssignmentType; /** The type of the load balancer. */ loadBalancerType?: LoadBalancerType; /** The ring number of HostPool. */ ring?: number; /** Is validation environment. */ validationEnvironment?: boolean; /** The registration info of HostPool. */ registrationInfo?: RegistrationInfoPatch; /** VM template for sessionhosts configuration within hostpool. */ vmTemplate?: string; /** URL to customer ADFS server for signing WVD SSO certificates. */ ssoadfsAuthority?: string; /** ClientId for the registered Relying Party used to issue WVD SSO certificates. */ ssoClientId?: string; /** Path to Azure KeyVault storing the secret used for communication to ADFS. */ ssoClientSecretKeyVaultPath?: string; /** The type of single sign on Secret Type. */ ssoSecretType?: SSOSecretType; /** The type of preferred application group type, default to Desktop Application Group */ preferredAppGroupType?: PreferredAppGroupType; /** The flag to turn on/off StartVMOnConnect feature. */ startVMOnConnect?: boolean; /** Enabled to allow this resource to be access from the public network */ publicNetworkAccess?: PublicNetworkAccess; }; /** Represents a UserSession definition. */ export type UserSession = Resource & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * ObjectId of user session. (internal use) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** The user principal name. */ userPrincipalName?: string; /** Application type of application. */ applicationType?: ApplicationType; /** State of user session. */ sessionState?: SessionState; /** The active directory user name. */ activeDirectoryUserName?: string; /** The timestamp of the user session create. */ createTime?: Date; }; /** Represents a SessionHost definition. */ export type SessionHost = Resource & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** * ObjectId of SessionHost. (internal use) * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** Last heart beat from SessionHost. */ lastHeartBeat?: Date; /** Number of sessions on SessionHost. */ sessions?: number; /** Version of agent on SessionHost. */ agentVersion?: string; /** Allow a new session. */ allowNewSession?: boolean; /** * Virtual Machine Id of SessionHost's underlying virtual machine. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly virtualMachineId?: string; /** * Resource Id of SessionHost's underlying virtual machine. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceId?: string; /** User assigned to SessionHost. */ assignedUser?: string; /** Status for a SessionHost. */ status?: Status; /** * The timestamp of the status. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly statusTimestamp?: Date; /** The version of the OS on the session host. */ osVersion?: string; /** The version of the side by side stack on the session host. */ sxSStackVersion?: string; /** Update state of a SessionHost. */ updateState?: UpdateState; /** * The timestamp of the last update. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastUpdateTime?: Date; /** The error message. */ updateErrorMessage?: string; /** * List of SessionHostHealthCheckReports * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly sessionHostHealthCheckResults?: SessionHostHealthCheckReport[]; }; /** SessionHost properties that can be patched. */ export type SessionHostPatch = Resource & { /** Allow a new session. */ allowNewSession?: boolean; /** User assigned to SessionHost. */ assignedUser?: string; }; /** Schema for MSIX Package properties. */ export type MsixPackage = Resource & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; /** VHD/CIM image path on Network Share. */ imagePath?: string; /** Package Name from appxmanifest.xml. */ packageName?: string; /** Package Family Name from appxmanifest.xml. Contains Package Name and Publisher name. */ packageFamilyName?: string; /** User friendly Name to be displayed in the portal. */ displayName?: string; /** Relative Path to the package inside the image. */ packageRelativePath?: string; /** Specifies how to register Package in feed. */ isRegularRegistration?: boolean; /** Make this version of the package the active one across the hostpool. */ isActive?: boolean; /** List of package dependencies. */ packageDependencies?: MsixPackageDependencies[]; /** Package Version found in the appxmanifest.xml. */ version?: string; /** Date Package was last updated, found in the appxmanifest.xml. */ lastUpdated?: Date; /** List of package applications. */ packageApplications?: MsixPackageApplications[]; }; /** MSIX Package properties that can be patched. */ export type MsixPackagePatch = Resource & { /** Set a version of the package to be active across hostpool. */ isActive?: boolean; /** Set Registration mode. Regular or Delayed. */ isRegularRegistration?: boolean; /** Display name for MSIX Package. */ displayName?: string; }; /** Represents the definition of contents retrieved after expanding the MSIX Image. */ export type ExpandMsixImage = Resource & { /** Alias of MSIX Package. */ packageAlias?: string; /** VHD/CIM image path on Network Share. */ imagePath?: string; /** Package Name from appxmanifest.xml. */ packageName?: string; /** Package Family Name from appxmanifest.xml. Contains Package Name and Publisher name. */ packageFamilyName?: string; /** Package Full Name from appxmanifest.xml. */ packageFullName?: string; /** User friendly Name to be displayed in the portal. */ displayName?: string; /** Relative Path to the package inside the image. */ packageRelativePath?: string; /** Specifies how to register Package in feed. */ isRegularRegistration?: boolean; /** Make this version of the package the active one across the hostpool. */ isActive?: boolean; /** List of package dependencies. */ packageDependencies?: MsixPackageDependencies[]; /** Package Version found in the appxmanifest.xml. */ version?: string; /** Date Package was last updated, found in the appxmanifest.xml. */ lastUpdated?: Date; /** List of package applications. */ packageApplications?: MsixPackageApplications[]; }; /** The Private Endpoint Connection resource. */ export type PrivateEndpointConnection = Resource & { /** The resource of private end point. */ privateEndpoint?: PrivateEndpoint; /** A collection of information about the state of the connection between service consumer and provider. */ privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; /** The provisioning state of the private endpoint connection resource. */ provisioningState?: PrivateEndpointConnectionProvisioningState; }; /** A private link resource */ export type PrivateLinkResource = Resource & { /** * The private link resource group id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly groupId?: string; /** * The private link resource required member names. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly requiredMembers?: string[]; /** The private link resource Private link DNS zone name. */ requiredZoneNames?: string[]; }; /** The Private Endpoint Connection resource. */ export type PrivateEndpointConnectionWithSystemData = PrivateEndpointConnection & { /** * Metadata pertaining to creation and last modification of the resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; }; /** Known values of {@link CreatedByType} that the service accepts. */ export enum KnownCreatedByType { User = "User", Application = "Application", ManagedIdentity = "ManagedIdentity", Key = "Key" } /** * Defines values for CreatedByType. \ * {@link KnownCreatedByType} can be used interchangeably with CreatedByType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Application** \ * **ManagedIdentity** \ * **Key** */ export type CreatedByType = string; /** Known values of {@link PublicNetworkAccess} that the service accepts. */ export enum KnownPublicNetworkAccess { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for PublicNetworkAccess. \ * {@link KnownPublicNetworkAccess} can be used interchangeably with PublicNetworkAccess, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type PublicNetworkAccess = string; /** Known values of {@link ScalingHostPoolType} that the service accepts. */ export enum KnownScalingHostPoolType { /** Users get a new (random) SessionHost every time it connects to the HostPool. */ Pooled = "Pooled" } /** * Defines values for ScalingHostPoolType. \ * {@link KnownScalingHostPoolType} can be used interchangeably with ScalingHostPoolType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pooled**: Users get a new (random) SessionHost every time it connects to the HostPool. */ export type ScalingHostPoolType = string; /** Known values of {@link ScalingScheduleDaysOfWeekItem} that the service accepts. */ export enum KnownScalingScheduleDaysOfWeekItem { Sunday = "Sunday", Monday = "Monday", Tuesday = "Tuesday", Wednesday = "Wednesday", Thursday = "Thursday", Friday = "Friday", Saturday = "Saturday" } /** * Defines values for ScalingScheduleDaysOfWeekItem. \ * {@link KnownScalingScheduleDaysOfWeekItem} can be used interchangeably with ScalingScheduleDaysOfWeekItem, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Sunday** \ * **Monday** \ * **Tuesday** \ * **Wednesday** \ * **Thursday** \ * **Friday** \ * **Saturday** */ export type ScalingScheduleDaysOfWeekItem = string; /** Known values of {@link SessionHostLoadBalancingAlgorithm} that the service accepts. */ export enum KnownSessionHostLoadBalancingAlgorithm { BreadthFirst = "BreadthFirst", DepthFirst = "DepthFirst" } /** * Defines values for SessionHostLoadBalancingAlgorithm. \ * {@link KnownSessionHostLoadBalancingAlgorithm} can be used interchangeably with SessionHostLoadBalancingAlgorithm, * this enum contains the known values that the service supports. * ### Known values supported by the service * **BreadthFirst** \ * **DepthFirst** */ export type SessionHostLoadBalancingAlgorithm = string; /** Known values of {@link StopHostsWhen} that the service accepts. */ export enum KnownStopHostsWhen { ZeroSessions = "ZeroSessions", ZeroActiveSessions = "ZeroActiveSessions" } /** * Defines values for StopHostsWhen. \ * {@link KnownStopHostsWhen} can be used interchangeably with StopHostsWhen, * this enum contains the known values that the service supports. * ### Known values supported by the service * **ZeroSessions** \ * **ZeroActiveSessions** */ export type StopHostsWhen = string; /** Known values of {@link ApplicationGroupType} that the service accepts. */ export enum KnownApplicationGroupType { RemoteApp = "RemoteApp", Desktop = "Desktop" } /** * Defines values for ApplicationGroupType. \ * {@link KnownApplicationGroupType} can be used interchangeably with ApplicationGroupType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **RemoteApp** \ * **Desktop** */ export type ApplicationGroupType = string; /** Known values of {@link Operation} that the service accepts. */ export enum KnownOperation { /** Start the migration. */ Start = "Start", /** Revoke the migration. */ Revoke = "Revoke", /** Complete the migration. */ Complete = "Complete", /** Hide the hostpool. */ Hide = "Hide", /** Unhide the hostpool. */ Unhide = "Unhide" } /** * Defines values for Operation. \ * {@link KnownOperation} can be used interchangeably with Operation, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Start**: Start the migration. \ * **Revoke**: Revoke the migration. \ * **Complete**: Complete the migration. \ * **Hide**: Hide the hostpool. \ * **Unhide**: Unhide the hostpool. */ export type Operation = string; /** Known values of {@link RemoteApplicationType} that the service accepts. */ export enum KnownRemoteApplicationType { InBuilt = "InBuilt", MsixApplication = "MsixApplication" } /** * Defines values for RemoteApplicationType. \ * {@link KnownRemoteApplicationType} can be used interchangeably with RemoteApplicationType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **InBuilt** \ * **MsixApplication** */ export type RemoteApplicationType = string; /** Known values of {@link CommandLineSetting} that the service accepts. */ export enum KnownCommandLineSetting { DoNotAllow = "DoNotAllow", Allow = "Allow", Require = "Require" } /** * Defines values for CommandLineSetting. \ * {@link KnownCommandLineSetting} can be used interchangeably with CommandLineSetting, * this enum contains the known values that the service supports. * ### Known values supported by the service * **DoNotAllow** \ * **Allow** \ * **Require** */ export type CommandLineSetting = string; /** Known values of {@link HostPoolType} that the service accepts. */ export enum KnownHostPoolType { /** Users will be assigned a SessionHost either by administrators (PersonalDesktopAssignmentType = Direct) or upon connecting to the pool (PersonalDesktopAssignmentType = Automatic). They will always be redirected to their assigned SessionHost. */ Personal = "Personal", /** Users get a new (random) SessionHost every time it connects to the HostPool. */ Pooled = "Pooled", /** Users assign their own machines, load balancing logic remains the same as Personal. PersonalDesktopAssignmentType must be Direct. */ BYODesktop = "BYODesktop" } /** * Defines values for HostPoolType. \ * {@link KnownHostPoolType} can be used interchangeably with HostPoolType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Personal**: Users will be assigned a SessionHost either by administrators (PersonalDesktopAssignmentType = Direct) or upon connecting to the pool (PersonalDesktopAssignmentType = Automatic). They will always be redirected to their assigned SessionHost. \ * **Pooled**: Users get a new (random) SessionHost every time it connects to the HostPool. \ * **BYODesktop**: Users assign their own machines, load balancing logic remains the same as Personal. PersonalDesktopAssignmentType must be Direct. */ export type HostPoolType = string; /** Known values of {@link PersonalDesktopAssignmentType} that the service accepts. */ export enum KnownPersonalDesktopAssignmentType { Automatic = "Automatic", Direct = "Direct" } /** * Defines values for PersonalDesktopAssignmentType. \ * {@link KnownPersonalDesktopAssignmentType} can be used interchangeably with PersonalDesktopAssignmentType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Automatic** \ * **Direct** */ export type PersonalDesktopAssignmentType = string; /** Known values of {@link LoadBalancerType} that the service accepts. */ export enum KnownLoadBalancerType { BreadthFirst = "BreadthFirst", DepthFirst = "DepthFirst", Persistent = "Persistent" } /** * Defines values for LoadBalancerType. \ * {@link KnownLoadBalancerType} can be used interchangeably with LoadBalancerType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **BreadthFirst** \ * **DepthFirst** \ * **Persistent** */ export type LoadBalancerType = string; /** Known values of {@link RegistrationTokenOperation} that the service accepts. */ export enum KnownRegistrationTokenOperation { Delete = "Delete", None = "None", Update = "Update" } /** * Defines values for RegistrationTokenOperation. \ * {@link KnownRegistrationTokenOperation} can be used interchangeably with RegistrationTokenOperation, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Delete** \ * **None** \ * **Update** */ export type RegistrationTokenOperation = string; /** Known values of {@link SSOSecretType} that the service accepts. */ export enum KnownSSOSecretType { SharedKey = "SharedKey", Certificate = "Certificate", SharedKeyInKeyVault = "SharedKeyInKeyVault", CertificateInKeyVault = "CertificateInKeyVault" } /** * Defines values for SSOSecretType. \ * {@link KnownSSOSecretType} can be used interchangeably with SSOSecretType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **SharedKey** \ * **Certificate** \ * **SharedKeyInKeyVault** \ * **CertificateInKeyVault** */ export type SSOSecretType = string; /** Known values of {@link PreferredAppGroupType} that the service accepts. */ export enum KnownPreferredAppGroupType { None = "None", Desktop = "Desktop", RailApplications = "RailApplications" } /** * Defines values for PreferredAppGroupType. \ * {@link KnownPreferredAppGroupType} can be used interchangeably with PreferredAppGroupType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **None** \ * **Desktop** \ * **RailApplications** */ export type PreferredAppGroupType = string; /** Known values of {@link ApplicationType} that the service accepts. */ export enum KnownApplicationType { RemoteApp = "RemoteApp", Desktop = "Desktop" } /** * Defines values for ApplicationType. \ * {@link KnownApplicationType} can be used interchangeably with ApplicationType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **RemoteApp** \ * **Desktop** */ export type ApplicationType = string; /** Known values of {@link SessionState} that the service accepts. */ export enum KnownSessionState { Unknown = "Unknown", Active = "Active", Disconnected = "Disconnected", Pending = "Pending", LogOff = "LogOff", UserProfileDiskMounted = "UserProfileDiskMounted" } /** * Defines values for SessionState. \ * {@link KnownSessionState} can be used interchangeably with SessionState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Unknown** \ * **Active** \ * **Disconnected** \ * **Pending** \ * **LogOff** \ * **UserProfileDiskMounted** */ export type SessionState = string; /** Known values of {@link Status} that the service accepts. */ export enum KnownStatus { /** Session Host has passed all the health checks and is available to handle connections. */ Available = "Available", /** Session Host is either turned off or has failed critical health checks which is causing service not to be able to route connections to this session host. Note this replaces previous 'NoHeartBeat' status. */ Unavailable = "Unavailable", /** Session Host is shutdown - RD Agent reported session host to be stopped or deallocated. */ Shutdown = "Shutdown", /** The Session Host is unavailable because it is currently disconnected. */ Disconnected = "Disconnected", /** Session Host is unavailable because currently an upgrade of RDAgent/side-by-side stack is in progress. Note: this state will be removed once the upgrade completes and the host is able to accept connections. */ Upgrading = "Upgrading", /** Session Host is unavailable because the critical component upgrade (agent, side-by-side stack, etc.) failed. */ UpgradeFailed = "UpgradeFailed", /** The Session Host is not heart beating. */ NoHeartbeat = "NoHeartbeat", /** SessionHost is not joined to domain. */ NotJoinedToDomain = "NotJoinedToDomain", /** SessionHost's domain trust relationship lost */ DomainTrustRelationshipLost = "DomainTrustRelationshipLost", /** SxS stack installed on the SessionHost is not ready to receive connections. */ SxSStackListenerNotReady = "SxSStackListenerNotReady", /** FSLogix is in an unhealthy state on the session host. */ FSLogixNotHealthy = "FSLogixNotHealthy", /** New status to inform admins that the health on their endpoint needs to be fixed. The connections might not fail, as these issues are not fatal. */ NeedsAssistance = "NeedsAssistance" } /** * Defines values for Status. \ * {@link KnownStatus} can be used interchangeably with Status, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Available**: Session Host has passed all the health checks and is available to handle connections. \ * **Unavailable**: Session Host is either turned off or has failed critical health checks which is causing service not to be able to route connections to this session host. Note this replaces previous 'NoHeartBeat' status. \ * **Shutdown**: Session Host is shutdown - RD Agent reported session host to be stopped or deallocated. \ * **Disconnected**: The Session Host is unavailable because it is currently disconnected. \ * **Upgrading**: Session Host is unavailable because currently an upgrade of RDAgent\/side-by-side stack is in progress. Note: this state will be removed once the upgrade completes and the host is able to accept connections. \ * **UpgradeFailed**: Session Host is unavailable because the critical component upgrade (agent, side-by-side stack, etc.) failed. \ * **NoHeartbeat**: The Session Host is not heart beating. \ * **NotJoinedToDomain**: SessionHost is not joined to domain. \ * **DomainTrustRelationshipLost**: SessionHost's domain trust relationship lost \ * **SxSStackListenerNotReady**: SxS stack installed on the SessionHost is not ready to receive connections. \ * **FSLogixNotHealthy**: FSLogix is in an unhealthy state on the session host. \ * **NeedsAssistance**: New status to inform admins that the health on their endpoint needs to be fixed. The connections might not fail, as these issues are not fatal. */ export type Status = string; /** Known values of {@link UpdateState} that the service accepts. */ export enum KnownUpdateState { Initial = "Initial", Pending = "Pending", Started = "Started", Succeeded = "Succeeded", Failed = "Failed" } /** * Defines values for UpdateState. \ * {@link KnownUpdateState} can be used interchangeably with UpdateState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Initial** \ * **Pending** \ * **Started** \ * **Succeeded** \ * **Failed** */ export type UpdateState = string; /** Known values of {@link HealthCheckName} that the service accepts. */ export enum KnownHealthCheckName { /** Verifies the SessionHost is joined to a domain. If this check fails is classified as fatal as no connection can succeed if the SessionHost is not joined to the domain. */ DomainJoinedCheck = "DomainJoinedCheck", /** Verifies the SessionHost is not experiencing domain trust issues that will prevent authentication on SessionHost at connection time when session is created. If this check fails is classified as fatal as no connection can succeed if we cannot reach the domain for authentication on the SessionHost. */ DomainTrustCheck = "DomainTrustCheck", /** Verifies the FSLogix service is up and running to make sure users' profiles are loaded in the session. If this check fails is classified as fatal as even if the connection can succeed, user experience is bad as the user profile cannot be loaded and user will get a temporary profile in the session. */ FSLogixHealthCheck = "FSLogixHealthCheck", /** Verifies that the SxS stack is up and running so connections can succeed. If this check fails is classified as fatal as no connection can succeed if the SxS stack is not ready. */ SxSStackListenerCheck = "SxSStackListenerCheck", /** Verifies that the required WVD service and Geneva URLs are reachable from the SessionHost. These URLs are: RdTokenUri, RdBrokerURI, RdDiagnosticsUri and storage blob URLs for agent monitoring (geneva). If this check fails, it is non fatal and the machine still can service connections, main issue may be that monitoring agent is unable to store warm path data (logs, operations ...). */ UrlsAccessibleCheck = "UrlsAccessibleCheck", /** Verifies that the required Geneva agent is running. If this check fails, it is non fatal and the machine still can service connections, main issue may be that monitoring agent is missing or running (possibly) older version. */ MonitoringAgentCheck = "MonitoringAgentCheck", /** Verifies the domain the SessionHost is joined to is still reachable. If this check fails is classified as fatal as no connection can succeed if the domain the SessionHost is joined is not reachable at the time of connection. */ DomainReachable = "DomainReachable", /** Verifies whether the WebRTCRedirector component is healthy. The WebRTCRedirector component is used to optimize video and audio performance in Microsoft Teams. This checks whether the component is still running, and whether there is a higher version available. If this check fails, it is non fatal and the machine still can service connections, main issue may be the WebRTCRedirector component has to be restarted or updated. */ WebRTCRedirectorCheck = "WebRTCRedirectorCheck", /** Verifies the value of SecurityLayer registration key. If the value is 0 (SecurityLayer.RDP) this check fails with Error code = NativeMethodErrorCode.E_FAIL and is fatal. If the value is 1 (SecurityLayer.Negotiate) this check fails with Error code = NativeMethodErrorCode.ERROR_SUCCESS and is non fatal. */ SupportedEncryptionCheck = "SupportedEncryptionCheck", /** Verifies the metadata service is accessible and return compute properties. */ MetaDataServiceCheck = "MetaDataServiceCheck", /** Verifies that the AppAttachService is healthy (there were no issues during package staging). The AppAttachService is used to enable the staging/registration (and eventual deregistration/destaging) of MSIX apps that have been set up by the tenant admin. This checks whether the component had any failures during package staging. Failures in staging will prevent some MSIX apps from working properly for the end user. If this check fails, it is non fatal and the machine still can service connections, main issue may be certain apps will not work for end-users. */ AppAttachHealthCheck = "AppAttachHealthCheck" } /** * Defines values for HealthCheckName. \ * {@link KnownHealthCheckName} can be used interchangeably with HealthCheckName, * this enum contains the known values that the service supports. * ### Known values supported by the service * **DomainJoinedCheck**: Verifies the SessionHost is joined to a domain. If this check fails is classified as fatal as no connection can succeed if the SessionHost is not joined to the domain. \ * **DomainTrustCheck**: Verifies the SessionHost is not experiencing domain trust issues that will prevent authentication on SessionHost at connection time when session is created. If this check fails is classified as fatal as no connection can succeed if we cannot reach the domain for authentication on the SessionHost. \ * **FSLogixHealthCheck**: Verifies the FSLogix service is up and running to make sure users' profiles are loaded in the session. If this check fails is classified as fatal as even if the connection can succeed, user experience is bad as the user profile cannot be loaded and user will get a temporary profile in the session. \ * **SxSStackListenerCheck**: Verifies that the SxS stack is up and running so connections can succeed. If this check fails is classified as fatal as no connection can succeed if the SxS stack is not ready. \ * **UrlsAccessibleCheck**: Verifies that the required WVD service and Geneva URLs are reachable from the SessionHost. These URLs are: RdTokenUri, RdBrokerURI, RdDiagnosticsUri and storage blob URLs for agent monitoring (geneva). If this check fails, it is non fatal and the machine still can service connections, main issue may be that monitoring agent is unable to store warm path data (logs, operations ...). \ * **MonitoringAgentCheck**: Verifies that the required Geneva agent is running. If this check fails, it is non fatal and the machine still can service connections, main issue may be that monitoring agent is missing or running (possibly) older version. \ * **DomainReachable**: Verifies the domain the SessionHost is joined to is still reachable. If this check fails is classified as fatal as no connection can succeed if the domain the SessionHost is joined is not reachable at the time of connection. \ * **WebRTCRedirectorCheck**: Verifies whether the WebRTCRedirector component is healthy. The WebRTCRedirector component is used to optimize video and audio performance in Microsoft Teams. This checks whether the component is still running, and whether there is a higher version available. If this check fails, it is non fatal and the machine still can service connections, main issue may be the WebRTCRedirector component has to be restarted or updated. \ * **SupportedEncryptionCheck**: Verifies the value of SecurityLayer registration key. If the value is 0 (SecurityLayer.RDP) this check fails with Error code = NativeMethodErrorCode.E_FAIL and is fatal. If the value is 1 (SecurityLayer.Negotiate) this check fails with Error code = NativeMethodErrorCode.ERROR_SUCCESS and is non fatal. \ * **MetaDataServiceCheck**: Verifies the metadata service is accessible and return compute properties. \ * **AppAttachHealthCheck**: Verifies that the AppAttachService is healthy (there were no issues during package staging). The AppAttachService is used to enable the staging\/registration (and eventual deregistration\/destaging) of MSIX apps that have been set up by the tenant admin. This checks whether the component had any failures during package staging. Failures in staging will prevent some MSIX apps from working properly for the end user. If this check fails, it is non fatal and the machine still can service connections, main issue may be certain apps will not work for end-users. */ export type HealthCheckName = string; /** Known values of {@link HealthCheckResult} that the service accepts. */ export enum KnownHealthCheckResult { /** Health check result is not currently known. */ Unknown = "Unknown", /** Health check passed. */ HealthCheckSucceeded = "HealthCheckSucceeded", /** Health check failed. */ HealthCheckFailed = "HealthCheckFailed", /** We received a Shutdown notification. */ SessionHostShutdown = "SessionHostShutdown" } /** * Defines values for HealthCheckResult. \ * {@link KnownHealthCheckResult} can be used interchangeably with HealthCheckResult, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Unknown**: Health check result is not currently known. \ * **HealthCheckSucceeded**: Health check passed. \ * **HealthCheckFailed**: Health check failed. \ * **SessionHostShutdown**: We received a Shutdown notification. */ export type HealthCheckResult = string; /** Known values of {@link PrivateEndpointServiceConnectionStatus} that the service accepts. */ export enum KnownPrivateEndpointServiceConnectionStatus { Pending = "Pending", Approved = "Approved", Rejected = "Rejected" } /** * Defines values for PrivateEndpointServiceConnectionStatus. \ * {@link KnownPrivateEndpointServiceConnectionStatus} can be used interchangeably with PrivateEndpointServiceConnectionStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Approved** \ * **Rejected** */ export type PrivateEndpointServiceConnectionStatus = string; /** Known values of {@link PrivateEndpointConnectionProvisioningState} that the service accepts. */ export enum KnownPrivateEndpointConnectionProvisioningState { Succeeded = "Succeeded", Creating = "Creating", Deleting = "Deleting", Failed = "Failed" } /** * Defines values for PrivateEndpointConnectionProvisioningState. \ * {@link KnownPrivateEndpointConnectionProvisioningState} can be used interchangeably with PrivateEndpointConnectionProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Succeeded** \ * **Creating** \ * **Deleting** \ * **Failed** */ export type PrivateEndpointConnectionProvisioningState = string; /** Defines values for SkuTier. */ export type SkuTier = "Free" | "Basic" | "Standard" | "Premium"; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = ResourceProviderOperationList; /** Optional parameters. */ export interface OperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OperationsListNextResponse = ResourceProviderOperationList; /** Optional parameters. */ export interface WorkspacesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type WorkspacesGetResponse = Workspace; /** Optional parameters. */ export interface WorkspacesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type WorkspacesCreateOrUpdateResponse = Workspace; /** Optional parameters. */ export interface WorkspacesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface WorkspacesUpdateOptionalParams extends coreClient.OperationOptions { /** Object containing Workspace definitions. */ workspace?: WorkspacePatch; } /** Contains response data for the update operation. */ export type WorkspacesUpdateResponse = Workspace; /** Optional parameters. */ export interface WorkspacesListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type WorkspacesListByResourceGroupResponse = WorkspaceList; /** Optional parameters. */ export interface WorkspacesListBySubscriptionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscription operation. */ export type WorkspacesListBySubscriptionResponse = WorkspaceList; /** Optional parameters. */ export interface WorkspacesListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type WorkspacesListByResourceGroupNextResponse = WorkspaceList; /** Optional parameters. */ export interface WorkspacesListBySubscriptionNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscriptionNext operation. */ export type WorkspacesListBySubscriptionNextResponse = WorkspaceList; /** Optional parameters. */ export interface ScalingPlansGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ScalingPlansGetResponse = ScalingPlan; /** Optional parameters. */ export interface ScalingPlansCreateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the create operation. */ export type ScalingPlansCreateResponse = ScalingPlan; /** Optional parameters. */ export interface ScalingPlansDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface ScalingPlansUpdateOptionalParams extends coreClient.OperationOptions { /** Object containing scaling plan definitions. */ scalingPlan?: ScalingPlanPatch; } /** Contains response data for the update operation. */ export type ScalingPlansUpdateResponse = ScalingPlan; /** Optional parameters. */ export interface ScalingPlansListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type ScalingPlansListByResourceGroupResponse = ScalingPlanList; /** Optional parameters. */ export interface ScalingPlansListBySubscriptionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscription operation. */ export type ScalingPlansListBySubscriptionResponse = ScalingPlanList; /** Optional parameters. */ export interface ScalingPlansListByHostPoolOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByHostPool operation. */ export type ScalingPlansListByHostPoolResponse = ScalingPlanList; /** Optional parameters. */ export interface ScalingPlansListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type ScalingPlansListByResourceGroupNextResponse = ScalingPlanList; /** Optional parameters. */ export interface ScalingPlansListBySubscriptionNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscriptionNext operation. */ export type ScalingPlansListBySubscriptionNextResponse = ScalingPlanList; /** Optional parameters. */ export interface ScalingPlansListByHostPoolNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByHostPoolNext operation. */ export type ScalingPlansListByHostPoolNextResponse = ScalingPlanList; /** Optional parameters. */ export interface ApplicationGroupsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ApplicationGroupsGetResponse = ApplicationGroup; /** Optional parameters. */ export interface ApplicationGroupsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type ApplicationGroupsCreateOrUpdateResponse = ApplicationGroup; /** Optional parameters. */ export interface ApplicationGroupsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface ApplicationGroupsUpdateOptionalParams extends coreClient.OperationOptions { /** Object containing ApplicationGroup definitions. */ applicationGroup?: ApplicationGroupPatch; } /** Contains response data for the update operation. */ export type ApplicationGroupsUpdateResponse = ApplicationGroup; /** Optional parameters. */ export interface ApplicationGroupsListByResourceGroupOptionalParams extends coreClient.OperationOptions { /** OData filter expression. Valid properties for filtering are applicationGroupType. */ filter?: string; } /** Contains response data for the listByResourceGroup operation. */ export type ApplicationGroupsListByResourceGroupResponse = ApplicationGroupList; /** Optional parameters. */ export interface ApplicationGroupsListBySubscriptionOptionalParams extends coreClient.OperationOptions { /** OData filter expression. Valid properties for filtering are applicationGroupType. */ filter?: string; } /** Contains response data for the listBySubscription operation. */ export type ApplicationGroupsListBySubscriptionResponse = ApplicationGroupList; /** Optional parameters. */ export interface ApplicationGroupsListByResourceGroupNextOptionalParams extends coreClient.OperationOptions { /** OData filter expression. Valid properties for filtering are applicationGroupType. */ filter?: string; } /** Contains response data for the listByResourceGroupNext operation. */ export type ApplicationGroupsListByResourceGroupNextResponse = ApplicationGroupList; /** Optional parameters. */ export interface ApplicationGroupsListBySubscriptionNextOptionalParams extends coreClient.OperationOptions { /** OData filter expression. Valid properties for filtering are applicationGroupType. */ filter?: string; } /** Contains response data for the listBySubscriptionNext operation. */ export type ApplicationGroupsListBySubscriptionNextResponse = ApplicationGroupList; /** Optional parameters. */ export interface StartMenuItemsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type StartMenuItemsListResponse = StartMenuItemList; /** Optional parameters. */ export interface StartMenuItemsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type StartMenuItemsListNextResponse = StartMenuItemList; /** Optional parameters. */ export interface ApplicationsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ApplicationsGetResponse = Application; /** Optional parameters. */ export interface ApplicationsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type ApplicationsCreateOrUpdateResponse = Application; /** Optional parameters. */ export interface ApplicationsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface ApplicationsUpdateOptionalParams extends coreClient.OperationOptions { /** Object containing Application definitions. */ application?: ApplicationPatch; } /** Contains response data for the update operation. */ export type ApplicationsUpdateResponse = Application; /** Optional parameters. */ export interface ApplicationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type ApplicationsListResponse = ApplicationList; /** Optional parameters. */ export interface ApplicationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type ApplicationsListNextResponse = ApplicationList; /** Optional parameters. */ export interface DesktopsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type DesktopsGetResponse = Desktop; /** Optional parameters. */ export interface DesktopsUpdateOptionalParams extends coreClient.OperationOptions { /** Object containing Desktop definitions. */ desktop?: DesktopPatch; } /** Contains response data for the update operation. */ export type DesktopsUpdateResponse = Desktop; /** Optional parameters. */ export interface DesktopsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type DesktopsListResponse = DesktopList; /** Optional parameters. */ export interface DesktopsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type DesktopsListNextResponse = DesktopList; /** Optional parameters. */ export interface HostPoolsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type HostPoolsGetResponse = HostPool; /** Optional parameters. */ export interface HostPoolsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type HostPoolsCreateOrUpdateResponse = HostPool; /** Optional parameters. */ export interface HostPoolsDeleteOptionalParams extends coreClient.OperationOptions { /** Force flag to delete sessionHost. */ force?: boolean; } /** Optional parameters. */ export interface HostPoolsUpdateOptionalParams extends coreClient.OperationOptions { /** Object containing HostPool definitions. */ hostPool?: HostPoolPatch; } /** Contains response data for the update operation. */ export type HostPoolsUpdateResponse = HostPool; /** Optional parameters. */ export interface HostPoolsListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type HostPoolsListByResourceGroupResponse = HostPoolList; /** Optional parameters. */ export interface HostPoolsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type HostPoolsListResponse = HostPoolList; /** Optional parameters. */ export interface HostPoolsRetrieveRegistrationTokenOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the retrieveRegistrationToken operation. */ export type HostPoolsRetrieveRegistrationTokenResponse = RegistrationInfo; /** Optional parameters. */ export interface HostPoolsListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type HostPoolsListByResourceGroupNextResponse = HostPoolList; /** Optional parameters. */ export interface HostPoolsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type HostPoolsListNextResponse = HostPoolList; /** Optional parameters. */ export interface UserSessionsListByHostPoolOptionalParams extends coreClient.OperationOptions { /** OData filter expression. Valid properties for filtering are userprincipalname and sessionstate. */ filter?: string; } /** Contains response data for the listByHostPool operation. */ export type UserSessionsListByHostPoolResponse = UserSessionList; /** Optional parameters. */ export interface UserSessionsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type UserSessionsGetResponse = UserSession; /** Optional parameters. */ export interface UserSessionsDeleteOptionalParams extends coreClient.OperationOptions { /** Force flag to login off userSession. */ force?: boolean; } /** Optional parameters. */ export interface UserSessionsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type UserSessionsListResponse = UserSessionList; /** Optional parameters. */ export interface UserSessionsDisconnectOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface UserSessionsSendMessageOptionalParams extends coreClient.OperationOptions { /** Object containing message includes title and message body */ sendMessage?: SendMessage; } /** Optional parameters. */ export interface UserSessionsListByHostPoolNextOptionalParams extends coreClient.OperationOptions { /** OData filter expression. Valid properties for filtering are userprincipalname and sessionstate. */ filter?: string; } /** Contains response data for the listByHostPoolNext operation. */ export type UserSessionsListByHostPoolNextResponse = UserSessionList; /** Optional parameters. */ export interface UserSessionsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type UserSessionsListNextResponse = UserSessionList; /** Optional parameters. */ export interface SessionHostsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type SessionHostsGetResponse = SessionHost; /** Optional parameters. */ export interface SessionHostsDeleteOptionalParams extends coreClient.OperationOptions { /** Force flag to force sessionHost deletion even when userSession exists. */ force?: boolean; } /** Optional parameters. */ export interface SessionHostsUpdateOptionalParams extends coreClient.OperationOptions { /** Force flag to update assign, unassign or reassign personal desktop. */ force?: boolean; /** Object containing SessionHost definitions. */ sessionHost?: SessionHostPatch; } /** Contains response data for the update operation. */ export type SessionHostsUpdateResponse = SessionHost; /** Optional parameters. */ export interface SessionHostsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type SessionHostsListResponse = SessionHostList; /** Optional parameters. */ export interface SessionHostsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type SessionHostsListNextResponse = SessionHostList; /** Optional parameters. */ export interface MsixPackagesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type MsixPackagesGetResponse = MsixPackage; /** Optional parameters. */ export interface MsixPackagesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type MsixPackagesCreateOrUpdateResponse = MsixPackage; /** Optional parameters. */ export interface MsixPackagesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MsixPackagesUpdateOptionalParams extends coreClient.OperationOptions { /** Object containing MSIX Package definitions. */ msixPackage?: MsixPackagePatch; } /** Contains response data for the update operation. */ export type MsixPackagesUpdateResponse = MsixPackage; /** Optional parameters. */ export interface MsixPackagesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type MsixPackagesListResponse = MsixPackageList; /** Optional parameters. */ export interface MsixPackagesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type MsixPackagesListNextResponse = MsixPackageList; /** Optional parameters. */ export interface MsixImagesExpandOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the expand operation. */ export type MsixImagesExpandResponse = ExpandMsixImageList; /** Optional parameters. */ export interface MsixImagesExpandNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the expandNext operation. */ export type MsixImagesExpandNextResponse = ExpandMsixImageList; /** Optional parameters. */ export interface PrivateEndpointConnectionsListByHostPoolOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByHostPool operation. */ export type PrivateEndpointConnectionsListByHostPoolResponse = PrivateEndpointConnectionListResultWithSystemData; /** Optional parameters. */ export interface PrivateEndpointConnectionsGetByHostPoolOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getByHostPool operation. */ export type PrivateEndpointConnectionsGetByHostPoolResponse = PrivateEndpointConnectionWithSystemData; /** Optional parameters. */ export interface PrivateEndpointConnectionsDeleteByHostPoolOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface PrivateEndpointConnectionsUpdateByHostPoolOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the updateByHostPool operation. */ export type PrivateEndpointConnectionsUpdateByHostPoolResponse = PrivateEndpointConnectionWithSystemData; /** Optional parameters. */ export interface PrivateEndpointConnectionsListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type PrivateEndpointConnectionsListByWorkspaceResponse = PrivateEndpointConnectionListResultWithSystemData; /** Optional parameters. */ export interface PrivateEndpointConnectionsGetByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getByWorkspace operation. */ export type PrivateEndpointConnectionsGetByWorkspaceResponse = PrivateEndpointConnectionWithSystemData; /** Optional parameters. */ export interface PrivateEndpointConnectionsDeleteByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface PrivateEndpointConnectionsUpdateByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the updateByWorkspace operation. */ export type PrivateEndpointConnectionsUpdateByWorkspaceResponse = PrivateEndpointConnectionWithSystemData; /** Optional parameters. */ export interface PrivateEndpointConnectionsListByHostPoolNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByHostPoolNext operation. */ export type PrivateEndpointConnectionsListByHostPoolNextResponse = PrivateEndpointConnectionListResultWithSystemData; /** Optional parameters. */ export interface PrivateEndpointConnectionsListByWorkspaceNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspaceNext operation. */ export type PrivateEndpointConnectionsListByWorkspaceNextResponse = PrivateEndpointConnectionListResultWithSystemData; /** Optional parameters. */ export interface PrivateLinkResourcesListByHostPoolOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByHostPool operation. */ export type PrivateLinkResourcesListByHostPoolResponse = PrivateLinkResourceListResult; /** Optional parameters. */ export interface PrivateLinkResourcesListByWorkspaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspace operation. */ export type PrivateLinkResourcesListByWorkspaceResponse = PrivateLinkResourceListResult; /** Optional parameters. */ export interface PrivateLinkResourcesListByHostPoolNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByHostPoolNext operation. */ export type PrivateLinkResourcesListByHostPoolNextResponse = PrivateLinkResourceListResult; /** Optional parameters. */ export interface PrivateLinkResourcesListByWorkspaceNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByWorkspaceNext operation. */ export type PrivateLinkResourcesListByWorkspaceNextResponse = PrivateLinkResourceListResult; /** Optional parameters. */ export interface DesktopVirtualizationAPIClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
module labelling_tool { /* Polygonal label model */ interface PolygonalLabelModel extends AbstractLabelModel { vertices: Vector2[]; } function new_PolygonalLabelModel(): PolygonalLabelModel { return {label_type: 'polygon', label_class: null, vertices: []}; } /* Polygonal label entity */ export class PolygonalLabelEntity extends AbstractLabelEntity<PolygonalLabelModel> { _polyk_poly: number[]; _centroid: Vector2; _bounding_box: AABox; poly: any; shape_line: any; constructor(view: RootLabelView, model: PolygonalLabelModel) { super(view, model); this._polyk_poly = []; this._centroid = null; this._bounding_box = null; this.poly = null; this.shape_line = null; } attach() { super.attach(); this.shape_line = d3.svg.line() .x(function (d: any) { return d.x; }) .y(function (d: any) { return d.y; }) .interpolate("linear-closed"); this.poly = this.root_view.world.append("path"); this.poly.data(this.model.vertices).attr("d", this.shape_line(this.model.vertices)); this.poly.on("mouseover", () => { for (var i = 0; i < this._event_listeners.length; i++) { this._event_listeners[i].on_mouse_in(this); } }); this.poly.on("mouseout", () => { for (var i = 0; i < this._event_listeners.length; i++) { this._event_listeners[i].on_mouse_out(this); } }); this._update_polyk_poly(); this._update_style(); }; detach() { this.poly.remove(); this.poly = null; this.shape_line = null; this._polyk_poly = []; super.detach(); }; _update_polyk_poly() { this._polyk_poly = []; for (var i = 0; i < this.model.vertices.length; i++) { this._polyk_poly.push(this.model.vertices[i].x); this._polyk_poly.push(this.model.vertices[i].y); } } update() { this.poly.data(this.model.vertices).attr("d", this.shape_line(this.model.vertices)); this._update_polyk_poly(); this._centroid = null; this._bounding_box = null; } commit() { this.root_view.commit_model(this.model); } _update_style() { if (this._attached) { var stroke_colour: Colour4 = this._outline_colour(); if (this.root_view.view.label_visibility == LabelVisibility.HIDDEN) { this.poly.attr("visibility", "hidden"); } else { var fill_colour: Colour4 = this.root_view.view.colour_for_label_class(this.model.label_class); if (this.root_view.view.label_visibility == LabelVisibility.FAINT) { stroke_colour = stroke_colour.with_alpha(0.2); if (this._hover) { fill_colour = fill_colour.lighten(0.4); } if (this._selected) { fill_colour = fill_colour.lerp(new Colour4(255, 128, 0.0, 1.0), 0.2); } fill_colour = fill_colour.with_alpha(0.1); } else if (this.root_view.view.label_visibility == LabelVisibility.FULL) { if (this._hover) { fill_colour = fill_colour.lighten(0.4); } if (this._selected) { fill_colour = fill_colour.lerp(new Colour4(255, 128, 0.0, 1.0), 0.2); } fill_colour = fill_colour.with_alpha(0.35); } this.poly.attr("style", "fill:" + fill_colour.to_rgba_string() + ";stroke:" + stroke_colour.to_rgba_string() + ";stroke-width:1") .attr("visibility", "visible"); } } } compute_centroid(): Vector2 { if (this._centroid === null) { this._centroid = compute_centroid_of_points(this.model.vertices); } return this._centroid; } compute_bounding_box(): AABox { if (this._bounding_box === null) { this._bounding_box = AABox_from_points(this.model.vertices); } return this._bounding_box; } contains_pointer_position(point: Vector2): boolean { if (this.compute_bounding_box().contains_point(point)) { return PolyK.ContainsPoint(this._polyk_poly, point.x, point.y); } else { return false; } } distance_to_point(point: Vector2): number { if (PolyK.ContainsPoint(this._polyk_poly, point.x, point.y)) { return 0.0; } else { var e = PolyK.ClosestEdge(this._polyk_poly, point.x, point.y); return e.dist; } } } register_entity_factory('polygon', (root_view: RootLabelView, model: AbstractLabelModel) => { return new PolygonalLabelEntity(root_view, model as PolygonalLabelModel); }); /* Draw polygon tool */ export class DrawPolygonTool extends AbstractTool { entity: PolygonalLabelEntity; _last_vertex_marker: any; _last_vertex_marker_visible: boolean; _key_event_listener: (event: any)=>any; constructor(view: RootLabelView, entity: PolygonalLabelEntity) { super(view); var self = this; this.entity = entity; this._last_vertex_marker = null; this._key_event_listener = function(event) { self.on_key_press(event); } } on_init() { this._last_vertex_marker = this._view.world.append("circle"); this._last_vertex_marker.attr("r", "3.0"); this._last_vertex_marker.attr("visibility", "hidden"); this._last_vertex_marker.style("fill", "rgba(128,0,192,0.1)"); this._last_vertex_marker.style("stroke-width", "1.0"); this._last_vertex_marker.style("stroke", "rgba(192,0,255,1.0)"); this._last_vertex_marker_visible = false; }; on_shutdown() { this._last_vertex_marker.remove(); this._last_vertex_marker = null; }; on_switch_in(pos: Vector2) { if (this.entity !== null) { this.add_point(pos); this._last_vertex_marker_visible = true; } document.addEventListener("keypress", this._key_event_listener); }; on_switch_out(pos: Vector2) { this._last_vertex_marker_visible = false; if (this.entity !== null) { this.remove_last_point(); this.entity.commit(); } document.removeEventListener("keypress", this._key_event_listener); }; on_key_press(event: any) { var key: string = event.key; if (key === ',') { // Shift vertices back var vertices = this.get_vertices(); if (vertices !== null && vertices.length >= 3) { var last_vertex = vertices[vertices.length - 2]; // Remove the last vertex vertices.splice(vertices.length - 2, 1); // Insert the last vertex at the beginning vertices.splice(0, 0, last_vertex); this.update_poly(); this.entity.commit(); } } else if (key == '.') { // Shift vertices forward var vertices = this.get_vertices(); if (vertices !== null && vertices.length >= 3) { var first_vertex = vertices[0]; // Remove the first vertex vertices.splice(0, 1); // Insert the first vertex at the end, before the current vertex vertices.splice(vertices.length - 1, 0, first_vertex); this.update_poly(); this.entity.commit(); } } else if (key == '/') { var vertices = this.get_vertices(); if (vertices !== null && vertices.length >= 3) { // Remove the last vertex vertices.splice(vertices.length - 2, 1); this.update_poly(); this.entity.commit(); } } } on_cancel(pos: Vector2): boolean { if (this.entity !== null) { this._last_vertex_marker_visible = false; this.remove_last_point(); var vertices = this.get_vertices(); if (vertices.length == 1) { this.destroy_entity(); } else { this.entity.commit(); this.entity = null; } } else { this._view.unselect_all_entities(); this._view.view.set_current_tool(new SelectEntityTool(this._view)); } return true; }; on_left_click(pos: Vector2, event: any) { this.add_point(pos); }; on_move(pos: Vector2) { this.update_last_point(pos); }; create_entity() { var model = new_PolygonalLabelModel(); var entity = this._view.get_or_create_entity_for_model(model); this.entity = entity; // Freeze to prevent this temporary change from being sent to the backend this._view.view.freeze(); this._view.add_child(entity); this._view.select_entity(entity, false, false); this._view.view.thaw(); }; destroy_entity() { // Freeze to prevent this temporary change from being sent to the backend this._view.view.freeze(); this.entity.destroy(); this.entity = null; this._view.view.thaw(); }; get_vertices() { return this.entity !== null ? this.entity.model.vertices : null; }; update_poly() { var last_vertex_pos: Vector2 = null; if (this.entity !== null) { this.entity.update(); var vertices = this.get_vertices(); if (vertices.length >= 2 && this._last_vertex_marker_visible) { var last_vertex_pos = vertices[vertices.length - 2]; } } this.show_last_vertex_at(last_vertex_pos); }; show_last_vertex_at(pos: Vector2) { if (pos === null) { this._last_vertex_marker.attr("visibility", "hidden"); } else { this._last_vertex_marker.attr("visibility", "visible"); this._last_vertex_marker.attr("cx", pos.x); this._last_vertex_marker.attr("cy", pos.y); } } add_point(pos: Vector2) { var entity_is_new = false; if (this.entity === null) { this.create_entity(); entity_is_new = true; } var vertices = this.get_vertices(); if (entity_is_new) { // Add a duplicate vertex; this second vertex will follow the mouse vertices.push(pos); } vertices.push(pos); this.update_poly(); }; update_last_point(pos: Vector2) { var vertices = this.get_vertices(); if (vertices !== null) { vertices[vertices.length - 1] = pos; this.update_poly(); } }; remove_last_point() { var vertices = this.get_vertices(); if (vertices !== null) { if (vertices.length > 0) { vertices.splice(vertices.length - 1, 1); this.update_poly(); } if (vertices.length === 0) { this.destroy_entity(); } } }; } }
the_stack
import { PendingPlugins, Plugin, PluginCollection } from "@scm-manager/ui-types"; import createInfiniteCachingClient from "./tests/createInfiniteCachingClient"; import { setIndexLink } from "./tests/indexLinks"; import fetchMock from "fetch-mock-jest"; import { renderHook } from "@testing-library/react-hooks"; import createWrapper from "./tests/createWrapper"; import { useAvailablePlugins, useInstalledPlugins, useInstallPlugin, usePendingPlugins, useUninstallPlugin, useUpdatePlugins, } from "./plugins"; import { act } from "react-test-renderer"; describe("Test plugin hooks", () => { const availablePlugin: Plugin = { author: "Douglas Adams", category: "all", displayName: "Heart of Gold", version: "x.y.z", name: "heart-of-gold-plugin", pending: false, dependencies: [], optionalDependencies: [], type: "SCM", _links: { install: { href: "/plugins/available/heart-of-gold-plugin/install" }, installWithRestart: { href: "/plugins/available/heart-of-gold-plugin/install?restart=true", }, }, }; const installedPlugin: Plugin = { author: "Douglas Adams", category: "all", displayName: "Heart of Gold", version: "x.y.z", name: "heart-of-gold-plugin", pending: false, markedForUninstall: false, dependencies: [], optionalDependencies: [], type: "SCM", _links: { self: { href: "/plugins/installed/heart-of-gold-plugin", }, update: { href: "/plugins/available/heart-of-gold-plugin/install", }, updateWithRestart: { href: "/plugins/available/heart-of-gold-plugin/install?restart=true", }, uninstall: { href: "/plugins/installed/heart-of-gold-plugin/uninstall", }, uninstallWithRestart: { href: "/plugins/installed/heart-of-gold-plugin/uninstall?restart=true", }, }, }; const installedCorePlugin: Plugin = { author: "Douglas Adams", category: "all", displayName: "Heart of Gold", version: "x.y.z", name: "heart-of-gold-core-plugin", pending: false, markedForUninstall: false, type: "SCM", dependencies: [], optionalDependencies: [], _links: { self: { href: "/plugins/installed/heart-of-gold-core-plugin", }, }, }; const createPluginCollection = (plugins: Plugin[]): PluginCollection => ({ _links: { update: { href: "/plugins/update", }, }, _embedded: { plugins, }, }); const createPendingPlugins = ( newPlugins: Plugin[] = [], updatePlugins: Plugin[] = [], uninstallPlugins: Plugin[] = [] ): PendingPlugins => ({ _links: {}, _embedded: { new: newPlugins, update: updatePlugins, uninstall: uninstallPlugins, }, }); afterEach(() => fetchMock.reset()); describe("useAvailablePlugins tests", () => { it("should return availablePlugins", async () => { const availablePlugins = createPluginCollection([availablePlugin]); const queryClient = createInfiniteCachingClient(); setIndexLink(queryClient, "availablePlugins", "/availablePlugins"); fetchMock.get("/api/v2/availablePlugins", availablePlugins); const { result, waitFor } = renderHook(() => useAvailablePlugins(), { wrapper: createWrapper(undefined, queryClient), }); await waitFor(() => !!result.current.data); expect(result.current.data).toEqual(availablePlugins); }); }); describe("useInstalledPlugins tests", () => { it("should return installedPlugins", async () => { const installedPlugins = createPluginCollection([installedPlugin, installedCorePlugin]); const queryClient = createInfiniteCachingClient(); setIndexLink(queryClient, "installedPlugins", "/installedPlugins"); fetchMock.get("/api/v2/installedPlugins", installedPlugins); const { result, waitFor } = renderHook(() => useInstalledPlugins(), { wrapper: createWrapper(undefined, queryClient), }); await waitFor(() => !!result.current.data); expect(result.current.data).toEqual(installedPlugins); }); }); describe("usePendingPlugins tests", () => { it("should return pendingPlugins", async () => { const pendingPlugins = createPendingPlugins([availablePlugin]); const queryClient = createInfiniteCachingClient(); setIndexLink(queryClient, "pendingPlugins", "/pendingPlugins"); fetchMock.get("/api/v2/pendingPlugins", pendingPlugins); const { result, waitFor } = renderHook(() => usePendingPlugins(), { wrapper: createWrapper(undefined, queryClient), }); await waitFor(() => !!result.current.data); expect(result.current.data).toEqual(pendingPlugins); }); }); describe("useInstallPlugin tests", () => { it("should use restart parameter", async () => { const queryClient = createInfiniteCachingClient(); queryClient.setQueryData(["plugins", "available"], createPluginCollection([availablePlugin])); queryClient.setQueryData(["plugins", "installed"], createPluginCollection([])); queryClient.setQueryData(["plugins", "pending"], createPendingPlugins()); fetchMock.post("/api/v2/plugins/available/heart-of-gold-plugin/install?restart=true", installedPlugin); fetchMock.get("/api/v2/", "Restarted"); const { result, waitFor, waitForNextUpdate } = renderHook(() => useInstallPlugin(), { wrapper: createWrapper(undefined, queryClient), }); await act(() => { const { install } = result.current; install(availablePlugin, { restart: true, initialDelay: 5, timeout: 5 }); return waitForNextUpdate(); }); await waitFor(() => result.current.isInstalled); expect(queryClient.getQueryState(["plugins", "available"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "installed"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "pending"])!.isInvalidated).toBe(true); }); it("should invalidate query keys", async () => { const queryClient = createInfiniteCachingClient(); queryClient.setQueryData(["plugins", "available"], createPluginCollection([availablePlugin])); queryClient.setQueryData(["plugins", "installed"], createPluginCollection([])); queryClient.setQueryData(["plugins", "pending"], createPendingPlugins()); fetchMock.post("/api/v2/plugins/available/heart-of-gold-plugin/install", installedPlugin); const { result, waitForNextUpdate } = renderHook(() => useInstallPlugin(), { wrapper: createWrapper(undefined, queryClient), }); await act(() => { const { install } = result.current; install(availablePlugin); return waitForNextUpdate(); }); expect(queryClient.getQueryState(["plugins", "available"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "installed"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "pending"])!.isInvalidated).toBe(true); }); }); describe("useUninstallPlugin tests", () => { it("should use restart parameter", async () => { const queryClient = createInfiniteCachingClient(); queryClient.setQueryData(["plugins", "available"], createPluginCollection([])); queryClient.setQueryData(["plugins", "installed"], createPluginCollection([installedPlugin])); queryClient.setQueryData(["plugins", "pending"], createPendingPlugins()); fetchMock.post("/api/v2/plugins/installed/heart-of-gold-plugin/uninstall?restart=true", availablePlugin); fetchMock.get("/api/v2/", "Restarted"); const { result, waitForNextUpdate, waitFor } = renderHook(() => useUninstallPlugin(), { wrapper: createWrapper(undefined, queryClient), }); await act(() => { const { uninstall } = result.current; uninstall(installedPlugin, { restart: true, initialDelay: 5, timeout: 5 }); return waitForNextUpdate(); }); await waitFor(() => result.current.isUninstalled); expect(queryClient.getQueryState(["plugins", "available"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "installed"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "pending"])!.isInvalidated).toBe(true); }); it("should invalidate query keys", async () => { const queryClient = createInfiniteCachingClient(); queryClient.setQueryData(["plugins", "available"], createPluginCollection([])); queryClient.setQueryData(["plugins", "installed"], createPluginCollection([installedPlugin])); queryClient.setQueryData(["plugins", "pending"], createPendingPlugins()); fetchMock.post("/api/v2/plugins/installed/heart-of-gold-plugin/uninstall", availablePlugin); const { result, waitForNextUpdate } = renderHook(() => useUninstallPlugin(), { wrapper: createWrapper(undefined, queryClient), }); await act(() => { const { uninstall } = result.current; uninstall(installedPlugin); return waitForNextUpdate(); }); expect(queryClient.getQueryState(["plugins", "available"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "installed"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "pending"])!.isInvalidated).toBe(true); }); }); describe("useUpdatePlugins tests", () => { it("should use restart parameter", async () => { const queryClient = createInfiniteCachingClient(); queryClient.setQueryData(["plugins", "available"], createPluginCollection([])); queryClient.setQueryData(["plugins", "installed"], createPluginCollection([installedPlugin])); queryClient.setQueryData(["plugins", "pending"], createPendingPlugins()); fetchMock.post("/api/v2/plugins/available/heart-of-gold-plugin/install?restart=true", installedPlugin); fetchMock.get("/api/v2/", "Restarted"); const { result, waitForNextUpdate, waitFor } = renderHook(() => useUpdatePlugins(), { wrapper: createWrapper(undefined, queryClient), }); await act(() => { const { update } = result.current; update(installedPlugin, { restart: true, timeout: 5, initialDelay: 5 }); return waitForNextUpdate(); }); await waitFor(() => result.current.isUpdated); expect(queryClient.getQueryState(["plugins", "available"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "installed"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "pending"])!.isInvalidated).toBe(true); }); it("should update collection", async () => { const queryClient = createInfiniteCachingClient(); queryClient.setQueryData(["plugins", "available"], createPluginCollection([])); queryClient.setQueryData(["plugins", "installed"], createPluginCollection([installedPlugin])); queryClient.setQueryData(["plugins", "pending"], createPendingPlugins()); fetchMock.post("/api/v2/plugins/update", installedPlugin); const { result, waitForNextUpdate } = renderHook(() => useUpdatePlugins(), { wrapper: createWrapper(undefined, queryClient), }); await act(() => { const { update } = result.current; update(createPluginCollection([installedPlugin, installedCorePlugin])); return waitForNextUpdate(); }); expect(queryClient.getQueryState(["plugins", "available"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "installed"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "pending"])!.isInvalidated).toBe(true); }); it("should ignore restart parameter collection", async () => { const queryClient = createInfiniteCachingClient(); queryClient.setQueryData(["plugins", "available"], createPluginCollection([])); queryClient.setQueryData(["plugins", "installed"], createPluginCollection([installedPlugin])); queryClient.setQueryData(["plugins", "pending"], createPendingPlugins()); fetchMock.post("/api/v2/plugins/update", installedPlugin); const { result, waitForNextUpdate } = renderHook(() => useUpdatePlugins(), { wrapper: createWrapper(undefined, queryClient), }); await act(() => { const { update } = result.current; update(createPluginCollection([installedPlugin, installedCorePlugin]), { restart: true }); return waitForNextUpdate(); }); expect(queryClient.getQueryState(["plugins", "available"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "installed"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "pending"])!.isInvalidated).toBe(true); }); it("should invalidate query keys", async () => { const queryClient = createInfiniteCachingClient(); queryClient.setQueryData(["plugins", "available"], createPluginCollection([])); queryClient.setQueryData(["plugins", "installed"], createPluginCollection([installedPlugin])); queryClient.setQueryData(["plugins", "pending"], createPendingPlugins()); fetchMock.post("/api/v2/plugins/available/heart-of-gold-plugin/install", installedPlugin); const { result, waitForNextUpdate } = renderHook(() => useUpdatePlugins(), { wrapper: createWrapper(undefined, queryClient), }); await act(() => { const { update } = result.current; update(installedPlugin); return waitForNextUpdate(); }); expect(queryClient.getQueryState(["plugins", "available"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "installed"])!.isInvalidated).toBe(true); expect(queryClient.getQueryState(["plugins", "pending"])!.isInvalidated).toBe(true); }); }); });
the_stack
import React from 'react'; import * as settings from 'electron-settings'; import TitleBar from 'frameless-titlebar'; import './style.scss'; import { visualizations } from '../../../../visualizations/visualizations.js'; import { MACOS, DEFAULT_SETTINGS, MAX_BAR_THICKNESS, LINUX } from '../../../../constants'; import { get, set } from 'lodash'; import { remote } from 'electron'; import { Platform } from 'frameless-titlebar/dist/title-bar/typings'; interface Setting { name: string; callback?: (value: any) => void; } class Settings extends React.Component<any, any> { private oldSettings: any; private settingsToWatch: Setting[]; constructor(props: any) { super(props); this.state = { ...settings.getSync(), }; this.oldSettings = {}; this.settingsToWatch = this.initSettingsToWatch(); this.settingsToWatch.map((setting) => { const currentSetting = get(this.state, setting.name) ?? get(DEFAULT_SETTINGS, setting.name); this.oldSettings[setting.name] = currentSetting; }); } initSettingsToWatch() { const mainWindow = remote.getCurrentWindow(); const settingsToWatch: Setting[] = [ { name: 'lofi.window.always_on_top', callback: (value) => mainWindow.setAlwaysOnTop(value), }, { name: 'lofi.window.show_in_taskbar', callback: (value) => { mainWindow.setSkipTaskbar(!value); mainWindow.setFocusable(value); // Workaround to make setSkipTaskbar behave // cf. https://github.com/electron/electron/issues/18378 mainWindow.on('focus', () => { mainWindow.setSkipTaskbar(!value); }); }, }, { name: 'lofi.window.hide' }, { name: 'lofi.window.metadata' }, { name: 'lofi.window.show_progress' }, { name: 'lofi.window.bar_thickness' }, { name: 'lofi.visualization' }, { name: 'hardware_acceleration' }, { name: 'debug', callback: (value) => value ? mainWindow.webContents.openDevTools({ mode: 'detach' }) : mainWindow.webContents.closeDevTools(), }, { name: 'lofi.audio.volume_increment' }, ]; return settingsToWatch; } nukeSettings() { if (!confirm('Are you sure you want to reset all Lofi settings?')) { return; } this.settingsToWatch.map((setting) => { this.setNewSettingsState(setting.name, get(DEFAULT_SETTINGS, setting.name)); settings.setSync(setting.name, get(DEFAULT_SETTINGS, setting.name)); if (setting.callback) { setting.callback(get(DEFAULT_SETTINGS, setting.name)); } }); this.props.lofi.hideSettingsWindow(); this.props.lofi.reloadSettings(); } commitSettings() { if (!this.isFormValid()) { return; } // Commit window settings settings.setSync('lofi.window.always_on_top', this.state.lofi.window.always_on_top); settings.setSync('lofi.window.show_in_taskbar', this.state.lofi.window.show_in_taskbar); settings.setSync('lofi.window.hide', this.state.lofi.window.hide); settings.setSync('lofi.window.metadata', this.state.lofi.window.metadata); settings.setSync('lofi.window.show_progress', this.state.lofi.window.show_progress); settings.setSync('lofi.window.bar_thickness', this.state.lofi.window.bar_thickness); // Commit visualization settings settings.setSync('lofi.visualization', this.state.lofi.visualization); // Commit advanced settings settings.setSync('hardware_acceleration', this.state.hardware_acceleration); settings.setSync('debug', this.state.debug); // Commit audio settings settings.setSync('lofi.audio.volume_increment', this.state.lofi.audio.volume_increment); const changedSettings = this.getChangedSettings(); changedSettings.map((setting) => { if (setting.callback) { setting.callback(get(this.state, setting.name)); } }); // Hide settings window and reload settings in main process this.props.lofi.hideSettingsWindow(); this.props.lofi.reloadSettings(); } setNewSettingsState(fullName: string, newValue: any) { const settings: { [x: string]: any } = this.state; set(settings, fullName, newValue); this.setState(settings); } getChangedSettings() { const currentSettings: { [x: string]: any } = this.state; const changedSettings = this.settingsToWatch.filter( (setting) => this.oldSettings[setting.name] !== get(currentSettings, setting.name) ); return changedSettings; } isFormValid() { const changedSettings = this.getChangedSettings(); if (!changedSettings || changedSettings.length === 0) { return false; } return ( this.state.lofi.audio.volume_increment && this.state.lofi.audio.volume_increment > 0 && this.state.lofi.audio.volume_increment <= 100 && this.state.lofi.window.bar_thickness && this.state.lofi.window.bar_thickness > 0 && this.state.lofi.window.bar_thickness <= MAX_BAR_THICKNESS ); } render() { return ( <div className="settings-wnd"> <TitleBar disableMaximize disableMinimize currentWindow={window} // electron window instance platform={(process.platform as Platform) ?? 'win32'} theme={{ bar: { background: '#0000', borderBottom: '#0000', }, }} onClose={() => this.props.lofi.hideSettingsWindow()} /> <div className="settings-wrapper"> <form className="form-horizontal"> <fieldset> <legend>Window</legend> <div className="form-group"> <div> <input type="checkbox" name="always_on_top" id="always_on_top" onChange={() => this.setNewSettingsState('lofi.window.always_on_top', !this.state.lofi.window.always_on_top) } checked={this.state.lofi.window.always_on_top} /> <label htmlFor="always_on_top">Always on top</label> </div> <div> <input type="checkbox" name="" id="show_in_taskbar" onChange={() => this.setNewSettingsState('lofi.window.show_in_taskbar', !this.state.lofi.window.show_in_taskbar) } checked={this.state.lofi.window.show_in_taskbar} /> <label htmlFor="show_in_taskbar">Display in the task bar</label> </div> <div> <input type="checkbox" name="hide" id="hide" onChange={() => this.setNewSettingsState('lofi.window.hide', !this.state.lofi.window.hide)} checked={this.state.lofi.window.hide} /> <label htmlFor="hide">Hide when Spotify is not detected</label> </div> <div> <input type="checkbox" name="metadata" id="metadata" onChange={() => this.setNewSettingsState('lofi.window.metadata', !this.state.lofi.window.metadata)} checked={this.state.lofi.window.metadata} /> <label htmlFor="metadata">Always show song and artist metadata</label> </div> <div> <input type="checkbox" name="show_progress" id="show_progress" onChange={() => this.setNewSettingsState('lofi.window.show_progress', !this.state.lofi.window.show_progress) } checked={this.state.lofi.window.show_progress} /> <label htmlFor="show_progress">Always show song progress</label> </div> </div> <div> <input type="number" min="1" max={MAX_BAR_THICKNESS} name="bar_thickness" id="bar_thickness" onChange={(e) => this.setNewSettingsState('lofi.window.bar_thickness', e.target.value)} value={this.state.lofi.window.bar_thickness} /> <label htmlFor="bar_thickness">Progress and volume bars thickness</label> </div> </fieldset> <fieldset> <legend>Visualization</legend> <div className="form-group"> <div> <select disabled={MACOS} value={this.state.lofi.visualization} className="picker" onChange={(e) => this.setNewSettingsState('lofi.visualization', Number(e.target.value))}> {visualizations.map((vis, idx) => ( <option key={idx} value={idx}> {vis.name} </option> ))} ; </select> </div> </div> </fieldset> <fieldset> <legend>Audio</legend> <div className="form-group"> <div> <input type="number" min="1" max="100" name="volume_increment" id="volume_increment" onChange={(e) => this.setNewSettingsState('lofi.audio.volume_increment', e.target.value)} value={this.state.lofi.audio.volume_increment} /> <label htmlFor="volume_increment">Scroll wheel volume increment</label> </div> </div> </fieldset> <fieldset> <legend>Advanced</legend> <div className="form-group"> {LINUX ? ( // FIXME Linux gpu support is always disabled, see cf. https://github.com/dvx/lofi/issues/149 '' ) : ( <div> <input type="checkbox" name="hardware_acceleration" id="hardware_acceleration" onChange={() => this.setNewSettingsState('hardware_acceleration', !this.state.hardware_acceleration) } checked={this.state.hardware_acceleration} /> <label htmlFor="hardware_acceleration">Use hardware acceleration (requires restart)</label> </div> )} <div> <input type="checkbox" name="debug" id="debug" onChange={(e) => this.setNewSettingsState('debug', !this.state.debug)} checked={this.state.debug} /> <label htmlFor="debug">Debug mode</label> </div> </div> </fieldset> </form> <div className="button-container"> <div className="button-holder"> <a href="#" onClick={this.nukeSettings.bind(this)} className="red-button"> Reset to defaults </a> </div> <div className="button-holder"> <a href="#" onClick={this.commitSettings.bind(this)} className={`${this.isFormValid() ? 'green-button' : 'button-disabled'}`}> Save </a> </div> </div> </div> </div> ); } } export default Settings;
the_stack
import React, { useLayoutEffect, MouseEvent } from 'react' import ButtonBase from '@mui/material/ButtonBase' import List, { ListProps } from '@mui/material/List' import ListItem, { ListItemProps } from '@mui/material/ListItem' import ListItemIcon from '@mui/material/ListItemIcon' import ListItemSecondaryAction from '@mui/material/ListItemSecondaryAction' import ListItemText from '@mui/material/ListItemText' import Typography from '@mui/material/Typography' import { DragDropContext, Droppable, Draggable, DropResult, DraggableStateSnapshot, DraggableProvided, DroppableProvided, } from 'react-beautiful-dnd' import ListSubheader from '@mui/material/ListSubheader' import AppLink from '../util/AppLink' import makeStyles from '@mui/styles/makeStyles' import { CSSTransition, TransitionGroup } from 'react-transition-group' import { Alert, AlertTitle } from '@mui/material' import { AlertColor } from '@mui/material/Alert' import classnames from 'classnames' import { Notice, NoticeType } from '../details/Notices' const lime = '#93ed94' const lightLime = '#defadf' const lightGrey = '#ebebeb' const useStyles = makeStyles({ alert: { margin: '0.5rem 0 0.5rem 0', width: '100%', }, alertAsButton: { width: '100%', '&:hover, &.Mui-focusVisible': { filter: 'brightness(90%)', }, }, buttonBase: { borderRadius: 4, }, background: { backgroundColor: 'white' }, highlightedItem: { borderLeft: '6px solid ' + lime, background: lightLime, }, participantDragging: { backgroundColor: lightGrey, }, slideEnter: { maxHeight: '0px', opacity: 0, transform: 'translateX(-100%)', }, slideEnterActive: { maxHeight: '60px', opacity: 1, transform: 'translateX(0%)', transition: 'all 500ms', }, slideExit: { maxHeight: '60px', opacity: 1, transform: 'translateX(0%)', }, slideExitActive: { maxHeight: '0px', opacity: 0, transform: 'translateX(-100%)', transition: 'all 500ms', }, listItem: { width: '100%', }, listItemText: { fontStyle: 'italic', }, listItemDisabled: { opacity: 0.6, width: '100%', }, }) export interface FlatListSub { id?: string subHeader: string } export interface FlatListNotice extends Notice { id?: string icon?: JSX.Element transition?: boolean handleOnClick?: (event: MouseEvent) => void 'data-cy'?: string } export interface FlatListItem { title?: string highlight?: boolean subText?: JSX.Element | string icon?: JSX.Element | null secondaryAction?: JSX.Element | null url?: string id?: string scrollIntoView?: boolean 'data-cy'?: string disabled?: boolean } export type FlatListListItem = FlatListSub | FlatListItem | FlatListNotice export interface FlatListProps extends ListProps { items: FlatListListItem[] // header elements will be displayed at the top of the list. headerNote?: string // left-aligned headerAction?: JSX.Element // right-aligned // emptyMessage will be displayed if there are no items in the list. emptyMessage?: string // indent text of each list item if no icon is present inset?: boolean // If specified, enables drag and drop // // onReorder(id, oldIndex, newIndex) onReorder?: (oldIndex: number, newIndex: number) => void // will render transition in list transition?: boolean } const severityMap: { [K in NoticeType]: AlertColor } = { INFO: 'info', WARNING: 'warning', ERROR: 'error', OK: 'success', } interface ScrollIntoViewListItemProps extends ListItemProps { scrollIntoView?: boolean } function ScrollIntoViewListItem( props: ScrollIntoViewListItemProps, ): JSX.Element { const { scrollIntoView, ...other } = props const ref = React.useRef<HTMLLIElement>(null) useLayoutEffect(() => { if (scrollIntoView) { ref.current?.scrollIntoView({ block: 'center' }) } }, [scrollIntoView]) return <ListItem ref={ref} {...other} /> } export default function FlatList({ onReorder, emptyMessage, headerNote, headerAction, items, inset, transition, ...listProps }: FlatListProps): JSX.Element { const classes = useStyles() function handleDragStart(): void { // adds a little vibration if the browser supports it if (window.navigator.vibrate) { window.navigator.vibrate(100) } } function handleDragEnd(result: DropResult): void { if (result.destination && onReorder) { onReorder(result.source.index, result.destination.index) } } function renderNoticeItem(item: FlatListNotice, idx: number): JSX.Element { if (item.handleOnClick) { return ( <ButtonBase className={classnames(classes.buttonBase, classes.alert)} onClick={item.handleOnClick} data-cy={item['data-cy']} > <Alert className={classes.alertAsButton} key={idx} severity={severityMap[item.type]} icon={item.icon} > {item.message && <AlertTitle>{item.message}</AlertTitle>} {item.details} </Alert> </ButtonBase> ) } return ( <Alert key={idx} className={classes.alert} severity={severityMap[item.type]} icon={item.icon} > {item.message && <AlertTitle>{item.message}</AlertTitle>} {item.details} </Alert> ) } function renderSubheaderItem(item: FlatListSub, idx: number): JSX.Element { return ( <ListSubheader key={idx} className={classes.background}> <Typography component='h2' variant='subtitle1' color='textSecondary' data-cy='flat-list-item-subheader' > {item.subHeader} </Typography> </ListSubheader> ) } function renderItem(item: FlatListItem, idx: number): JSX.Element { let itemProps = {} if (item.url) { itemProps = { component: AppLink, to: item.url, button: true, } } return ( <ScrollIntoViewListItem scrollIntoView={item.scrollIntoView} key={idx} {...itemProps} className={classnames({ [classes.listItem]: true, [classes.highlightedItem]: item.highlight, [classes.listItemDisabled]: item.disabled, })} > {item.icon && <ListItemIcon>{item.icon}</ListItemIcon>} <ListItemText primary={item.title} secondary={item.subText} secondaryTypographyProps={{ style: { whiteSpace: 'pre-line' } }} inset={inset && !item.icon} /> {item.secondaryAction && ( <ListItemSecondaryAction> {item.secondaryAction} </ListItemSecondaryAction> )} </ScrollIntoViewListItem> ) } function renderTransitionItems(): JSX.Element[] { return items.map((item, idx) => { if ('subHeader' in item) { return ( <CSSTransition key={'header_' + item.id} timeout={0} exit={false} enter={false} > {renderSubheaderItem(item, idx)} </CSSTransition> ) } if ('type' in item) { return ( <CSSTransition key={'notice_' + item.id} timeout={500} exit={Boolean(item.transition)} enter={Boolean(item.transition)} classNames={{ enter: classes.slideEnter, enterActive: classes.slideEnterActive, exit: classes.slideExit, exitActive: classes.slideExitActive, }} > {renderNoticeItem(item, idx)} </CSSTransition> ) } return ( <CSSTransition key={'item_' + item.id} timeout={500} classNames={{ enter: classes.slideEnter, enterActive: classes.slideEnterActive, exit: classes.slideExit, exitActive: classes.slideExitActive, }} > {renderItem(item, idx)} </CSSTransition> ) }) } function renderEmptyMessage(): JSX.Element { return ( <ListItem> <ListItemText disableTypography secondary={ <Typography data-cy='list-empty-message' variant='caption'> {emptyMessage} </Typography> } /> </ListItem> ) } function renderItems(): (JSX.Element | undefined)[] | JSX.Element { return items.map((item: FlatListListItem, idx: number) => { if ('subHeader' in item) { return renderSubheaderItem(item, idx) } if ('type' in item) { return renderNoticeItem(item, idx) } if (!onReorder) { return renderItem(item, idx) } if (item.id) { return ( <Draggable key={item.id} draggableId={item.id} index={idx}> {( provided: DraggableProvided, snapshot: DraggableStateSnapshot, ) => { // light grey background while dragging non-active user const draggingBackground = snapshot.isDragging ? classes.participantDragging : '' return ( <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} className={draggingBackground} > {renderItem(item, idx)} </div> ) }} </Draggable> ) } }) } function renderTransitions(): JSX.Element { return <TransitionGroup>{renderTransitionItems()}</TransitionGroup> } // renderList handles rendering the list container as well as any // header elements provided function renderList(): JSX.Element { return ( <List {...listProps}> {(headerNote || headerAction) && ( <ListItem> {headerNote && ( <ListItemText disableTypography secondary={ <Typography color='textSecondary'>{headerNote}</Typography> } className={classes.listItemText} /> )} {headerAction && ( <ListItemSecondaryAction>{headerAction}</ListItemSecondaryAction> )} </ListItem> )} {!items.length && renderEmptyMessage()} {transition ? renderTransitions() : renderItems()} </List> ) } function renderDragAndDrop(): JSX.Element { return ( <DragDropContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}> <Droppable droppableId='droppable'> {(provided: DroppableProvided) => ( <div ref={provided.innerRef} {...provided.droppableProps}> {renderList()} {provided.placeholder} </div> )} </Droppable> </DragDropContext> ) } if (onReorder) { // Enable drag and drop return renderDragAndDrop() } return renderList() }
the_stack
import { expect } from 'chai'; import toArray from 'lodash/toArray'; import React from 'react'; import ReactDOM from 'react-dom'; import { Subject } from 'rxjs/Subject'; import sinon from 'sinon'; import { createApp } from 'frint'; import { renderToString } from 'frint-react-server'; import render from '../render'; import observe from './observe'; import Region from './Region'; import RegionService from '../services/Region'; import streamProps from '../streamProps'; describe('frint-react › components › Region', function () { beforeEach(function () { resetDOM(); }); it('is a function', function () { expect(Region).to.be.a('function'); }); it('renders empty region when no root app available', function () { function MyComponent() { return ( <div id="my-component"> <Region name="left-sidebar" /> </div> ); } ReactDOM.render( <MyComponent />, document.getElementById('root') ); const element = document.getElementById('my-component'); expect(element.innerHTML).to.eql(''); }); it('renders apps with weighted ordering', function () { // root function RootComponent() { return ( <div> <Region name="sidebar" /> </div> ); } const RootApp = createApp({ name: 'RootApp', providers: [ { name: 'component', useValue: RootComponent }, ], }); // apps function App1Component() { return <p>App 1</p>; } const App1 = createApp({ name: 'App1', providers: [ { name: 'component', useValue: App1Component }, ], }); function App2Component() { return <p>App 2</p>; } const App2 = createApp({ name: 'App2', providers: [ { name: 'component', useValue: App2Component }, ], }); // render window.app = new RootApp(); render( window.app, document.getElementById('root') ); // register apps window.app.registerApp(App1, { regions: ['sidebar'], weight: 10, }); window.app.registerApp(App2, { regions: ['sidebar'], weight: 5, }); // verify const paragraphs = document.querySelectorAll('p'); // @TODO: enzyme can be used? expect(paragraphs[0].innerHTML).to.equal('App 2'); expect(paragraphs[1].innerHTML).to.equal('App 1'); }); it('warns when apps subscription emits an error', function () { // root function RootComponent() { return ( <div> <Region name="sidebar" /> <Region name="footer" /> </div> ); } const RootApp = createApp({ name: 'RootApp', providers: [ { name: 'component', useValue: RootComponent }, ], }); // fake an error window.app = new RootApp(); const subject$ = new Subject(); window.app.getApps$ = function getApps$() { return subject$; }; // render render( window.app, document.getElementById('root') ); // verify const stub = sinon.stub(console, 'warn'); subject$.error(new Error('Something bad happened...')); sinon.assert.calledTwice(stub); // two Regions }); it('renders single and multi-instance apps', function () { // root const todos = [ { id: '1', title: 'First todo' }, { id: '2', title: 'Second todo' }, { id: '3', title: 'Third todo' }, ]; let rootComponentInstance; // @TODO: hack class RootComponent extends React.Component { render() { rootComponentInstance = this; return ( <div> <p id="root-text">Hello World from Root</p> <Region className="sidebar" name="sidebar" /> <ul className="todos"> {todos.map((todo) => { return ( <li key={`todo-item-${todo.id}`}> {todo.title} <Region data={{ todo }} name="todo-item" uniqueKey={`todo-item-${todo.id}`} /> </li> ); })} </ul> </div> ); } } const RootApp = createApp({ name: 'RootApp', providers: [ { name: 'component', useValue: RootComponent }, ], }); // apps function App1Component() { return <p id="app1-text">Hello World from App1</p>; } const App1 = createApp({ name: 'App1', providers: [ { name: 'component', useValue: App1Component }, ], }); const App2Component = observe(function (app) { return streamProps() .set( app.get('region').getData$(), data => ({ todo: data.todo }) ) .get$(); })(({ todo }) => ( <p className="app2-text">Hello World from App2 - {todo.title}</p> )); const App2 = createApp({ name: 'App2', providers: [ { name: 'component', useValue: App2Component }, { name: 'region', useClass: RegionService }, ], }); // render window.app = new RootApp(); render( window.app, document.getElementById('root') ); expect(document.getElementById('root-text').innerHTML).to.equal('Hello World from Root'); // register apps window.app.registerApp(App1, { regions: ['sidebar'], weight: 0, }); window.app.registerApp(App2, { regions: ['todo-item'], weight: 1, multi: true, }); // verify single instance app expect(document.getElementById('app1-text').innerHTML).to.equal('Hello World from App1'); // verify multi instance app const elements = toArray(document.getElementsByClassName('app2-text')); elements.forEach((el, index) => { expect(el.innerHTML).to.contain('Hello World from App2 - '); expect(el.innerHTML).to.contain(todos[index].title); }); // change in props todos[1].title = 'Second todo [updated]'; rootComponentInstance.forceUpdate(); elements.forEach((el, index) => { expect(el.innerHTML).to.contain(todos[index].title); }); // unmount ReactDOM.unmountComponentAtNode(document.getElementById('root')); expect(toArray(document.getElementsByClassName('app2-text')).length).to.equal(0); }); it('calls beforeDestroy when unmounting multi-instance apps', function () { // root const todos = [ { id: '1', title: 'First todo' }, ]; let rootComponentInstance; // @TODO: hack class RootComponent extends React.Component { render() { rootComponentInstance = this; return ( <div> <p id="root-text">Hello World from Root</p> <Region name="sidebar" /> <ul className="todos"> {todos.map((todo) => { return ( <li key={`todo-item-${todo.id}`}> {todo.title} <Region data={{ todo }} name="todo-item" uniqueKey={`todo-item-${todo.id}`} /> </li> ); })} </ul> </div> ); } } const RootApp = createApp({ name: 'RootApp', providers: [ { name: 'component', useValue: RootComponent }, ], }); // app const AppComponent = observe(function (app) { return streamProps() .set( app.get('region').getData$(), data => ({ todo: data.todo }) ) .get$(); })(({ todo }) => ( <p className="app-text">Hello World from App - {todo.title}</p> )); let beforeDestroyCalled = false; const App = createApp({ name: 'App', beforeDestroy: function () { beforeDestroyCalled = true; }, providers: [ { name: 'component', useValue: AppComponent }, { name: 'region', useClass: RegionService }, ], }); // render window.app = new RootApp(); render( window.app, document.getElementById('root') ); expect(document.getElementById('root-text').innerHTML).to.equal('Hello World from Root'); // register app window.app.registerApp(App, { regions: ['todo-item'], multi: true, }); // verify multi instance app const elements = toArray(document.getElementsByClassName('app-text')); elements.forEach((el, index) => { expect(el.innerHTML).to.contain('Hello World from App - '); expect(el.innerHTML).to.contain(todos[index].title); }); // rootApp should have the instance expect(window.app.getAppInstance('App', 'todo-item', 'todo-item-1')).to.not.equal(null); // change in props todos.pop(); // empty the list rootComponentInstance.forceUpdate(); const updatedElements = toArray(document.getElementsByClassName('app-text')); expect(updatedElements.length).to.equal(0); // check if beforeDestroy was called expect(beforeDestroyCalled).to.equal(true); // rootApp should not have the instance any more expect(window.app.getAppInstance('App', 'todo-item', 'todo-item-1')).to.equal(null); }); it('should accept className and pass down to rendered component', function () { const className = 'region-sidebar'; // root function RootComponent() { return ( <div> <Region className={className} name="sidebar" /> </div> ); } const RootApp = createApp({ name: 'RootApp', providers: [ { name: 'component', useValue: RootComponent }, ], }); // apps function App1Component() { return <p>App 1</p>; } const App1 = createApp({ name: 'App1', providers: [ { name: 'component', useValue: App1Component }, ], }); // render window.app = new RootApp(); render( window.app, document.getElementById('root') ); // register apps window.app.registerApp(App1, { regions: ['sidebar'], weight: 10, }); // verify const paragraph = document.querySelector('p'); // @TODO: enzyme can be used? expect(paragraph.parentElement.className).to.equal(className); expect(paragraph.innerHTML).to.equal('App 1'); }); it('should pass props to render the component', function () { const data = 'data'; const foo = 'foo'; // root function RootComponent() { return ( <div> <Region data={data} foo={foo} name="sidebar1" /> <Region data={data} foo={foo} name="sidebar2"> {(list, props) => list.map(({ Component, name }) => ( <Component data={props.data} foo={props.foo} key={`app-${name}`} /> ))} </Region> </div> ); } const RootApp = createApp({ name: 'RootApp', providers: [ { name: 'component', useValue: RootComponent }, ], }); // apps function App1Component(props) { return <p>App1 {props.data} {props.foo}</p>; } const App1 = createApp({ name: 'App1', providers: [ { name: 'component', useValue: App1Component }, ], }); function App2Component(props) { return <p>App2 {props.data} {props.foo}</p>; } const App2 = createApp({ name: 'App2', providers: [ { name: 'component', useValue: App2Component }, ], }); // render const rootApp = new RootApp(); render( rootApp, document.getElementById('root') ); // register apps rootApp.registerApp(App1, { regions: ['sidebar1'], }); rootApp.registerApp(App2, { regions: ['sidebar2'], }); // verify const paragraphs = document.querySelectorAll('p'); expect(paragraphs[0].innerHTML).to.equal(`App1 ${data} ${foo}`); expect(paragraphs[1].innerHTML).to.equal(`App2 ${data} ${foo}`); }); it('should render when renderToString is called', function () { // root function RootComponent() { return ( <div> <Region name="sidebar" /> </div> ); } const RootApp = createApp({ name: 'RootApp', providers: [ { name: 'component', useValue: RootComponent }, ], }); // apps function App1Component() { return <p>App 1</p>; } const App1 = createApp({ name: 'App1', providers: [ { name: 'component', useValue: App1Component }, ], }); function App2Component() { return <p>App 2</p>; } const App2 = createApp({ name: 'App2', providers: [ { name: 'component', useValue: App2Component }, ], }); // render const rootApp = new RootApp(); // register apps rootApp.registerApp(App1, { regions: ['sidebar'], weight: 10, }); rootApp.registerApp(App2, { regions: ['sidebar2'], weight: 10, }); const string = renderToString(rootApp); // verify expect(string).to.include('App 1'); expect(string).not.to.include('App 2'); }); it('should unmount component when no root app is available', function () { function MyComponent() { return ( <div id="my-component"> <Region name="left-sidebar" /> </div> ); } ReactDOM.render( <MyComponent />, document.getElementById('root') ); const element = document.getElementById('my-component'); expect(element.innerHTML).to.eql(''); expect(ReactDOM.unmountComponentAtNode(document.getElementById('root'))).to.equal(true); expect(document.getElementById('my-component')).to.equal(null); }); });
the_stack
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Inject } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { SensorParserConfigComponent, Pane, KafkaStatus } from './sensor-parser-config.component'; import { StellarService } from '../../service/stellar.service'; import { SensorParserConfigService } from '../../service/sensor-parser-config.service'; import { KafkaService } from '../../service/kafka.service'; import { KafkaTopic } from '../../model/kafka-topic'; import { GrokValidationService } from '../../service/grok-validation.service'; import { MetronAlerts } from '../../shared/metron-alerts'; import { SensorParserConfig } from '../../model/sensor-parser-config'; import { ParseMessageRequest } from '../../model/parse-message-request'; import { SensorParserContext } from '../../model/sensor-parser-context'; import { AuthenticationService } from '../../service/authentication.service'; import { FieldTransformer } from '../../model/field-transformer'; import { SensorParserConfigModule } from './sensor-parser-config.module'; import { SensorEnrichmentConfigService } from '../../service/sensor-enrichment-config.service'; import { SensorEnrichmentConfig } from '../../model/sensor-enrichment-config'; import { SensorIndexingConfigService } from '../../service/sensor-indexing-config.service'; import { IndexingConfigurations } from '../../model/sensor-indexing-config'; import { of } from 'rxjs'; import { HdfsService } from '../../service/hdfs.service'; import { RestError } from '../../model/rest-error'; import { RiskLevelRule } from '../../model/risk-level-rule'; import {AppConfigService} from '../../service/app-config.service'; import {MockAppConfigService} from '../../service/mock.app-config.service'; class MockRouter { navigateByUrl(url: string) {} } class MockActivatedRoute { private name: string; params: Observable<Params>; setNameForTest(name: string) { this.name = name; this.params = Observable.create(observer => { observer.next({ id: this.name }); observer.complete(); }); } } class MockSensorParserConfigService extends SensorParserConfigService { private name: string; private sensorParserConfig: SensorParserConfig; private parsedMessage: any; private postedSensorParserConfig: SensorParserConfig; private throwError: boolean; public post( name: string, sensorParserConfig: SensorParserConfig ): Observable<SensorParserConfig> { if (this.throwError) { let error = new RestError(); error.message = 'SensorParserConfig post error'; return throwError(error); } this.postedSensorParserConfig = sensorParserConfig; return Observable.create(observer => { observer.next(sensorParserConfig); observer.complete(); }); } public get(name: string): Observable<SensorParserConfig> { return Observable.create(observer => { observer.next(this.sensorParserConfig); observer.complete(); }); } public getAll(): Observable<{}> { return Observable.create(observer => { let results = {}; results[this.name] = this.sensorParserConfig; observer.next(results); observer.complete(); }); } public getAvailableParsers(): Observable<{}> { return Observable.create(observer => { observer.next({ Bro: 'org.apache.metron.parsers.bro.BasicBroParser', Grok: 'org.apache.metron.parsers.GrokParser' }); observer.complete(); }); } public parseMessage( parseMessageRequest: ParseMessageRequest ): Observable<{}> { return Observable.create(observer => { observer.next(this.parsedMessage); observer.complete(); }); } public setSensorParserConfig( name: string, sensorParserConfig: SensorParserConfig ) { this.name = name; this.sensorParserConfig = sensorParserConfig; } public setParsedMessage(parsedMessage: any) { this.parsedMessage = parsedMessage; } public setThrowError(throwError: boolean) { this.throwError = throwError; } public getPostedSensorParserConfig() { return this.postedSensorParserConfig; } } class MockSensorIndexingConfigService extends SensorIndexingConfigService { private name: string; private postedIndexingConfigurations: IndexingConfigurations; private sensorIndexingConfig: IndexingConfigurations; private throwError: boolean; public post( name: string, sensorIndexingConfig: IndexingConfigurations ): Observable<IndexingConfigurations> { if (this.throwError) { let error = new RestError(); error.message = 'IndexingConfigurations post error'; return throwError(error); } this.postedIndexingConfigurations = sensorIndexingConfig; return Observable.create(observer => { observer.next(sensorIndexingConfig); observer.complete(); }); } public get(name: string): Observable<IndexingConfigurations> { if (this.sensorIndexingConfig === null) { let error = new RestError(); error.message = 'IndexingConfigurations get error'; return throwError(error); } return Observable.create(observer => { if (name === this.name) { observer.next(this.sensorIndexingConfig); } observer.complete(); }); } public setSensorIndexingConfig(name: string, result: IndexingConfigurations) { this.name = name; this.sensorIndexingConfig = result; } public setThrowError(throwError: boolean) { this.throwError = throwError; } public getPostedIndexingConfigurations(): IndexingConfigurations { return this.postedIndexingConfigurations; } } class MockKafkaService extends KafkaService { private name: string; private kafkaTopic: KafkaTopic; private kafkaTopicForPost: KafkaTopic; private sampleData = { key1: 'value1', key2: 'value2' }; public setKafkaTopic(name: string, kafkaTopic: KafkaTopic) { this.name = name; this.kafkaTopic = kafkaTopic; } public setSampleData(name: string, sampleData?: any) { this.name = name; this.sampleData = sampleData; } public sample(name: string): Observable<string> { if (this.sampleData === null) { return throwError(new RestError()); } return Observable.create(observer => { if (name === this.name) { observer.next(JSON.stringify(this.sampleData)); } observer.complete(); }); } public get(name: string): Observable<KafkaTopic> { if (this.kafkaTopic === null) { return throwError(new RestError()); } return Observable.create(observer => { if (name === this.name) { observer.next(this.kafkaTopic); } observer.complete(); }); } public post(k: KafkaTopic): Observable<KafkaTopic> { this.kafkaTopicForPost = k; console.log('called post MockKafkaService: ' + this.kafkaTopicForPost); return Observable.create(observer => { observer.next({}); observer.complete(); }); } public getKafkaTopicForPost(): KafkaTopic { console.log('Called get MockKafkaService: ' + this.kafkaTopicForPost); return this.kafkaTopicForPost; } } class MockGrokValidationService extends GrokValidationService { private path: string; private contents: string; public setContents(path: string, contents: string) { this.path = path; this.contents = contents; } public list(): Observable<string[]> { return Observable.create(observer => { observer.next({ BASE10NUM: '(?<![0-9.+-])(?>[+-]?(?:(?:[0-9]+(?:\\.[0-9]+)?)|(?:\\.[0-9]+)))', BASE16FLOAT: '\\b(?<![0-9A-Fa-f.])(?:[+-]?(?:0x)?(?:(?:[0-9A-Fa-f]+(?:\\.[0-9A-Fa-f]*)?)|(?:\\.[0-9A-Fa-f]+)))\\b', BASE16NUM: '(?<![0-9A-Fa-f])(?:[+-]?(?:0x)?(?:[0-9A-Fa-f]+))', CISCOMAC: '(?:(?:[A-Fa-f0-9]{4}\\.){2}[A-Fa-f0-9]{4})', COMMONMAC: '(?:(?:[A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2})', DATA: '.*?' }); observer.complete(); }); } public getStatement(path: string): Observable<string> { if (this.contents === null) { return throwError('Error'); } return Observable.create(observer => { if (path === this.path) { observer.next(this.contents); } observer.complete(); }); } } class MockHdfsService extends HdfsService { private fileList: string[]; private path: string; private contents: string; private postedContents: string; public setFileList(path: string, fileList: string[]) { this.path = path; this.fileList = fileList; } public setContents(path: string, contents: string) { this.path = path; this.contents = contents; } public list(path: string): Observable<string[]> { if (this.fileList === null) { return throwError('Error'); } return Observable.create(observer => { if (path === this.path) { observer.next(this.fileList); } observer.complete(); }); } public read(path: string): Observable<string> { if (this.contents === null) { return throwError('Error'); } return Observable.create(observer => { if (path === this.path) { observer.next(this.contents); } observer.complete(); }); } public post(path: string, contents: string): Observable<{}> { if (this.contents === null) { let error = new RestError(); error.message = 'HDFS post Error'; return throwError(error); } this.postedContents = contents; return Observable.create(observer => { observer.next(contents); observer.complete(); }); } public deleteFile(path: string): Observable<HttpResponse<{}>> { return Observable.create(observer => { observer.next({}); observer.complete(); }); } public getPostedContents() { return this.postedContents; } } class MockAuthenticationService extends AuthenticationService { public getCurrentUser(options: {}): Observable<HttpResponse<{}>> { let responseOptions: {} = { body: 'user' }; let response: HttpResponse<{}> = new HttpResponse(responseOptions); return of(response); } } class MockTransformationValidationService extends StellarService { private transformationValidationResult: any; private transformationValidationForValidate: SensorParserContext; public setTransformationValidationResultForTest( transformationValidationResult: any ): void { this.transformationValidationResult = transformationValidationResult; } public getTransformationValidationForValidate(): SensorParserContext { return this.transformationValidationForValidate; } public validate(t: SensorParserContext): Observable<{}> { this.transformationValidationForValidate = t; return Observable.create(observer => { observer.next(this.transformationValidationResult); observer.complete(); }); } } export class MockSensorEnrichmentConfigService { private name: string; private sensorEnrichmentConfig: SensorEnrichmentConfig; private postedSensorEnrichmentConfig: SensorEnrichmentConfig; private throwError: boolean; public setSensorEnrichmentConfig( name: string, sensorEnrichmentConfig: SensorEnrichmentConfig ) { this.name = name; this.sensorEnrichmentConfig = sensorEnrichmentConfig; } public get(name: string): Observable<SensorEnrichmentConfig> { if (this.sensorEnrichmentConfig === null) { let error = new RestError(); error.message = 'SensorEnrichmentConfig get error'; return throwError(error); } return Observable.create(observer => { if (name === this.name) { observer.next(this.sensorEnrichmentConfig); } observer.complete(); }); } public post( name: string, sensorEnrichmentConfig: SensorEnrichmentConfig ): Observable<SensorEnrichmentConfig> { if (this.throwError) { let error = new RestError(); error.message = 'SensorEnrichmentConfig post error'; return throwError(error); } this.postedSensorEnrichmentConfig = sensorEnrichmentConfig; return Observable.create(observer => { observer.next(sensorEnrichmentConfig); observer.complete(); }); } public setThrowError(throwError: boolean) { this.throwError = throwError; } public getPostedSensorEnrichmentConfig() { return this.postedSensorEnrichmentConfig; } } describe('Component: SensorParserConfig', () => { let component: SensorParserConfigComponent; let fixture: ComponentFixture<SensorParserConfigComponent>; let sensorParserConfigService: MockSensorParserConfigService; let sensorEnrichmentConfigService: MockSensorEnrichmentConfigService; let sensorIndexingConfigService: MockSensorIndexingConfigService; let transformationValidationService: MockTransformationValidationService; let kafkaService: MockKafkaService; let hdfsService: MockHdfsService; let grokValidationService: MockGrokValidationService; let activatedRoute: MockActivatedRoute; let metronAlerts: MetronAlerts; let router: MockRouter; let squidSensorParserConfig: any = { parserClassName: 'org.apache.metron.parsers.GrokParser', sensorTopic: 'squid', parserConfig: { grokPath: '/apps/metron/patterns/squid', patternLabel: 'SQUID_DELIMITED', timestampField: 'timestamp' }, fieldTransformations: [ { input: [], output: ['full_hostname', 'domain_without_subdomains', 'hostname'], transformation: 'STELLAR', config: { full_hostname: 'URL_TO_HOST(url)', domain_without_subdomains: 'DOMAIN_REMOVE_SUBDOMAINS(full_hostname)' } } ] }; let squidSensorEnrichmentConfig = { enrichment: { fieldMap: { geo: ['ip_dst_addr'], host: ['ip_dst_addr'], whois: [], stellar: { config: { group1: {} } } }, fieldToTypeMap: {}, config: {} }, threatIntel: { threatIntel: { fieldMap: { hbaseThreatIntel: ['ip_dst_addr'] }, fieldToTypeMap: { ip_dst_addr: ['malicious_ip'] } } } }; let squidIndexingConfigurations = { hdfs: { index: 'squid', batchSize: 5, enabled: true }, elasticsearch: { index: 'squid', batchSize: 10, enabled: true }, solr: { index: 'squid', batchSize: 1, enabled: false } }; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [SensorParserConfigModule], providers: [ MetronAlerts, { provide: HttpClient }, { provide: SensorParserConfigService, useClass: MockSensorParserConfigService }, { provide: SensorIndexingConfigService, useClass: MockSensorIndexingConfigService }, { provide: KafkaService, useClass: MockKafkaService }, { provide: HdfsService, useClass: MockHdfsService }, { provide: GrokValidationService, useClass: MockGrokValidationService }, { provide: StellarService, useClass: MockTransformationValidationService }, { provide: ActivatedRoute, useClass: MockActivatedRoute }, { provide: Router, useClass: MockRouter }, { provide: AuthenticationService, useClass: MockAuthenticationService }, { provide: SensorEnrichmentConfigService, useClass: MockSensorEnrichmentConfigService }, { provide: AppConfigService, useClass: MockAppConfigService } ] }); fixture = TestBed.createComponent(SensorParserConfigComponent); component = fixture.componentInstance; sensorParserConfigService = TestBed.get(SensorParserConfigService); sensorIndexingConfigService = TestBed.get(SensorIndexingConfigService); transformationValidationService = TestBed.get(StellarService); kafkaService = TestBed.get(KafkaService); hdfsService = TestBed.get(HdfsService); grokValidationService = TestBed.get(GrokValidationService); sensorEnrichmentConfigService = TestBed.get(SensorEnrichmentConfigService); activatedRoute = TestBed.get(ActivatedRoute); metronAlerts = TestBed.get(MetronAlerts); router = TestBed.get(Router); })); afterEach(() => { fixture.destroy(); }) it('should create an instance of SensorParserConfigComponent', async(() => { expect(component).toBeDefined(); })); it('should handle ngOnInit', async(() => { spyOn(component, 'init'); spyOn(component, 'createForms'); spyOn(component, 'getAvailableParsers'); activatedRoute.setNameForTest('squid'); component.ngOnInit(); expect(component.init).toHaveBeenCalledWith('squid'); expect(component.createForms).toHaveBeenCalled(); expect(component.getAvailableParsers).toHaveBeenCalled(); })); it('should createForms', async(() => { component.sensorParserConfig = Object.assign( new SensorParserConfig(), squidSensorParserConfig ); component.createForms(); expect(Object.keys(component.sensorConfigForm.controls).length).toEqual(17); expect( Object.keys(component.transformsValidationForm.controls).length ).toEqual(2); expect(component.showAdvancedParserConfiguration).toEqual(true); component.sensorParserConfig.parserConfig = {}; component.showAdvancedParserConfiguration = false; component.createForms(); expect(component.showAdvancedParserConfiguration).toEqual(false); })); it('should getAvailableParsers', async(() => { component.getAvailableParsers(); expect(component.availableParsers).toEqual({ Bro: 'org.apache.metron.parsers.bro.BasicBroParser', Grok: 'org.apache.metron.parsers.GrokParser' }); expect(component.availableParserNames).toEqual(['Bro', 'Grok']); })); it('should init', async(() => { sensorParserConfigService.setSensorParserConfig( 'squid', squidSensorParserConfig ); component.init('new'); let expectedSensorParserConfig = new SensorParserConfig(); expectedSensorParserConfig.parserClassName = 'org.apache.metron.parsers.GrokParser'; expect(component.sensorParserConfig).toEqual(expectedSensorParserConfig); expect(component.sensorEnrichmentConfig).toEqual( new SensorEnrichmentConfig() ); expect(component.indexingConfigurations).toEqual( new IndexingConfigurations() ); expect(component.editMode).toEqual(false); expect(component.currentSensors).toEqual(['squid']); spyOn(component, 'getKafkaStatus'); let sensorParserConfig = Object.assign( new SensorParserConfig(), squidSensorParserConfig ); sensorParserConfigService.setSensorParserConfig( 'squid', sensorParserConfig ); sensorEnrichmentConfigService.setSensorEnrichmentConfig( 'squid', Object.assign(new SensorEnrichmentConfig(), squidSensorEnrichmentConfig) ); sensorIndexingConfigService.setSensorIndexingConfig( 'squid', Object.assign(new IndexingConfigurations(), squidIndexingConfigurations) ); hdfsService.setContents( '/apps/metron/patterns/squid', 'SQUID_DELIMITED grok statement' ); component.init('squid'); expect(component.sensorParserConfig).toEqual( Object.assign(new SensorParserConfig(), squidSensorParserConfig) ); expect(component.sensorNameValid).toEqual(true); expect(component.getKafkaStatus).toHaveBeenCalled(); expect(component.showAdvancedParserConfiguration).toEqual(true); expect(component.grokStatement).toEqual('SQUID_DELIMITED grok statement'); expect(component.patternLabel).toEqual('SQUID_DELIMITED'); expect(component.sensorEnrichmentConfig).toEqual( Object.assign(new SensorEnrichmentConfig(), squidSensorEnrichmentConfig) ); expect(component.indexingConfigurations).toEqual( Object.assign(new IndexingConfigurations(), squidIndexingConfigurations) ); component.sensorParserConfig.parserConfig['grokPath'] = '/patterns/squid'; hdfsService.setContents('/patterns/squid', null); grokValidationService.setContents( '/patterns/squid', 'SQUID grok statement from classpath' ); component.init('squid'); expect(component.grokStatement).toEqual( 'SQUID grok statement from classpath' ); spyOn(metronAlerts, 'showErrorMessage'); sensorEnrichmentConfigService.setSensorEnrichmentConfig('squid', null); component.init('squid'); expect(metronAlerts.showErrorMessage).toHaveBeenCalledWith( 'SensorEnrichmentConfig get error' ); sensorIndexingConfigService.setSensorIndexingConfig('squid', null); component.init('squid'); expect(metronAlerts.showErrorMessage).toHaveBeenCalledWith( 'IndexingConfigurations get error' ); grokValidationService.setContents('/patterns/squid', null); component.init('squid'); expect(metronAlerts.showErrorMessage).toHaveBeenCalledWith( 'Could not find grok statement in HDFS or classpath at /patterns/squid' ); sensorParserConfig = new SensorParserConfig(); sensorParserConfig.sensorTopic = 'bro'; sensorParserConfigService.setSensorParserConfig('bro', sensorParserConfig); component.showAdvancedParserConfiguration = false; component.init('bro'); expect(component.showAdvancedParserConfiguration).toEqual(false); })); it('should getMessagePrefix', async(() => { component.getAvailableParsers(); expect(component.getMessagePrefix()).toEqual('Created'); component.editMode = true; expect(component.getMessagePrefix()).toEqual('Modified'); })); it('should handle onSetKafkaTopic', async(() => { spyOn(component, 'getKafkaStatus'); component.onSetKafkaTopic(); expect(component.getKafkaStatus).not.toHaveBeenCalled(); component.sensorParserConfig.sensorTopic = 'bro'; component.onSetKafkaTopic(); expect(component.kafkaTopicValid).toEqual(true); expect(component.getKafkaStatus).toHaveBeenCalled(); })); it('should handle onSetSensorName', async(() => { component.onSetSensorName(); expect(component.sensorNameValid).toEqual(false); component.sensorName = 'squid'; component.currentSensors = ['squid']; component.onSetSensorName(); expect(component.sensorNameUnique).toEqual(false); expect(component.sensorNameValid).toEqual(false); component.sensorName = 'squidUnique'; component.onSetSensorName(); expect(component.sensorNameUnique).toEqual(true); expect(component.sensorNameValid).toEqual(true); })); it('sensor name should be validated agains special characters', () => { component.sensorName = 'squidWithSpecChar@'; component.onSetSensorName(); expect(component.sensorNameNoSpecChars).toEqual(false); expect(component.sensorNameValid).toEqual(false); component.sensorName = 'squidWithSpecChar#'; component.onSetSensorName(); expect(component.sensorNameNoSpecChars).toEqual(false); expect(component.sensorNameValid).toEqual(false); component.sensorName = 'squidWithSpecChar/'; component.onSetSensorName(); expect(component.sensorNameNoSpecChars).toEqual(false); expect(component.sensorNameValid).toEqual(false); component.sensorName = 'squidWithSpecChar?'; component.onSetSensorName(); expect(component.sensorNameNoSpecChars).toEqual(false); expect(component.sensorNameValid).toEqual(false); component.sensorName = 'squidWithSpecChar?$&%'; component.onSetSensorName(); expect(component.sensorNameNoSpecChars).toEqual(false); expect(component.sensorNameValid).toEqual(false); }); it('sensor name validation should accept dash and lowdash chars', () => { component.sensorName = 'squidWithSpecChar-'; component.onSetSensorName(); expect(component.sensorNameNoSpecChars).toEqual(true); expect(component.sensorNameValid).toEqual(true); component.sensorName = 'squidWithSpecChar_'; component.onSetSensorName(); expect(component.sensorNameNoSpecChars).toEqual(true); expect(component.sensorNameValid).toEqual(true); }) it('should handle onParserTypeChange', async(() => { spyOn(component, 'hidePane'); component.onParserTypeChange(); expect(component.hidePane).not.toHaveBeenCalled(); component.sensorParserConfig.parserClassName = 'org.apache.metron.parsers.GrokParser'; component.onParserTypeChange(); expect(component.parserClassValid).toEqual(true); expect(component.hidePane).not.toHaveBeenCalled(); component.sensorParserConfig.parserClassName = 'org.apache.metron.parsers.bro.BasicBroParser'; component.onParserTypeChange(); expect(component.hidePane).toHaveBeenCalledWith(Pane.GROK); })); it('isGrokStatementValid should validate grokStatement', async(() => { expect(component.isGrokStatementValid()).toEqual(false); component.grokStatement = ''; expect(component.isGrokStatementValid()).toEqual(false); component.grokStatement = 'grok statement'; expect(component.isGrokStatementValid()).toEqual(true); })); it('should handle isConfigValid', async(() => { expect(component.isConfigValid()).toEqual(false); component.sensorNameValid = true; component.kafkaTopicValid = true; component.parserClassValid = true; expect(component.isConfigValid()).toEqual(true); component.sensorParserConfig.parserClassName = 'org.apache.metron.parsers.GrokParser'; expect(component.isConfigValid()).toEqual(false); component.grokStatement = 'grok statement'; expect(component.isConfigValid()).toEqual(true); })); it('should getKafkaStatus', async(() => { component.getKafkaStatus(); expect(component.currentKafkaStatus).toEqual(null); component.sensorParserConfig.sensorTopic = 'squid'; kafkaService.setKafkaTopic('squid', null); component.getKafkaStatus(); expect(component.currentKafkaStatus).toEqual(KafkaStatus.NO_TOPIC); kafkaService.setKafkaTopic('squid', new KafkaTopic()); kafkaService.setSampleData('squid', null); component.getKafkaStatus(); expect(component.currentKafkaStatus).toEqual(KafkaStatus.NOT_EMITTING); kafkaService.setSampleData('squid', 'message'); component.getKafkaStatus(); expect(component.currentKafkaStatus).toEqual(KafkaStatus.EMITTING); })); it('should getTransforms', async(() => { expect(component.getTransforms()).toEqual('0 Transformations Applied'); component.sensorParserConfig.fieldTransformations.push( Object.assign(new FieldTransformer(), { output: ['field1', 'field2'] }) ); component.sensorParserConfig.fieldTransformations.push( Object.assign(new FieldTransformer(), { output: ['field3'] }) ); expect(component.getTransforms()).toEqual('3 Transformations Applied'); })); it('should handle onSaveGrokStatement', async(() => { component.sensorName = 'squid'; component.onSaveGrokStatement('grok statement'); expect(component.grokStatement).toEqual('grok statement'); expect(component.sensorParserConfig.parserConfig['grokPath']).toEqual( '/apps/metron/patterns/squid' ); component.sensorParserConfig.parserConfig['grokPath'] = '/patterns/squid'; component.onSaveGrokStatement('grok statement'); expect(component.sensorParserConfig.parserConfig['grokPath']).toEqual( '/apps/metron/patterns/squid' ); component.sensorParserConfig.parserConfig['grokPath'] = '/custom/grok/path'; component.onSaveGrokStatement('grok statement'); expect(component.sensorParserConfig.parserConfig['grokPath']).toEqual( '/custom/grok/path' ); })); it('should onSavePatternLabel', async(() => { component.onSavePatternLabel('PATTERN_LABEL'); expect(component.patternLabel).toEqual('PATTERN_LABEL'); expect(component.sensorParserConfig.parserConfig['patternLabel']).toEqual( 'PATTERN_LABEL' ); })); it('should goBack', async(() => { activatedRoute.setNameForTest('new'); router.navigateByUrl = jasmine.createSpy('navigateByUrl'); component.goBack(); expect(router.navigateByUrl).toHaveBeenCalledWith('/sensors'); })); it('should save sensor configuration', async(() => { let fieldTransformer = Object.assign(new FieldTransformer(), { input: [], output: ['url_host'], transformation: 'MTL', config: { url_host: 'TO_LOWER(URL_TO_HOST(url))' } }); let sensorParserConfigSave: SensorParserConfig = new SensorParserConfig(); sensorParserConfigSave.sensorTopic = 'squid'; sensorParserConfigSave.parserClassName = 'org.apache.metron.parsers.GrokParser'; sensorParserConfigSave.parserConfig['grokPath'] = '/apps/metron/patterns/squid'; sensorParserConfigSave.fieldTransformations = [fieldTransformer]; activatedRoute.setNameForTest('new'); sensorParserConfigService.setThrowError(true); spyOn(metronAlerts, 'showSuccessMessage'); spyOn(metronAlerts, 'showErrorMessage'); component.sensorParserConfig.sensorTopic = 'squid'; component.sensorParserConfig.parserClassName = 'org.apache.metron.parsers.GrokParser'; component.sensorParserConfig.parserConfig['grokPath'] = '/apps/metron/patterns/squid'; component.sensorParserConfig.fieldTransformations = [fieldTransformer]; component.onSave(); expect(metronAlerts.showErrorMessage['calls'].mostRecent().args[0]).toEqual( 'Unable to save sensor config: SensorParserConfig post error' ); component.sensorEnrichmentConfig = Object.assign( new SensorEnrichmentConfig(), squidSensorEnrichmentConfig ); component.indexingConfigurations = Object.assign( new IndexingConfigurations(), squidIndexingConfigurations ); sensorParserConfigService.setThrowError(false); hdfsService.setContents( '/apps/metron/patterns/squid', 'SQUID grok statement' ); component.grokStatement = 'SQUID grok statement'; component.onSave(); expect(sensorParserConfigService.getPostedSensorParserConfig()).toEqual( sensorParserConfigSave ); expect( sensorEnrichmentConfigService.getPostedSensorEnrichmentConfig() ).toEqual( Object.assign(new SensorEnrichmentConfig(), squidSensorEnrichmentConfig) ); expect( sensorIndexingConfigService.getPostedIndexingConfigurations() ).toEqual( Object.assign(new IndexingConfigurations(), squidIndexingConfigurations) ); expect(hdfsService.getPostedContents()).toEqual('SQUID grok statement'); hdfsService.setContents('/apps/metron/patterns/squid', null); component.onSave(); expect(metronAlerts.showErrorMessage['calls'].mostRecent().args[0]).toEqual( 'HDFS post Error' ); sensorEnrichmentConfigService.setThrowError(true); component.onSave(); expect(metronAlerts.showErrorMessage['calls'].mostRecent().args[0]).toEqual( 'Created Sensor parser config but unable to save enrichment configuration: SensorEnrichmentConfig post error' ); sensorIndexingConfigService.setThrowError(true); component.onSave(); expect(metronAlerts.showErrorMessage['calls'].mostRecent().args[0]).toEqual( 'Created Sensor parser config but unable to save indexing configuration: IndexingConfigurations post error' ); })); it('should getTransformationCount', async(() => { let transforms = [ Object.assign(new FieldTransformer(), { input: ['method'], output: null, transformation: 'REMOVE', config: { condition: 'exists(method) and method == "foo"' } }), Object.assign(new FieldTransformer(), { input: [], output: ['method', 'status_code', 'url'], transformation: 'STELLAR', config: { method: 'TO_UPPER(method)', status_code: 'TO_LOWER(code)', url: 'TO_STRING(TRIM(url))' } }) ]; expect(component.getTransformationCount()).toEqual(0); fixture.componentInstance.sensorParserConfig.fieldTransformations = transforms; expect(component.getTransformationCount()).toEqual(3); fixture.componentInstance.sensorParserConfig.fieldTransformations = [ transforms[0] ]; expect(component.getTransformationCount()).toEqual(0); })); it('should getEnrichmentCount', async(() => { component.sensorEnrichmentConfig.enrichment.fieldMap['geo'] = [ 'ip_src_addr', 'ip_dst_addr' ]; component.sensorEnrichmentConfig.enrichment.fieldToTypeMap[ 'hbaseenrichment' ] = ['ip_src_addr', 'ip_dst_addr']; expect(component.getEnrichmentCount()).toEqual(4); })); it('should getThreatIntelCount', async(() => { component.sensorEnrichmentConfig.threatIntel.fieldToTypeMap[ 'hbaseenrichment' ] = ['ip_src_addr', 'ip_dst_addr']; expect(component.getThreatIntelCount()).toEqual(2); })); it('should getRuleCount', async(() => { let rule1 = Object.assign(new RiskLevelRule(), { name: 'rule1', rule: 'some rule', score: 50 }); let rule2 = Object.assign(new RiskLevelRule(), { name: 'rule2', rule: 'some other rule', score: 80 }); component.sensorEnrichmentConfig.threatIntel.triageConfig.riskLevelRules.push( rule1 ); component.sensorEnrichmentConfig.threatIntel.triageConfig.riskLevelRules.push( rule2 ); expect(component.getRuleCount()).toEqual(2); })); it('should showPane', async(() => { component.showPane(Pane.GROK); expect(component.showGrokValidator).toEqual(true); expect(component.showFieldSchema).toEqual(false); expect(component.showRawJson).toEqual(false); component.showPane(Pane.FIELDSCHEMA); expect(component.showGrokValidator).toEqual(false); expect(component.showFieldSchema).toEqual(true); expect(component.showRawJson).toEqual(false); component.showPane(Pane.RAWJSON); expect(component.showGrokValidator).toEqual(false); expect(component.showFieldSchema).toEqual(false); expect(component.showRawJson).toEqual(true); })); it('should hidePane', async(() => { component.hidePane(Pane.GROK); expect(component.showGrokValidator).toEqual(false); expect(component.showFieldSchema).toEqual(false); expect(component.showRawJson).toEqual(false); component.hidePane(Pane.FIELDSCHEMA); expect(component.showGrokValidator).toEqual(false); expect(component.showFieldSchema).toEqual(false); expect(component.showRawJson).toEqual(false); component.hidePane(Pane.RAWJSON); expect(component.showGrokValidator).toEqual(false); expect(component.showFieldSchema).toEqual(false); expect(component.showRawJson).toEqual(false); })); it('should handle onShowGrokPane', async(() => { spyOn(component, 'showPane'); component.sensorName = 'squid'; component.onShowGrokPane(); expect(component.patternLabel).toEqual('SQUID'); expect(component.showPane).toHaveBeenCalledWith(component.pane.GROK); component.patternLabel = 'PATTERN_LABEL'; component.onShowGrokPane(); expect(component.patternLabel).toEqual('PATTERN_LABEL'); })); it('should handle onRawJsonChanged', async(() => { spyOn(component.sensorFieldSchema, 'createFieldSchemaRows'); component.onRawJsonChanged(); expect( component.sensorFieldSchema.createFieldSchemaRows ).toHaveBeenCalled(); })); it('should handle onAdvancedConfigFormClose', async(() => { component.onAdvancedConfigFormClose(); expect(component.showAdvancedParserConfiguration).toEqual(false); })); it('should be timestamp by default', () => { expect(component.sensorParserConfig.timestampField).toEqual('timestamp'); }); it('should be invalid if timestamp field is empty', () => { component.sensorNameValid = true; component.kafkaTopicValid = true; component.parserClassValid = true; component.grokStatement = 'grokStatement'; component.sensorParserConfig = new SensorParserConfig(); component.sensorParserConfig.parserClassName = 'org.apache.metron.parsers.GrokParser' component.sensorParserConfig.timestampField = ''; expect(component.isConfigValid()).toEqual(false); component.sensorParserConfig.timestampField = 'timestamp'; expect(component.isConfigValid()).toEqual(true); }); });
the_stack
import { expect } from "chai"; import * as sinon from "sinon"; import { Point } from "@itwin/core-react"; import { AccuDrawKeyboardShortcuts, CommandItemDef, ConfigurableUiManager, KeyboardShortcut, KeyboardShortcutContainer, KeyboardShortcutManager, KeyboardShortcutProps, } from "../../appui-react"; import { CursorInformation } from "../../appui-react/cursor/CursorInformation"; import { KeyboardShortcutMenu } from "../../appui-react/keyboardshortcut/KeyboardShortcutMenu"; import TestUtils from "../TestUtils"; import { ConditionalBooleanValue, FunctionKey, SpecialKey } from "@itwin/appui-abstract"; import { SyncUiEventDispatcher } from "../../appui-react/syncui/SyncUiEventDispatcher"; describe("KeyboardShortcut", () => { const testSpyMethod = sinon.spy(); let testCommand: CommandItemDef; let testCommand2: CommandItemDef; before(async () => { await TestUtils.initializeUiFramework(); testCommand = new CommandItemDef({ commandId: "testCommand", iconSpec: "icon-placeholder", label: "Test", execute: () => { testSpyMethod(); }, }); testCommand2 = new CommandItemDef({ commandId: "testCommand2", iconSpec: "icon-placeholder", label: "Test", execute: () => { testSpyMethod(); }, }); }); after(() => { TestUtils.terminateUiFramework(); }); beforeEach(() => { testSpyMethod.resetHistory(); KeyboardShortcutManager.shortcutContainer.emptyData(); }); describe("KeyboardShortcut", () => { it("Providing no item or shortcuts should throw Error", () => { expect(() => KeyboardShortcutManager.loadKeyboardShortcut({ key: "a" })).to.throw(Error); }); it("should support function keys", () => { const keyboardShortcut = new KeyboardShortcut({ key: FunctionKey.F7, item: testCommand }); expect(keyboardShortcut.isFunctionKey).to.be.true; expect(keyboardShortcut.isSpecialKey).to.be.false; }); it("should support special keys", () => { const keyboardShortcut = new KeyboardShortcut({ key: SpecialKey.ArrowDown, item: testCommand }); expect(keyboardShortcut.isSpecialKey).to.be.true; expect(keyboardShortcut.isFunctionKey).to.be.false; }); it("Should provide and execute item", async () => { KeyboardShortcutManager.loadKeyboardShortcut({ key: "b", item: testCommand, }); const shortcut = KeyboardShortcutManager.getShortcut("b"); expect(shortcut).to.not.be.undefined; if (shortcut) { expect(shortcut.id).to.eq("b"); expect(shortcut.item).to.eq(testCommand); shortcut.itemPicked(); await TestUtils.flushAsyncOperations(); expect(testSpyMethod.calledOnce).to.be.true; } }); it("Registering with duplicate key should replace", () => { KeyboardShortcutManager.loadKeyboardShortcut({ key: "b", item: testCommand, }); KeyboardShortcutManager.loadKeyboardShortcut({ key: "b", item: testCommand2, }); const shortcut = KeyboardShortcutManager.getShortcut("b"); expect(shortcut).to.not.be.undefined; if (shortcut) { expect(shortcut.item).to.eq(testCommand2); const shortcuts = KeyboardShortcutManager.shortcutContainer.getAvailableKeyboardShortcuts(); expect(shortcuts.length).to.eq(1); expect(shortcuts[0].item).to.eq(testCommand2); } }); it("KeyboardShortcut should support child shortcuts", () => { KeyboardShortcutManager.loadKeyboardShortcut({ key: "d", labelKey: "SampleApp:buttons.shortcutsSubMenu", shortcuts: [ { key: "1", item: testCommand, }, ], }); const shortcut = KeyboardShortcutManager.getShortcut("d"); expect(shortcut).to.not.be.undefined; if (shortcut) { expect(shortcut.id).to.eq("d"); expect(shortcut.shortcutContainer.areKeyboardShortcutsAvailable()).to.be.true; expect(shortcut.getShortcut("1")).to.not.be.undefined; const menuSpyMethod = sinon.spy(); const remove = KeyboardShortcutMenu.onKeyboardShortcutMenuEvent.addListener(menuSpyMethod); shortcut.itemPicked(); expect(menuSpyMethod.calledOnce).to.be.true; remove(); } }); it("Should support Alt, Ctrl and Shift keys", () => { KeyboardShortcutManager.loadKeyboardShortcut({ key: "A", item: testCommand, isAltKeyRequired: true, isCtrlKeyRequired: true, isShiftKeyRequired: true, iconSpec: "icon-placeholder", label: "Test", tooltip: "Tooltip", }); const keyMapKey = KeyboardShortcutContainer.generateKeyMapKey("A", true, true, true); expect(keyMapKey).to.eq("Ctrl+Shift+Alt+A"); const shortcut = KeyboardShortcutManager.getShortcut(keyMapKey); expect(shortcut).to.not.be.undefined; if (shortcut) { expect(shortcut.isAltKeyRequired).to.be.true; expect(shortcut.isCtrlKeyRequired).to.be.true; expect(shortcut.isShiftKeyRequired).to.be.true; } }); it("Should support disabled & hidden", () => { KeyboardShortcutManager.loadKeyboardShortcut({ key: "x", item: testCommand, isDisabled: true, isHidden: true, label: "Test", }); const shortcut = KeyboardShortcutManager.getShortcut("x"); expect(shortcut).to.not.be.undefined; expect(shortcut!.isDisabled).to.be.true; expect(shortcut!.isHidden).to.be.true; const yCommand = new CommandItemDef({ commandId: "yCommand", iconSpec: "icon-placeholder", isDisabled: true, isHidden: true, label: "Test", execute: () => { testSpyMethod(); }, }); KeyboardShortcutManager.loadKeyboardShortcut({ key: "y", item: yCommand, label: "Test", }); const yShortcut = KeyboardShortcutManager.getShortcut("y"); expect(yShortcut).to.not.be.undefined; expect(yShortcut!.isDisabled).to.be.true; expect(yShortcut!.isHidden).to.be.true; }); }); describe("KeyboardShortcutManager", () => { it("ConfigurableUiManager.loadKeyboardShortcuts should load shortcuts", () => { const keyboardShortcutList: KeyboardShortcutProps[] = [ { key: "a", item: testCommand, }, { key: "d", labelKey: "Test", shortcuts: [ { key: "1", item: testCommand, }, ], }, { key: FunctionKey.F7, item: testCommand, }, { key: SpecialKey.Home, item: testCommand, }, ]; const menuSpyMethod = sinon.spy(); KeyboardShortcutManager.displayShortcutsMenu(); // No shortcuts to display yet expect(menuSpyMethod.calledOnce).to.be.false; ConfigurableUiManager.loadKeyboardShortcuts(keyboardShortcutList); expect(KeyboardShortcutManager.shortcutContainer.areKeyboardShortcutsAvailable()).to.be.true; expect(KeyboardShortcutManager.shortcutContainer.getAvailableKeyboardShortcuts().length).to.eq(4); expect(KeyboardShortcutManager.getShortcut("a")).to.not.be.undefined; expect(KeyboardShortcutManager.getShortcut("d")).to.not.be.undefined; expect(KeyboardShortcutManager.getShortcut(FunctionKey.F7)).to.not.be.undefined; expect(KeyboardShortcutManager.getShortcut(SpecialKey.Home)).to.not.be.undefined; const remove = KeyboardShortcutMenu.onKeyboardShortcutMenuEvent.addListener(menuSpyMethod); KeyboardShortcutManager.displayShortcutsMenu(); expect(menuSpyMethod.calledOnce).to.be.true; remove(); }); it("processKey should invoke item", async () => { KeyboardShortcutManager.loadKeyboardShortcut({ key: "f", item: testCommand, }); const shortcut = KeyboardShortcutManager.getShortcut("f"); expect(shortcut).to.not.be.undefined; const processed = KeyboardShortcutManager.processKey("f"); expect(processed).to.be.true; await TestUtils.flushAsyncOperations(); expect(testSpyMethod.calledOnce).to.be.true; const processedG = KeyboardShortcutManager.processKey("g"); expect(processedG).to.be.false; }); it("processKey should invoke item", async () => { const testEventId = "test-sync-event"; const testEventId3 = "test-sync-event3"; const conditional1 = new ConditionalBooleanValue(() => true, [testEventId], false); const conditional2 = new ConditionalBooleanValue(() => true, [testEventId], false); const conditional3 = new ConditionalBooleanValue(() => true, [testEventId3], false); KeyboardShortcutManager.initialize(); KeyboardShortcutManager.loadKeyboardShortcut( { key: "r", labelKey: "Test", isDisabled: conditional1, shortcuts: [ { key: "t", item: testCommand, isDisabled: conditional2, }, { key: "z", item: testCommand, isDisabled: conditional3, isHidden: conditional2, }, ], }, ); const shortcut = KeyboardShortcutManager.getShortcut("r"); expect(shortcut).to.not.be.undefined; expect(ConditionalBooleanValue.getValue(shortcut!.isDisabled)).to.be.false; const childShortcut = shortcut!.getShortcut("t"); expect(childShortcut).to.not.be.undefined; expect(ConditionalBooleanValue.getValue(childShortcut!.isDisabled)).to.be.false; const childShortcutZ = shortcut!.getShortcut("z"); expect(childShortcutZ).to.not.be.undefined; expect(ConditionalBooleanValue.getValue(childShortcutZ!.isDisabled)).to.be.false; expect(ConditionalBooleanValue.getValue(childShortcutZ!.isHidden)).to.be.false; SyncUiEventDispatcher.dispatchImmediateSyncUiEvent(testEventId); expect(ConditionalBooleanValue.getValue(shortcut!.isDisabled)).to.be.true; expect(ConditionalBooleanValue.getValue(childShortcut!.isDisabled)).to.be.true; expect(ConditionalBooleanValue.getValue(childShortcutZ!.isDisabled)).to.be.false; expect(ConditionalBooleanValue.getValue(childShortcutZ!.isHidden)).to.be.true; }); it("Should maintain cursor X & Y", () => { CursorInformation.cursorPosition = new Point(100, 200); expect(KeyboardShortcutManager.cursorX).to.eq(100); expect(KeyboardShortcutManager.cursorY).to.eq(200); }); it("setFocusToHome should set focus to home", () => { const buttonElement = document.createElement("button"); document.body.appendChild(buttonElement); buttonElement.focus(); let activeElement = document.activeElement as HTMLElement; expect(activeElement === buttonElement).to.be.true; expect(KeyboardShortcutManager.isFocusOnHome).to.be.false; KeyboardShortcutManager.setFocusToHome(); activeElement = document.activeElement as HTMLElement; expect(activeElement === document.body).to.be.true; expect(KeyboardShortcutManager.isFocusOnHome).to.be.true; document.body.removeChild(buttonElement); }); }); it("should support loading the AccuDraw keyboard shortcuts", async () => { KeyboardShortcutManager.loadKeyboardShortcuts(AccuDrawKeyboardShortcuts.getDefaultShortcuts()); const shortcutA = KeyboardShortcutManager.getShortcut("a"); expect(shortcutA).to.not.be.undefined; const shortcutR = KeyboardShortcutManager.getShortcut("r"); expect(shortcutR).to.not.be.undefined; }); });
the_stack
import { V, Variable } from "./v"; import { assert, assume } from "../utils"; import { ParsedMaki, Command, Method } from "./parser"; import { getClass, getMethod } from "./objects"; import { classResolver } from "../skin/resolver"; function validateMaki(program: ParsedMaki) { /* for (const v of program.variables) { validateVariable(v); } */ return; // Comment this out to get warnings about missing methods for (const method of program.methods) { if (method.name.startsWith("on")) { continue; } const guid = program.classes[method.typeOffset]; const methodDefinition = getMethod(guid, method.name); const klass = classResolver(guid); const impl = klass.prototype[method.name]; if (!impl) { const classDefinition = getClass(guid); console.warn(`Expected to find ${classDefinition.name}.${method.name}`); } else if (impl.length != methodDefinition.parameters.length) { throw new Error("Arity Error"); } } } export function interpret( start: number, program: ParsedMaki, stack: Variable[], classResolver: (guid: string) => any ) { validateMaki(program); const interpreter = new Interpreter(program, classResolver); interpreter.stack = stack; return interpreter.interpret(start); } function validateVariable(v: Variable) { if (v.type === "OBJECT" && typeof v.value !== "object") { debugger; } } class Interpreter { stack: Variable[]; callStack: number[]; classes: string[]; variables: Variable[]; methods: Method[]; commands: Command[]; debug: boolean = false; classResolver: (guid: string) => any; constructor(program: ParsedMaki, classResolver: (guid: string) => any) { const { commands, methods, variables, classes } = program; this.classResolver = classResolver; this.commands = commands; this.methods = methods; this.variables = variables; this.classes = classes; this.stack = []; this.callStack = []; /* for (const v of this.variables) { validateVariable(v); } */ } push(variable: Variable) { this.stack.push(variable); } interpret(start: number) { for (const v of this.variables) { validateVariable(v); } // Instruction Pointer let ip = start; while (ip < this.commands.length) { const command = this.commands[ip]; if (this.debug) { console.log(command); } switch (command.opcode) { // push case 1: { const offsetIntoVariables = command.arg; this.push(this.variables[offsetIntoVariables]); break; } // pop case 2: { this.stack.pop(); break; } // popTo case 3: { const a = this.stack.pop(); const offsetIntoVariables = command.arg; const current = this.variables[offsetIntoVariables]; assume( typeof a.value === typeof current.value || current.value == null, `Assigned from one type to a different type ${typeof a.value}, ${typeof current.value}.` ); current.value = a.value; break; } // == case 8: { const a = this.stack.pop(); const b = this.stack.pop(); assume( typeof a.value == typeof b.value, `Tried to compare a ${a.type} to a ${b.type}.` ); const result = V.newInt(b.value === a.value); this.push(result); break; } // != case 9: { const a = this.stack.pop(); const b = this.stack.pop(); /* It's fine to compare objects to null assume( a.type == b.type, `Tried to compare a ${a.type} to a ${b.type}.` ); */ const result = V.newInt(b.value !== a.value); this.push(result); break; } // > case 10: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } if (this.debug) { console.log(`${b.value} > ${a.value}`); } this.push(V.newInt(b.value > a.value)); break; } // >= case 11: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } if (this.debug) { console.log(`${b.value} >= ${a.value}`); } this.push(V.newInt(b.value >= a.value)); break; break; } // < case 12: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } if (this.debug) { console.log(`${b.value} < ${a.value}`); } this.push(V.newInt(b.value < a.value)); break; } // <= case 13: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } if (this.debug) { console.log(`${b.value} < ${a.value}`); } this.push(V.newInt(b.value <= a.value)); break; } // jumpIf case 16: { const value = this.stack.pop(); // This seems backwards. Seems like we're doing a "jump if not" if (value.value) { break; } ip = command.arg - 1; break; } // jumpIfNot case 17: { const value = this.stack.pop(); // This seems backwards. Same as above if (!value.value) { break; } ip = command.arg - 1; break; } // jump case 18: { ip = command.arg - 1; break; } // call // strangeCall (seems to behave just like regular call) case 24: case 112: { const methodOffset = command.arg; const method = this.methods[methodOffset]; let methodName = method.name; const returnType = method.returnType; const classesOffset = method.typeOffset; methodName = methodName.toLowerCase(); const guid = this.classes[classesOffset]; const klass = this.classResolver(guid); if (!klass) { throw new Error("Need to add a missing class to runtime"); } // This is a bit awkward. Because the variables are stored on the stack // before the object, we have to find the number of arguments without // actually having access to the object instance. if (!klass.prototype[methodName]) { throw new Error( `Need to add missing method: ${klass.name}.${methodName}: ${returnType}` ); } let argCount: number = klass.prototype[methodName].length; const methodDefinition = getMethod(guid, methodName); assert( argCount === (methodDefinition.parameters.length ?? 0), `Arg count mismatch. Expected ${ methodDefinition.parameters.length ?? 0 } arguments, but found ${argCount} for ${klass.name}.${methodName}` ); const methodArgs = []; while (argCount--) { const a = this.stack.pop(); methodArgs.push(a.value); } const obj = this.stack.pop(); assert( (obj.type === "OBJECT" && typeof obj.value) === "object" && obj.value != null, `Guru Meditation: Tried to call method ${klass.name}.${methodName} on null object` ); let value = obj.value[methodName](...methodArgs); if (value === undefined && returnType !== "NULL") { throw new Error( `Did not expect ${klass.name}.${methodName}: ${returnType} to return undefined` ); } if (value === null) { // variables[1] holds global NULL value value = this.variables[1]; } if (returnType === "BOOLEAN") { assert(typeof value === "boolean", "BOOL should return a boolean"); value = value ? 1 : 0; } if (returnType === "OBJECT") { assert( typeof value === "object", `Expected the returned value of ${klass.name}.${methodName} to be an object, but it was "${value}"` ); } if (this.debug) { console.log(`Calling method ${methodName}`); } this.push({ type: returnType, value } as any); break; } // callGlobal case 25: { this.callStack.push(ip); const offset = command.arg; ip = offset - 1; // -1 because we ++ after the switch break; } // return case 33: { ip = this.callStack.pop(); // TODO: Stack protection? break; } // complete case 40: { // noop for now // assume(false, "OPCODE: complete"); break; } // mov case 48: { const a = this.stack.pop(); const b = this.stack.pop(); /* assume( a.type === b.type, `Type mismatch: ${a.type} != ${b.type} at ip: ${ip}` ); */ b.value = a.value; this.push(a); break; } // postinc case 56: { const a = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to increment a non-number."); } const aValue = a.value; a.value = aValue + 1; this.push({ type: a.type, value: aValue }); break; } // postdec case 57: { const a = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to decrement a non-number."); } const aValue = a.value; a.value = aValue - 1; this.push({ type: a.type, value: aValue }); break; } // preinc case 58: { const a = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to increment a non-number."); } a.value++; this.push(a); break; } // predec case 59: { const a = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to increment a non-number."); } a.value--; this.push(a); break; } // + (add) case 64: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "OBJECT": case "BOOLEAN": case "NULL": throw new Error( `Tried to add non-numbers: ${b.type} + ${a.type}.` ); case "STRING": if (b.type !== "STRING") { throw new Error( `Tried to add string and a non-string: ${b.type} + ${a.type}.` ); } } switch (b.type) { case "OBJECT": case "BOOLEAN": throw new Error("Tried to add non-numbers."); } // TODO: Do we need to round the value if INT? this.push({ type: a.type, value: b.value + a.value }); break; } // - (subtract) case 65: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } // TODO: Do we need to round the value if INT? this.push({ type: a.type, value: b.value - a.value }); break; } // * (multiply) case 66: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } // TODO: Do we need to round the value if INT? this.push({ type: a.type, value: b.value * a.value }); break; } // / (divide) case 67: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": throw new Error("Tried to add non-numbers."); } // TODO: Do we need to round the value if INT? this.push({ type: a.type, value: b.value / a.value }); break; } // % (mod) case 68: { const a = this.stack.pop(); const b = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": throw new Error("Tried to add non-numbers."); // Need to coerce LHS if not int, RHS is always int (enforced by compiler) case "FLOAT": case "DOUBLE": const value = Math.floor(b.value) % a.value; this.push({ type: a.type, value }); break; case "INT": this.push({ type: a.type, value: b.value % a.value }); break; } break; } // & (binary and) case 72: { assume(false, "Unimplimented & operator"); break; } // | (binary or) case 73: { assume(false, "Unimplimented | operator"); break; } // ! (not) case 74: { const a = this.stack.pop(); this.push(V.newInt(!a.value)); break; } // - (negative) case 76: { const a = this.stack.pop(); switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } this.push({ type: a.type, value: -a.value }); break; } // logAnd (&&) case 80: { const a = this.stack.pop(); const b = this.stack.pop(); // Some of these are probably valid, but we'll enable them once we see usage. switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } if (b.value && a.value) { this.push(a); } else { this.push(b); } break; } // logOr || case 81: { const a = this.stack.pop(); const b = this.stack.pop(); // Some of these are probably valid, but we'll enable them once we see usage. switch (a.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } switch (b.type) { case "STRING": case "OBJECT": case "BOOLEAN": case "NULL": throw new Error("Tried to add non-numbers."); } if (b.value) { this.push(b); } else { this.push(a); } break; } // << case 88: { assume(false, "Unimplimented << operator"); break; } // >> case 89: { assume(false, "Unimplimented >> operator"); break; } // new case 96: { const classesOffset = command.arg; const guid = this.classes[classesOffset]; const Klass = this.classResolver(guid); const klassInst = new Klass(); this.push({ type: "OBJECT", value: klassInst }); break; } // delete case 97: { const aValue = this.stack.pop(); // TODO: Cleanup the object? break; } default: throw new Error(`Unhandled opcode ${command.opcode}`); } ip++; /* for (const v of this.variables) { validateVariable(v); } */ } } }
the_stack
/// <reference types="node" /> export {}; /** * A set of commonly understood string names for types to help with completions. */ export type NamedType = "string" | "pointer" | keyof TypesDefaultRegistry | `${keyof TypesDefaultRegistry}${"*" | " *" | "**" | " **"}`; /** * Base constraint for a type understood by the package. */ export type TypeLike = Type | string; /** * Base constraint for a type understood by the package. This is similar to {@link TypeLike} but is more restrictive. Its * primary use is in overloads that take {@link TypeLike} in order to improve completions. */ export type NamedTypeLike = Type | NamedType; /** * A type-space registry of type names to their JS types (allows for overrides of defaults) * * If you find a type is too specific for your use case, you can modify {@link UnderlyingTypeOverrideRegistry} using * a module augmentation: * * ```ts * declare module "ref-napi" { * interface UnderlyingTypeOverrideRegistry { * int64: SomeOtherType; * } * } * ``` */ export interface UnderlyingTypeOverrideRegistry { // tslint:disable-line no-empty-interface } /** * A type-space registry of type names to their JS types. * * **Do not augment this type.** If you find a type is too specific for your use case, you can modify * {@link UnderlyingTypeOverrideRegistry} using module augmentation: * * ```ts * declare module "ref-napi" { * interface UnderlyingTypeOverrideRegistry { * int64: SomeOtherType; * } * } * ``` */ export interface UnderlyingTypeDefaultRegistry { "void": void; // tslint:disable-line void-return "bool": boolean; "int8": number; "uint8": number; "int16": number; "uint16": number; "int32": number; "uint32": number; "float": number; "double": number; "byte": number; "char": number; "uchar": number; "short": number; "ushort": number; "int": number; "uint": number; "int64": string | number; "uint64": string | number; "long": string | number; "longlong": string | number; "ulong": string | number; "ulonglong": string | number; "size_t": string | number; "Object": unknown; "CString": string | null; "pointer": Pointer<unknown>; "string": string | null; "char*": string; "char *": string; "byte*": Buffer | Pointer<number>; "byte *": Buffer | Pointer<number>; "void*": Pointer<unknown>; "void *": Pointer<unknown>; } /** * A type-space registry of type names to their JS types. * * **Do not augment this type.** If you find a type is too specific for your use case, you can modify * {@link UnderlyingTypeOverrideRegistry} using module augmentation: * * ```ts * declare module "ref-napi" { * interface UnderlyingTypeOverrideRegistry { * "long": SomeOtherType; * } * } * ``` */ export interface UnderlyingTypeRegistry extends Omit<UnderlyingTypeDefaultRegistry, keyof UnderlyingTypeOverrideRegistry>, UnderlyingTypeOverrideRegistry { } // Helper type that trims leading and trailing spaces from a string type Trim<S extends string> = // NOTE: look for double and single space characters to reduce recursion S extends ` ${infer U}` ? Trim<U> : S extends ` ${infer U}` ? Trim<U> : S extends `${infer U} ` ? Trim<U> : S extends `${infer U} ` ? Trim<U> : S; /** * Gets the underlying type for a {@link Type} or {@link BaseNamedType}. */ export type UnderlyingType<T extends TypeLike> = T extends Type<infer U> ? U : // Allow for user-defined type overrides T extends keyof UnderlyingTypeOverrideRegistry ? UnderlyingTypeOverrideRegistry[T] : // Use default type map T extends keyof UnderlyingTypeRegistry ? UnderlyingTypeRegistry[T] : // Coerce pointer types into relevant references. T extends `${infer U}*` ? Trim<U> extends "char" ? string | null : // `char*` is a string type Trim<U> extends "byte" ? Buffer | Pointer<number> : // `byte*` is either a `Buffer` or a `Pointer` to a single byte Trim<U> extends "void" ? Pointer<unknown> : // `void*` is a `Pointer` to some unknown value. Pointer<UnderlyingType<U>> : // Treat this as a `Pointer` to the underlying type. unknown; /** * Helper type to get a tuple of the underlying types of a tuple of {@link TypeLike} types. */ export type UnderlyingTypes<T extends readonly TypeLike[]> = Extract<{ [P in keyof T]: P extends `${number}` ? UnderlyingType<Extract<T[P], TypeLike>> : T[P]; }, any[]>; /** * Coerces a {@link TypeLike} to a {@link Type}. */ export type CoerceType<T extends TypeLike> = Type<UnderlyingType<T>>; /** * Helper type to coerce a tuple of {@link TypeLike} types to a tuple of {@link Type} types. */ export type CoerceTypes<T extends readonly TypeLike[]> = Extract<{ [P in keyof T]: P extends `${number}` ? CoerceType<Extract<T[P], TypeLike>> : T[P]; }, any[]>; /** * Dereferences a type */ export type DerefType<T extends TypeLike> = UnderlyingType<T> extends Pointer<infer U> ? Type<U> : never; /** * Helper type to deref a tuple of {@link TypeLike} types to a tuple of {@link Type} types. */ export type DerefTypes<T extends readonly TypeLike[]> = Extract<{ [P in keyof T]: P extends `${number}` ? DerefType<Extract<T[P], TypeLike>> : T[P]; }, any[]>; /** * A typed pointer. */ export interface Pointer<T> extends Buffer { ref(): Pointer<Pointer<T>>; deref(): T; type: Type<T>; } /** * A buffer representing a value. */ export interface Value<T> extends Buffer { ref(): Pointer<T>; deref(): never; type: Type<T>; } export interface Type<T = any> { /** The size in bytes required to hold this datatype. */ size: number; /** The current level of indirection of the buffer. */ indirection: number; /** To invoke when `ref.get` is invoked on a buffer of this type. */ get(buffer: Buffer, offset: number): T; /** To invoke when `ref.set` is invoked on a buffer of this type. */ set(buffer: Buffer, offset: number, value: T): void; /** The name to use during debugging for this datatype. */ name?: string | undefined; /** The alignment of this datatype when placed inside a struct. */ alignment?: number | undefined; } /** A Buffer that references the C NULL pointer. */ export declare var NULL: Value<null>; /** A pointer-sized buffer pointing to NULL. */ export declare var NULL_POINTER: Pointer<Value<null>>; /** Get the memory address of buffer. */ export declare function address(buffer: Buffer): number; /** Get the memory address of buffer. */ export declare function hexAddress(buffer: Buffer): string; /** Allocate the memory with the given value written to it. */ export declare function alloc<TType extends NamedType>(type: TType, value?: UnderlyingType<TType>): [UnderlyingType<TType>] extends [never] | [0] ? Value<any> : UnderlyingType<TType> extends Buffer ? UnderlyingType<TType> : Value<UnderlyingType<TType>>; /** Allocate the memory with the given value written to it. */ export declare function alloc<TType extends TypeLike>(type: TType, value?: UnderlyingType<TType>): [UnderlyingType<TType>] extends [never] | [0] ? Value<any> : UnderlyingType<TType> extends Buffer ? UnderlyingType<TType> : Value<UnderlyingType<TType>>; /** * Allocate the memory with the given string written to it with the given * encoding (defaults to utf8). The buffer is 1 byte longer than the * string itself, and is NULL terminated. */ export declare function allocCString(string: string, encoding?: BufferEncoding): Value<string>; export declare function allocCString(string: string | null, encoding?: BufferEncoding): Value<string | null>; /** Coerce a type. String are looked up from the ref.types object. */ export declare function coerceType<T extends NamedType>(type: T): Type<UnderlyingType<T>>; export declare function coerceType<T extends TypeLike>(type: T): Type<UnderlyingType<T>>; /** * Get value after dereferencing buffer. * That is, first it checks the indirection count of buffer's type, and * if it's greater than 1 then it merely returns another Buffer, but with * one level less indirection. */ export declare function deref<T>(buffer: Pointer<T>): T; export declare function deref(buffer: Buffer): any; /** Create clone of the type, with decremented indirection level by 1. */ export declare function derefType<T extends NamedType>(type: T): DerefType<T>; export declare function derefType<T extends TypeLike>(type: T): DerefType<T>; export declare function derefType(type: TypeLike): Type; /** Represents the native endianness of the processor ("LE" or "BE"). */ export declare var endianness: "LE" | "BE"; /** Check the indirection level and return a dereferenced when necessary. */ export declare function get<T>(buffer: Pointer<T> | Value<T>, offset?: 0): T; export declare function get<T extends NamedType>(buffer: Buffer, offset: number | undefined, type: T): UnderlyingType<T>; export declare function get<T extends TypeLike>(buffer: Buffer, offset: number | undefined, type: T): UnderlyingType<T>; export declare function get(buffer: Buffer, offset?: number, type?: TypeLike): any; /** Get type of the buffer. Create a default type when none exists. */ export declare function getType<T>(buffer: Pointer<T>): Type<T>; export declare function getType(buffer: Buffer): Type; /** Check the NULL. */ export declare function isNull(buffer: Buffer): boolean; /** Read C string until the first NULL. */ export declare function readCString(buffer: Buffer, offset?: number): string; /** * Read a big-endian signed 64-bit int. * If there is losing precision, then return a string, otherwise a number. * @return {number|string} */ export declare function readInt64BE(buffer: Buffer, offset?: number): number | string; /** * Read a little-endian signed 64-bit int. * If there is losing precision, then return a string, otherwise a number. * @return {number|string} */ export declare function readInt64LE(buffer: Buffer, offset?: number): number | string; /** Read a JS Object that has previously been written. */ export declare function readObject<T>(buffer: Pointer<T>, offset?: 0): T; export declare function readObject(buffer: Buffer, offset?: number): Object; /** Read data from the pointer. */ export declare function readPointer(buffer: Buffer, offset?: number, length?: number): Buffer; /** * Read a big-endian unsigned 64-bit int. * If there is losing precision, then return a string, otherwise a number. * @return {number|string} */ export declare function readUInt64BE(buffer: Buffer, offset?: number): string | number; /** * Read a little-endian unsigned 64-bit int. * If there is losing precision, then return a string, otherwise a number. * @return {number|string} */ export declare function readUInt64LE(buffer: Buffer, offset?: number): string | number; /** Create pointer to buffer. */ export declare function ref<T>(buffer: Pointer<T>): Pointer<Pointer<T>>; export declare function ref<T>(buffer: Value<T>): Pointer<T>; export declare function ref(buffer: Buffer): Buffer; /** Create clone of the type, with incremented indirection level by 1. */ export declare function refType<T extends NamedTypeLike>(type: T): Type<Pointer<UnderlyingType<T>>>; export declare function refType<T extends TypeLike>(type: T): Type<Pointer<UnderlyingType<T>>>; export declare function refType(type: TypeLike): Type; /** * Create buffer with the specified size, with the same address as source. * This function "attaches" source to the returned buffer to prevent it from * being garbage collected. */ export declare function reinterpret(buffer: Buffer, size: number, offset?: number): Buffer; /** * Scan past the boundary of the buffer's length until it finds size number * of aligned NULL bytes. */ export declare function reinterpretUntilZeros(buffer: Buffer, size: number, offset?: number): Buffer; /** Write pointer if the indirection is 1, otherwise write value. */ export declare function set<T>(buffer: Pointer<T> | Value<T>, offset: 0, value: T): void; export declare function set<T extends NamedType>(buffer: Buffer, offset: number, value: UnderlyingType<T>, type: T): void; export declare function set<T extends TypeLike>(buffer: Buffer, offset: number, value: UnderlyingType<T>, type: T): void; export declare function set(buffer: Buffer, offset: number, value: any, type?: TypeLike): void; /** Write the string as a NULL terminated. Default encoding is utf8. */ export declare function writeCString(buffer: Buffer, offset: number, string: string, encoding?: BufferEncoding): void; /** Write a big-endian signed 64-bit int. */ export declare function writeInt64BE(buffer: Buffer, offset: number, input: string | number): void; /** Write a little-endian signed 64-bit int. */ export declare function writeInt64LE(buffer: Buffer, offset: number, input: string | number): void; /** * Write the JS Object. This function "attaches" object to buffer to prevent * it from being garbage collected. */ export declare function writeObject<T>(buffer: Value<T>, offset: 0, object: T): void; export declare function writeObject(buffer: Buffer, offset: number, object: Object): void; /** * Write the memory address of pointer to buffer at the specified offset. This * function "attaches" object to buffer to prevent it from being garbage collected. */ export declare function writePointer(buffer: Buffer, offset: number, pointer: Buffer): void; /** Write a big-endian unsigned 64-bit int. */ export declare function writeUInt64BE(buffer: Buffer, offset: number, input: string | number): void; /** Write a little-endian unsigned 64-bit int. */ export declare function writeUInt64LE(buffer: Buffer, offset: number, input: string | number): void; /** * Attach object to buffer such. * It prevents object from being garbage collected until buffer does. */ export declare function _attach(buffer: Buffer, object: Object): void; /** Same as ref.reinterpret, except that this version does not attach buffer. */ export declare function _reinterpret(buffer: Buffer, size: number, offset?: number): Buffer; /** Same as ref.reinterpretUntilZeros, except that this version does not attach buffer. */ export declare function _reinterpretUntilZeros(buffer: Buffer, size: number, offset?: number): Buffer; /** Same as ref.writePointer, except that this version does not attach pointer. */ export declare function _writePointer(buffer: Buffer, offset: number, pointer: Buffer): void; /** Same as ref.writeObject, except that this version does not attach object. */ export declare function _writeObject<T>(buffer: Value<T>, offset: 0, object: T): void; export declare function _writeObject(buffer: Buffer, offset: number, object: Object): void; /** * A registry of user-defined type names to {@link Type} instances known to `ref-napi`. * * If you find a type is too specific for your use case, you can modify {@link TypesOverrideRegistry} using * module augmentation: * * ```ts * declare module "ref-napi" { * interface TypesOverrideRegistry { * int64: Type<SomeOtherType>; * } * } * ``` */ export interface TypesOverrideRegistry { // tslint:disable-line no-empty-interface } /** * A registry of default type names to {@link Type} types known to `ref-napi`. * * **Do not augment this type.** If you find a type is too specific for your use case, you can modify * {@link TypesOverrideRegistry} using module augmentation: * * ```ts * declare module "ref-napi" { * interface TypesOverrideRegistry { * int64: Type<SomeOtherType>; * } * } * ``` */ export interface TypesDefaultRegistry { void: Type<void>; int64: Type<string | number>; ushort: Type<number>; int: Type<number>; uint64: Type<string | number>; float: Type<number>; uint: Type<number>; long: Type<string | number>; double: Type<number>; int8: Type<number>; ulong: Type<string | number>; Object: Type<unknown>; uint8: Type<number>; longlong: Type<string | number>; CString: Type<string | null>; int16: Type<number>; ulonglong: Type<string | number>; bool: Type<boolean>; uint16: Type<number>; char: Type<number>; byte: Type<number>; int32: Type<number>; uchar: Type<number>; size_t: Type<string | number>; uint32: Type<number>; short: Type<number>; } /** * A combined registry of default and overridden type names to {@link Type} types known to `ref-napi`. * * **Do not augment this type.** If you find a type is too specific for your use case, you can modify * {@link TypesOverrideRegistry} using module augmentation: * * ```ts * declare module "ref-napi" { * interface TypesOverrideRegistry { * int64: Type<SomeOtherType>; * } * } * ``` */ export interface TypesRegistry extends Omit<TypesDefaultRegistry, keyof TypesOverrideRegistry>, TypesOverrideRegistry { } /** Default types. */ export declare var types: TypesRegistry; /** * A registry of type names to their alignments. * * NOTE: This is not a 1:1 correspondence with {@link TypesDefaultRegistry} as it excludes {@link TypesDefaultRegistry.void} and * {@link TypesDefaultRegistry.CString}, but includes {@link AlignofRegistry.pointer}. */ export interface AlignofRegistry { pointer: number; int64: number; ushort: number; int: number; uint64: number; float: number; uint: number; long: number; double: number; int8: number; ulong: number; Object: number; uint8: number; longlong: number; int16: number; ulonglong: number; bool: number; uint16: number; char: number; byte: number; int32: number; uchar: number; size_t: number; uint32: number; short: number; } /** Default type alignments. */ export declare var alignof: AlignofRegistry; /** * A registry of type names to their sizes. * * NOTE: This is not a 1:1 correspondence with {@link TypesDefaultRegistry} as it excludes {@link TypesDefaultRegistry.void} and * {@link TypesDefaultRegistry.CString}, but includes {@link SizeofRegistry.pointer}. */ export interface SizeofRegistry { pointer: number; int64: number; ushort: number; int: number; uint64: number; float: number; uint: number; long: number; double: number; int8: number; ulong: number; Object: number; uint8: number; longlong: number; int16: number; ulonglong: number; bool: number; uint16: number; char: number; byte: number; int32: number; uchar: number; size_t: number; uint32: number; short: number; } /** Default type sizes. */ export declare var sizeof: SizeofRegistry; declare global { interface Buffer { address(): number; hexAddress(): string; isNull(): boolean; ref(): Buffer; deref(): any; readObject(offset?: number): Object; writeObject(object: Object, offset?: number): void; readPointer(offset?: number, length?: number): Buffer; writePointer(pointer: Buffer, offset?: number): void; readCString(offset?: number): string; writeCString(string: string, offset?: number, encoding?: string): void; readInt64BE(offset?: number): string | number; writeInt64BE(input: string | number, offset?: number): void; readUInt64BE(offset?: number): string | number; writeUInt64BE(input: string | number, offset?: number): void; readInt64LE(offset?: number): string | number; writeInt64LE(input: string | number, offset?: number): void; readUInt64LE(offset?: number): string | number; writeUInt64LE(input: string | number, offset?: number): void; reinterpret(size: number, offset?: number): Buffer; reinterpretUntilZeros(size: number, offset?: number): Buffer; type?: Type | undefined; } }
the_stack
import { PHASE } from "../../common"; import { idb } from "../db"; import g from "./g"; import type { TeamFiltered } from "../../common/types"; import { getPlayers, getTopPlayers } from "../core/season/awards"; import { dpoyScore, makeTeams, mvpScore, } from "../core/season/doAwards.football"; import advStatsSave from "./advStatsSave"; import { groupByUnique } from "../../common/groupBy"; type Team = TeamFiltered< ["tid"], undefined, [ "gp", "ptsPerDrive", "oppPtsPerDrive", "pts", "oppPts", "drives", "pss", "pssYds", "pssTD", "pssInt", "rus", "rusYds", "rec", "recYds", "fga0", "fga20", "fga30", "fga40", "fga50", "xpa", "pnt", "pntYds", "pntBlk", ], number >; const TCK_CONSTANT = { DL: 0.6, LB: 0.3, CB: 0, S: 0, }; const DEFENSIVE_POSITIONS = ["DL", "LB", "CB", "S"] as const; // Approximate Value: https://www.sports-reference.com/blog/approximate-value-methodology/ const calculateAV = (players: any[], teamsInput: Team[], league: any) => { const teams = teamsInput.map(t => { const offPts = league.ptsPerDrive === 0 ? 0 : (100 * t.stats.ptsPerDrive) / league.ptsPerDrive; const ptsOL = (5 / 11) * offPts; const ptsSkill = offPts - ptsOL; const ptsRus = t.stats.rusYds + t.stats.recYds === 0 ? 0 : (ptsSkill * 0.22 * (t.stats.rusYds / (t.stats.rusYds + t.stats.recYds))) / 0.37; const ptsPss = (ptsSkill - ptsRus) * 0.26; const ptsRec = (ptsSkill - ptsRus) * 0.74; let defPts = 0; if (league.ptsPerDrive !== 0) { const M = t.stats.oppPtsPerDrive / league.ptsPerDrive; defPts = (100 * (1 + 2 * M - M ** 2)) / (2 * M); } const ptsFront7 = (2 / 3) * defPts; const ptsSecondary = (1 / 3) * defPts; const kPlayingTime = t.stats.xpa + 3 * (t.stats.fga0 + t.stats.fga20 + t.stats.fga30 + t.stats.fga40 + t.stats.fga50); return { ...t, stats: { ...t.stats, ptsOL, ptsRus, ptsPss, ptsRec, ptsFront7, ptsSecondary, individualPtsOL: 0, individualPtsFront7: 0, individualPtsSecondary: 0, kPlayingTime, }, }; }); const teamsByTid = groupByUnique(teams, "tid"); const individualPts = players.map(p => { let score = 0; const t = teamsByTid[p.tid]; if (t === undefined) { throw new Error("Should never happen"); } if (p.ratings.pos === "OL" || p.ratings.pos === "TE") { const posMultiplier = p.ratings.pos === "OL" ? 1.1 : 0.2; let allProMultiplier = 1; if (p.ratings.pos === "OL") { if (p.allLeagueTeam === 0) { allProMultiplier = 1.5; } else if (p.allLeagueTeam === 1) { allProMultiplier = 1; } } score = p.stats.gp + 5 * p.stats.gs * posMultiplier * allProMultiplier; t.stats.individualPtsOL += score; } else if (DEFENSIVE_POSITIONS.includes(p.ratings.pos)) { let allProLevel = 0; if (p.allLeagueTeam === 0) { allProLevel = 1.9; } else if (p.allLeagueTeam === 1) { allProLevel = 1.6; } score = p.stats.gp + 5 * p.stats.gs + p.stats.defSk + 4 * p.stats.defFmbRec + 4 * p.stats.defInt + 5 * (p.stats.defIntTD + p.stats.defFmbTD) + // https://github.com/microsoft/TypeScript/issues/21732 // @ts-expect-error TCK_CONSTANT[p.ratings.pos] * p.stats.defTck + (allProLevel * 80 * t.stats.gp) / g.get("numGames"); if (p.ratings.pos === "DL" || p.ratings.pos === "LB") { t.stats.individualPtsFront7 += score; } else { t.stats.individualPtsSecondary += score; } } return score; }); const av = players.map((p, i) => { let score = 0; const t = teamsByTid[p.tid]; if (t === undefined) { throw new Error("Should never happen"); } // OL if (p.ratings.pos === "OL" || p.ratings.pos === "TE") { score += (individualPts[i] / t.stats.individualPtsOL) * t.stats.ptsOL; } // Rushing score += (p.stats.rusYds / t.stats.rusYds) * t.stats.ptsRus; if (p.stats.rus / p.stats.gp >= 200 / 16) { if (p.stats.rusYdsPerAtt > league.rusYdsPerAtt) { score += 0.75 * (p.stats.rusYdsPerAtt - league.rusYdsPerAtt); } else { score += 2 * (p.stats.rusYdsPerAtt - league.rusYdsPerAtt); } } // Receiving score += (p.stats.recYds / t.stats.recYds) * t.stats.ptsRec; if (p.stats.rec / p.stats.gp >= 70 / 16) { if (p.stats.recYdsPerAtt > league.recYdsPerAtt) { score += 0.5 * (p.stats.recYdsPerAtt - league.recYdsPerAtt); } else { score += 2 * (p.stats.recYdsPerAtt - league.recYdsPerAtt); } } // Passing score += (p.stats.pssYds / t.stats.pssYds) * t.stats.ptsPss; if (p.stats.pss / p.stats.gp >= 400 / 16) { if (p.stats.pssAdjYdsPerAtt > league.pssAdjYdsPerAtt) { score += 0.5 * (p.stats.pssAdjYdsPerAtt - league.pssAdjYdsPerAtt); } else { score += 2 * (p.stats.pssAdjYdsPerAtt - league.pssAdjYdsPerAtt); } } // Defense if (p.ratings.pos === "DL" || p.ratings.pos === "LB") { score += (individualPts[i] / t.stats.individualPtsFront7) * t.stats.ptsFront7; } if (p.ratings.pos === "S" || p.ratings.pos === "CB") { score += (individualPts[i] / t.stats.individualPtsSecondary) * t.stats.ptsSecondary; } // Returns score += p.stats.prTD + p.stats.krTD; // Kicking { // Ignore schedule length normalization const kPlayingTime = p.stats.xpa + 3 * (p.stats.fga0 + p.stats.fga20 + p.stats.fga30 + p.stats.fga40 + p.stats.fga50); if (kPlayingTime > 0) { let paaTotal = p.stats.xp - p.stats.xpa * league.xpp; paaTotal += 3 * (p.stats.fg0 - p.stats.fga0 * league.fgp0); paaTotal += 3 * (p.stats.fg20 - p.stats.fga20 * league.fgp20); paaTotal += 3 * (p.stats.fg30 - p.stats.fga30 * league.fgp30); paaTotal += 3 * (p.stats.fg40 - p.stats.fga40 * league.fgp40); paaTotal += 3 * (p.stats.fg50 - p.stats.fga50 * league.fgp50); const pctTeamPlayingTime = kPlayingTime / t.stats.kPlayingTime; const avgAV = 3.125 * pctTeamPlayingTime; const rawAV = avgAV + paaTotal / 5; score += rawAV; } } // Punting { // Ignore schedule length normalization if ( p.stats.pnt + p.stats.pntBlk > 0 && t.stats.pnt + t.stats.pntBlk > 0 ) { const adjPntYPA = (p.stats.pntYds - 13 * p.stats.pntBlk) / (p.stats.pnt + p.stats.pntBlk); const adjPuntYdsAboveAvg = (p.stats.pnt + p.stats.pntBlk) * (adjPntYPA - league.adjPntYPA); const pctTeamPlayingTime = (p.stats.pnt + p.stats.pntBlk) / (t.stats.pnt + t.stats.pntBlk); const avgAV = 2.1875 * pctTeamPlayingTime; const rawAV = avgAV + adjPuntYdsAboveAvg / 200; score += rawAV; } } // Adjust for GP... docs don't say to do this, but it feels right score *= t.stats.gp / g.get("numGames"); return score === Infinity ? 0 : score; }); return { av, }; }; const advStats = async () => { const playersRaw = await idb.cache.players.indexGetAll("playersByTid", [ 0, // Active players have tid >= 0 Infinity, ]); const players = await idb.getCopies.playersPlus(playersRaw, { attrs: ["pid", "tid"], stats: [ "gp", "gs", "pss", "pssYds", "pssAdjYdsPerAtt", "rus", "rusYds", "rusYdsPerAtt", "rec", "recYds", "recYdsPerAtt", "defSk", "defFmbRec", "defInt", "defIntTD", "defFmbTD", "defTck", "prTD", "krTD", "fg0", "fg20", "fg30", "fg40", "fg50", "fga0", "fga20", "fga30", "fga40", "fga50", "xp", "xpa", "pnt", "pntYds", "pntBlk", ], ratings: ["pos"], season: g.get("season"), playoffs: PHASE.PLAYOFFS === g.get("phase"), regularSeason: PHASE.PLAYOFFS !== g.get("phase"), }); const teamStats = [ "gp", "ptsPerDrive", "oppPtsPerDrive", "pts", "oppPts", "drives", "pss", "pssYds", "pssTD", "pssInt", "rus", "rusYds", "rec", "recYds", "fg0", "fg20", "fg30", "fg40", "fg50", "fga0", "fga20", "fga30", "fga40", "fga50", "xp", "xpa", "pnt", "pntYds", "pntBlk", ] as const; const teams = await idb.getCopies.teamsPlus( { attrs: ["tid"], stats: teamStats, season: g.get("season"), playoffs: PHASE.PLAYOFFS === g.get("phase"), regularSeason: PHASE.PLAYOFFS !== g.get("phase"), addDummySeason: true, active: true, }, "noCopyCache", ); const league: any = teams.reduce((memo: any, t) => { for (const key of teamStats) { if (memo.hasOwnProperty(key)) { memo[key] += t.stats[key]; } else { memo[key] = t.stats[key]; } } return memo; }, {}); league.ptsPerDrive = league.pts / league.drives; league.pssAdjYdsPerAtt = (league.pssYds + 20 * league.pssTD - 45 * league.pssInt) / league.pss; league.rusYdsPerAtt = league.rusYds / league.rus; league.recYdsPerAtt = league.recYds / league.rec; league.fgp0 = league.fg0 / league.fga0; league.fgp20 = league.fg20 / league.fga20; league.fgp30 = league.fg30 / league.fga30; league.fgp40 = league.fg40 / league.fga40; league.fgp50 = league.fg50 / league.fga50; league.xpp = league.xp / league.xpa; league.adjPntYPA = (league.pntYds - 13 * league.pntBlk) / (league.pnt + league.pntBlk); const updatedStats = { ...calculateAV(players, teams, league) }; await advStatsSave(players, playersRaw, updatedStats); // Hackily account for AV of award winners, for OL and defense. These will not exactly correspond to the "real" AV formulas, they're just intended to be simple and good enough. if (PHASE.PLAYOFFS !== g.get("phase")) { const players2 = await getPlayers(g.get("season")); const mvpPlayers = getTopPlayers( { amount: Infinity, score: mvpScore, }, players2, ); const dpoyPlayers = getTopPlayers( { amount: Infinity, score: dpoyScore, }, players2, ); const allLeague = makeTeams(mvpPlayers, dpoyPlayers); for (let i = 0; i < allLeague.length; i++) { for (const p2 of allLeague[i].players) { if (p2 && (p2.pos === "OL" || DEFENSIVE_POSITIONS.includes(p2.pos))) { const p = players.find(p3 => p3.pid === p2.pid); if (p) { p.allLeagueTeam = i; } } } } const updatedStats = { ...calculateAV(players, teams, league) }; await advStatsSave(players, playersRaw, updatedStats); } }; export default advStats;
the_stack
import { createCheckoutService, CheckoutSelectors, CheckoutService, CustomError, PaymentMethod, RequestError } from '@bigcommerce/checkout-sdk'; import { mount, ReactWrapper } from 'enzyme'; import { EventEmitter } from 'events'; import { find, merge, noop } from 'lodash'; import React, { FunctionComponent } from 'react'; import { getCart } from '../cart/carts.mock'; import { CheckoutProvider } from '../checkout'; import { getCheckout, getCheckoutPayment } from '../checkout/checkouts.mock'; import { ErrorModal } from '../common/error'; import { getStoreConfig } from '../config/config.mock'; import { getCustomer } from '../customer/customers.mock'; import { createLocaleContext, LocaleContext, LocaleContextType } from '../locale'; import { getOrder } from '../order/orders.mock'; import { getConsignment } from '../shipping/consignment.mock'; import { Button } from '../ui/button'; import { getPaymentMethod } from './payment-methods.mock'; import { PaymentMethodId } from './paymentMethod'; import Payment, { PaymentProps } from './Payment'; import PaymentForm, { PaymentFormProps } from './PaymentForm'; describe('Payment', () => { let PaymentTest: FunctionComponent<PaymentProps>; let checkoutService: CheckoutService; let checkoutState: CheckoutSelectors; let defaultProps: PaymentProps; let localeContext: LocaleContextType; let paymentMethods: PaymentMethod[]; let selectedPaymentMethod: PaymentMethod; let subscribeEventEmitter: EventEmitter; beforeEach(() => { checkoutService = createCheckoutService(); checkoutState = checkoutService.getState(); paymentMethods = [ getPaymentMethod(), { ...getPaymentMethod(), id: 'sagepay' }, { ...getPaymentMethod(), id: 'bolt', initializationData: { showInCheckout: true }}, ]; selectedPaymentMethod = paymentMethods[0]; subscribeEventEmitter = new EventEmitter(); jest.spyOn(checkoutService, 'getState') .mockImplementation(() => checkoutState); jest.spyOn(checkoutService, 'subscribe') .mockImplementation(subscriber => { subscribeEventEmitter.on('change', () => subscriber(checkoutService.getState())); subscribeEventEmitter.emit('change'); return noop; }); jest.spyOn(checkoutService, 'loadPaymentMethods') .mockResolvedValue(checkoutState); jest.spyOn(checkoutService, 'finalizeOrderIfNeeded') .mockRejectedValue({ type: 'order_finalization_not_required' }); jest.spyOn(checkoutState.data, 'getCart') .mockReturnValue(getCart()); jest.spyOn(checkoutState.data, 'getCheckout') .mockReturnValue(getCheckout()); jest.spyOn(checkoutState.data, 'getConfig') .mockReturnValue(getStoreConfig()); jest.spyOn(checkoutState.data, 'getCustomer') .mockReturnValue(getCustomer()); jest.spyOn(checkoutState.data, 'getOrder') .mockReturnValue(merge(getOrder(), { isComplete: false })); jest.spyOn(checkoutState.data, 'getPaymentMethods') .mockReturnValue(paymentMethods); jest.spyOn(checkoutState.data, 'getPaymentMethod') .mockImplementation(id => find(checkoutState.data.getPaymentMethods(), { id })); jest.spyOn(checkoutState.data, 'isPaymentDataRequired') .mockReturnValue(true); localeContext = createLocaleContext(getStoreConfig()); defaultProps = { onSubmit: jest.fn(), onSubmitError: jest.fn(), onUnhandledError: jest.fn(), }; PaymentTest = props => ( <CheckoutProvider checkoutService={ checkoutService }> <LocaleContext.Provider value={ localeContext }> <Payment { ...props } /> </LocaleContext.Provider> </CheckoutProvider> ); }); it('renders payment form with expected props', async () => { const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).props()) .toEqual(expect.objectContaining({ methods: paymentMethods, onSubmit: expect.any(Function), selectedMethod: paymentMethods[0], })); }); it('does not render amazon if multi-shipping', async () => { paymentMethods.push({ ...getPaymentMethod(), id: 'amazonpay' }); jest.spyOn(checkoutState.data, 'getConsignments') .mockReturnValue([ getConsignment(), getConsignment(), ]); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); paymentMethods.pop(); expect(container.find(PaymentForm).prop('methods')) .toEqual(paymentMethods); }); it('does not render bolt if showInCheckout is false', async () => { const expectedPaymentMethods = paymentMethods.filter(method => method.id !== PaymentMethodId.Bolt); paymentMethods[2] = { ...getPaymentMethod(), id: 'bolt', initializationData: { showInCheckout: false } }; const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).props()) .toEqual(expect.objectContaining({ methods: expectedPaymentMethods, onSubmit: expect.any(Function), selectedMethod: expectedPaymentMethods[0], })); }); it('passes initialisation status to payment form', async () => { jest.spyOn(checkoutState.statuses, 'isInitializingPayment') .mockReturnValue(true); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).prop('isInitializingPayment')) .toEqual(true); }); it('does not render payment form until initial requests are made', async () => { const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(PaymentForm).length) .toEqual(0); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).length) .toEqual(1); expect(checkoutService.loadPaymentMethods) .toHaveBeenCalled(); expect(checkoutService.finalizeOrderIfNeeded) .toHaveBeenCalled(); }); it('does not render payment form if there are no methods', () => { jest.spyOn(checkoutState.data, 'getPaymentMethods') .mockReturnValue([]); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(PaymentForm).length) .toEqual(0); }); it('does not render payment form if the current order is complete', () => { jest.spyOn(checkoutState.data, 'getOrder') .mockReturnValue(getOrder()); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(PaymentForm).length) .toEqual(0); }); it('loads payment methods when component is mounted', async () => { mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); expect(checkoutService.loadPaymentMethods) .toHaveBeenCalled(); }); it('triggers callback when payment methods are loaded', async () => { const handeReady = jest.fn(); mount(<PaymentTest { ...defaultProps } onReady={ handeReady } />); await new Promise(resolve => process.nextTick(resolve)); expect(handeReady) .toHaveBeenCalled(); }); it('calls applyStoreCredit when checkbox is clicked', async () => { jest.spyOn(checkoutState.data, 'getCustomer') .mockReturnValue({ ...getCustomer(), storeCredit: 10, }); jest.spyOn(checkoutService, 'applyStoreCredit') .mockResolvedValue(checkoutState); const component = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); component.update(); component.find('input[name="useStoreCredit"]') .simulate('change', { target: { checked: false, name: 'useStoreCredit' } }); expect(checkoutService.applyStoreCredit) .toHaveBeenCalledWith(false); }); it('sets default selected payment method', async () => { const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).prop('selectedMethod')) .toEqual(paymentMethods[0]); }); it('sets default selected payment method to the one with default stored instrument', async () => { paymentMethods[1].config.hasDefaultStoredInstrument = true; const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).props()) .toEqual(expect.objectContaining({ methods: paymentMethods, selectedMethod: paymentMethods[1], })); }); it('renders PaymentForm with usableStoreCredit=0 when grandTotal=0', async () => { jest.spyOn(checkoutState.data, 'getCheckout') .mockReturnValue({ ...getCheckout(), grandTotal: 0, }); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).prop('usableStoreCredit')) .toEqual(0); }); it('renders PaymentForm with grandTotal as usableStoreCredit when usableStoreCredit > grandTotal', async () => { jest.spyOn(checkoutState.data, 'getCheckout') .mockReturnValue({ ...getCheckout(), grandTotal: 20, }); jest.spyOn(checkoutState.data, 'getCustomer') .mockReturnValue({ ...getCustomer(), storeCredit: 100, }); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).prop('usableStoreCredit')) .toEqual(20); }); it('sets selected hosted payment as default selected payment method and filters methods prop to the hosted payment only', async () => { jest.spyOn(checkoutState.data, 'getCheckout') .mockReturnValue({ ...getCheckout(), payments: [{ ...getCheckoutPayment(), providerId: paymentMethods[1].id, }], }); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).props()) .toEqual(expect.objectContaining({ methods: [paymentMethods[1]], selectedMethod: paymentMethods[1], })); }); it('updates default selected payment method when list changes', async () => { const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); expect(container.find(PaymentForm).prop('selectedMethod')) .toEqual(paymentMethods[0]); // Update the list of payment methods so that its order is reversed checkoutState = merge({}, checkoutState, { data: { getPaymentMethods: jest.fn(() => ([paymentMethods[1], paymentMethods[0]])), }, }); subscribeEventEmitter.emit('change'); container.update(); expect(container.find(PaymentForm).prop('selectedMethod')) .toEqual(paymentMethods[1]); }); it('tries to finalize order when component is mounted', async () => { mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); expect(checkoutService.finalizeOrderIfNeeded) .toHaveBeenCalled(); }); it('triggers completion handler if order is finalized successfully', async () => { jest.spyOn(checkoutService, 'finalizeOrderIfNeeded') .mockResolvedValue(checkoutState); const handleFinalize = jest.fn(); mount(<PaymentTest { ...defaultProps } onFinalize={ handleFinalize } />); await new Promise(resolve => process.nextTick(resolve)); expect(handleFinalize) .toHaveBeenCalled(); }); it('triggers error handler if unable to finalize', async () => { jest.spyOn(checkoutService, 'finalizeOrderIfNeeded') .mockRejectedValue({ type: 'unknown_error' }); const handleFinalizeError = jest.fn(); mount(<PaymentTest { ...defaultProps } onFinalizeError={ handleFinalizeError } />); await new Promise(resolve => process.nextTick(resolve)); expect(handleFinalizeError) .toHaveBeenCalled(); }); it('does not trigger error handler if finalization is not required', async () => { const handleFinalizeError = jest.fn(); mount(<PaymentTest { ...defaultProps } onFinalizeError={ handleFinalizeError } />); await new Promise(resolve => process.nextTick(resolve)); expect(handleFinalizeError) .not.toHaveBeenCalled(); }); it('checks if available payment methods are supported in embedded mode', () => { const checkEmbeddedSupport = jest.fn(); mount(<PaymentTest { ...defaultProps } checkEmbeddedSupport={ checkEmbeddedSupport } />); expect(checkEmbeddedSupport) .toHaveBeenCalledWith(paymentMethods.map(({ id }) => id)); }); it('renders error modal if there is error when submitting order', () => { jest.spyOn(checkoutState.errors, 'getSubmitOrderError') .mockReturnValue({ type: 'payment_method_invalid' } as CustomError); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(ErrorModal)) .toHaveLength(1); }); it('does not render error modal when there is cancellation error', () => { jest.spyOn(checkoutState.errors, 'getSubmitOrderError') .mockReturnValue({ type: 'payment_cancelled' } as CustomError); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(ErrorModal)) .toHaveLength(0); }); it('does not render error modal when there is spam protection not completed error', () => { jest.spyOn(checkoutState.errors, 'getSubmitOrderError') .mockReturnValue({ type: 'spam_protection_not_completed' } as CustomError); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(ErrorModal)) .toHaveLength(0); }); it('does not render error modal when there is invalid payment form error', () => { jest.spyOn(checkoutState.errors, 'getSubmitOrderError') .mockReturnValue({ type: 'payment_invalid_form' } as CustomError); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(ErrorModal)) .toHaveLength(0); }); it('does not render error modal when there is invalid hosted form value error', () => { jest.spyOn(checkoutState.errors, 'getSubmitOrderError') .mockReturnValue({ type: 'invalid_hosted_form_value' } as CustomError); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(ErrorModal)) .toHaveLength(0); }); it('renders error modal if there is error when finalizing order', () => { jest.spyOn(checkoutState.errors, 'getFinalizeOrderError') .mockReturnValue({ type: 'request' } as CustomError); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(ErrorModal)) .toHaveLength(1); }); it('redirects to location error header when error type is provider_error', () => { jest.spyOn(window.top.location, 'assign') .mockImplementation(); jest.spyOn(checkoutState.errors, 'getFinalizeOrderError') .mockReturnValue({ type: 'request', body: { type: 'provider_error' }, headers: { location: 'foo' }, } as unknown as RequestError); const container = mount(<PaymentTest { ...defaultProps } />); container.find(Button).simulate('click'); expect(window.top.location.assign).toHaveBeenCalledWith('foo'); }); it('does not render error modal if order does not need to finalize', () => { jest.spyOn(checkoutState.errors, 'getFinalizeOrderError') .mockReturnValue({ type: 'order_finalization_not_required' } as CustomError); const container = mount(<PaymentTest { ...defaultProps } />); expect(container.find(ErrorModal)) .toHaveLength(0); }); it('passes validation schema to payment form', async () => { const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); const form: ReactWrapper<PaymentFormProps> = container.find(PaymentForm); try { // tslint:disable-next-line:no-non-null-assertion form.prop('validationSchema')!.validateSync({ ccNumber: '' }); } catch (error) { expect(error.name) .toEqual('ValidationError'); } }); it('submits order with payment data if payment is required', async () => { jest.spyOn(checkoutState.data, 'isPaymentDataRequired') .mockReturnValue(true); jest.spyOn(checkoutState.data, 'isPaymentDataSubmitted') .mockReturnValue(false); jest.spyOn(checkoutService, 'submitOrder') .mockResolvedValue(checkoutState); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); const form: ReactWrapper<PaymentFormProps> = container.find(PaymentForm); // tslint:disable-next-line:no-non-null-assertion form.prop('onSubmit')!({ ccCvv: '123', ccExpiry: '10 / 25', ccName: 'test', ccNumber: '4111 1111 1111 1111', paymentProviderRadio: selectedPaymentMethod.id, }); expect(checkoutService.submitOrder) .toHaveBeenCalledWith({ payment: { methodId: selectedPaymentMethod.id, gatewayId: selectedPaymentMethod.gateway, paymentData: { ccCvv: '123', ccExpiry: { month: '10', year: '2025', }, ccName: 'test', ccNumber: '4111111111111111', }, }, }); }); it('triggers callback when order is submitted successfully', async () => { jest.spyOn(checkoutService, 'submitOrder') .mockResolvedValue(checkoutState); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); const form: ReactWrapper<PaymentFormProps> = container.find(PaymentForm); // tslint:disable-next-line:no-non-null-assertion form.prop('onSubmit')!({ ccCvv: '123', ccExpiry: '10 / 25', ccName: 'test', ccNumber: '4111 1111 1111 1111', paymentProviderRadio: selectedPaymentMethod.id, }); await new Promise(resolve => process.nextTick(resolve)); expect(defaultProps.onSubmit) .toHaveBeenCalled(); }); it('triggers error callback when order fails to submit', async () => { jest.spyOn(checkoutService, 'submitOrder') .mockRejectedValue(checkoutState); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); const form: ReactWrapper<PaymentFormProps> = container.find(PaymentForm); // tslint:disable-next-line:no-non-null-assertion form.prop('onSubmit')!({ ccCvv: '123', ccExpiry: '10 / 25', ccName: 'test', ccNumber: '4111 1111 1111 1111', paymentProviderRadio: selectedPaymentMethod.id, }); await new Promise(resolve => process.nextTick(resolve)); expect(defaultProps.onSubmitError) .toHaveBeenCalled(); }); it('submits order with selected instrument if payment is required', async () => { jest.spyOn(checkoutState.data, 'isPaymentDataRequired') .mockReturnValue(true); jest.spyOn(checkoutState.data, 'isPaymentDataSubmitted') .mockReturnValue(false); jest.spyOn(checkoutService, 'submitOrder') .mockResolvedValue(checkoutState); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); const form: ReactWrapper<PaymentFormProps> = container.find(PaymentForm); // tslint:disable-next-line:no-non-null-assertion form.prop('onSubmit')!({ ccCvv: '123', ccNumber: '4111 1111 1111 1111', instrumentId: '123', paymentProviderRadio: selectedPaymentMethod.id, }); expect(checkoutService.submitOrder) .toHaveBeenCalledWith({ payment: { methodId: selectedPaymentMethod.id, gatewayId: selectedPaymentMethod.gateway, paymentData: { ccCvv: '123', ccNumber: '4111111111111111', instrumentId: '123', }, }, }); }); it('reloads checkout object if unable to submit order due to spam protection error', async () => { jest.spyOn(checkoutService, 'loadCheckout') .mockResolvedValue(checkoutState); jest.spyOn(checkoutState.errors, 'getSubmitOrderError') .mockReturnValue({ type: 'request', body: { type: 'spam_protection_expired' }, } as unknown as RequestError); const container = mount(<PaymentTest { ...defaultProps } />); await new Promise(resolve => process.nextTick(resolve)); container.update(); container.find('ErrorModal Button').simulate('click'); expect(checkoutService.loadCheckout) .toHaveBeenCalled(); expect(container.find(PaymentForm).prop('didExceedSpamLimit')) .toBeTruthy(); }); });
the_stack
declare module "babylonjs-procedural-textures/brick/brickProceduralTexture.fragment" { /** @hidden */ export var brickProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/brick/brickProceduralTexture" { import { Color3 } from "babylonjs/Maths/math"; import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/brick/brickProceduralTexture.fragment"; export class BrickProceduralTexture extends ProceduralTexture { private _numberOfBricksHeight; private _numberOfBricksWidth; private _jointColor; private _brickColor; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; numberOfBricksHeight: number; numberOfBricksWidth: number; jointColor: Color3; brickColor: Color3; /** * Serializes this brick procedural texture * @returns a serialized brick procedural texture object */ serialize(): any; /** * Creates a Brick Procedural Texture from parsed brick procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing brick procedural texture information * @returns a parsed Brick Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): BrickProceduralTexture; } } declare module "babylonjs-procedural-textures/brick/index" { export * from "babylonjs-procedural-textures/brick/brickProceduralTexture"; } declare module "babylonjs-procedural-textures/cloud/cloudProceduralTexture.fragment" { /** @hidden */ export var cloudProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/cloud/cloudProceduralTexture" { import { Color4 } from "babylonjs/Maths/math"; import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/cloud/cloudProceduralTexture.fragment"; export class CloudProceduralTexture extends ProceduralTexture { private _skyColor; private _cloudColor; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; skyColor: Color4; cloudColor: Color4; /** * Serializes this cloud procedural texture * @returns a serialized cloud procedural texture object */ serialize(): any; /** * Creates a Cloud Procedural Texture from parsed cloud procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing cloud procedural texture information * @returns a parsed Cloud Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): CloudProceduralTexture; } } declare module "babylonjs-procedural-textures/cloud/index" { export * from "babylonjs-procedural-textures/cloud/cloudProceduralTexture"; } declare module "babylonjs-procedural-textures/fire/fireProceduralTexture.fragment" { /** @hidden */ export var fireProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/fire/fireProceduralTexture" { import { Vector2, Color3 } from "babylonjs/Maths/math"; import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/fire/fireProceduralTexture.fragment"; export class FireProceduralTexture extends ProceduralTexture { private _time; private _speed; private _autoGenerateTime; private _fireColors; private _alphaThreshold; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; render(useCameraPostProcess?: boolean): void; static readonly PurpleFireColors: Color3[]; static readonly GreenFireColors: Color3[]; static readonly RedFireColors: Color3[]; static readonly BlueFireColors: Color3[]; autoGenerateTime: boolean; fireColors: Color3[]; time: number; speed: Vector2; alphaThreshold: number; /** * Serializes this fire procedural texture * @returns a serialized fire procedural texture object */ serialize(): any; /** * Creates a Fire Procedural Texture from parsed fire procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing fire procedural texture information * @returns a parsed Fire Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): FireProceduralTexture; } } declare module "babylonjs-procedural-textures/fire/index" { export * from "babylonjs-procedural-textures/fire/fireProceduralTexture"; } declare module "babylonjs-procedural-textures/grass/grassProceduralTexture.fragment" { /** @hidden */ export var grassProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/grass/grassProceduralTexture" { import { Color3 } from "babylonjs/Maths/math"; import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/grass/grassProceduralTexture.fragment"; export class GrassProceduralTexture extends ProceduralTexture { private _grassColors; private _groundColor; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; grassColors: Color3[]; groundColor: Color3; /** * Serializes this grass procedural texture * @returns a serialized grass procedural texture object */ serialize(): any; /** * Creates a Grass Procedural Texture from parsed grass procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing grass procedural texture information * @returns a parsed Grass Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): GrassProceduralTexture; } } declare module "babylonjs-procedural-textures/grass/index" { export * from "babylonjs-procedural-textures/grass/grassProceduralTexture"; } declare module "babylonjs-procedural-textures/marble/marbleProceduralTexture.fragment" { /** @hidden */ export var marbleProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/marble/marbleProceduralTexture" { import { Color3 } from "babylonjs/Maths/math"; import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/marble/marbleProceduralTexture.fragment"; export class MarbleProceduralTexture extends ProceduralTexture { private _numberOfTilesHeight; private _numberOfTilesWidth; private _amplitude; private _jointColor; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; numberOfTilesHeight: number; amplitude: number; numberOfTilesWidth: number; jointColor: Color3; /** * Serializes this marble procedural texture * @returns a serialized marble procedural texture object */ serialize(): any; /** * Creates a Marble Procedural Texture from parsed marble procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing marble procedural texture information * @returns a parsed Marble Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): MarbleProceduralTexture; } } declare module "babylonjs-procedural-textures/marble/index" { export * from "babylonjs-procedural-textures/marble/marbleProceduralTexture"; } declare module "babylonjs-procedural-textures/normalMap/normalMapProceduralTexture.fragment" { /** @hidden */ export var normalMapProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/normalMap/normalMapProceduralTexture" { import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/normalMap/normalMapProceduralTexture.fragment"; export class NormalMapProceduralTexture extends ProceduralTexture { private _baseTexture; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; render(useCameraPostProcess?: boolean): void; resize(size: any, generateMipMaps: any): void; baseTexture: Texture; /** * Serializes this normal map procedural texture * @returns a serialized normal map procedural texture object */ serialize(): any; /** * Creates a Normal Map Procedural Texture from parsed normal map procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing normal map procedural texture information * @returns a parsed Normal Map Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): NormalMapProceduralTexture; } } declare module "babylonjs-procedural-textures/normalMap/index" { export * from "babylonjs-procedural-textures/normalMap/normalMapProceduralTexture"; } declare module "babylonjs-procedural-textures/perlinNoise/perlinNoiseProceduralTexture.fragment" { /** @hidden */ export var perlinNoiseProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/perlinNoise/perlinNoiseProceduralTexture" { import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/perlinNoise/perlinNoiseProceduralTexture.fragment"; export class PerlinNoiseProceduralTexture extends ProceduralTexture { time: number; timeScale: number; translationSpeed: number; private _currentTranslation; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; render(useCameraPostProcess?: boolean): void; resize(size: any, generateMipMaps: any): void; /** * Serializes this perlin noise procedural texture * @returns a serialized perlin noise procedural texture object */ serialize(): any; /** * Creates a Perlin Noise Procedural Texture from parsed perlin noise procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing perlin noise procedural texture information * @returns a parsed Perlin Noise Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): PerlinNoiseProceduralTexture; } } declare module "babylonjs-procedural-textures/perlinNoise/index" { export * from "babylonjs-procedural-textures/perlinNoise/perlinNoiseProceduralTexture"; } declare module "babylonjs-procedural-textures/road/roadProceduralTexture.fragment" { /** @hidden */ export var roadProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/road/roadProceduralTexture" { import { Color3 } from "babylonjs/Maths/math"; import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/road/roadProceduralTexture.fragment"; export class RoadProceduralTexture extends ProceduralTexture { private _roadColor; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; roadColor: Color3; /** * Serializes this road procedural texture * @returns a serialized road procedural texture object */ serialize(): any; /** * Creates a Road Procedural Texture from parsed road procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing road procedural texture information * @returns a parsed Road Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): RoadProceduralTexture; } } declare module "babylonjs-procedural-textures/road/index" { export * from "babylonjs-procedural-textures/road/roadProceduralTexture"; } declare module "babylonjs-procedural-textures/starfield/starfieldProceduralTexture.fragment" { /** @hidden */ export var starfieldProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/starfield/starfieldProceduralTexture" { import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/starfield/starfieldProceduralTexture.fragment"; export class StarfieldProceduralTexture extends ProceduralTexture { private _time; private _alpha; private _beta; private _zoom; private _formuparam; private _stepsize; private _tile; private _brightness; private _darkmatter; private _distfading; private _saturation; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; time: number; alpha: number; beta: number; formuparam: number; stepsize: number; zoom: number; tile: number; brightness: number; darkmatter: number; distfading: number; saturation: number; /** * Serializes this starfield procedural texture * @returns a serialized starfield procedural texture object */ serialize(): any; /** * Creates a Starfield Procedural Texture from parsed startfield procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing startfield procedural texture information * @returns a parsed Starfield Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): StarfieldProceduralTexture; } } declare module "babylonjs-procedural-textures/starfield/index" { export * from "babylonjs-procedural-textures/starfield/starfieldProceduralTexture"; } declare module "babylonjs-procedural-textures/wood/woodProceduralTexture.fragment" { /** @hidden */ export var woodProceduralTexturePixelShader: { name: string; shader: string; }; } declare module "babylonjs-procedural-textures/wood/woodProceduralTexture" { import { Color3 } from "babylonjs/Maths/math"; import { Texture } from "babylonjs/Materials/Textures/texture"; import { ProceduralTexture } from "babylonjs/Materials/Textures/Procedurals/proceduralTexture"; import { Scene } from "babylonjs/scene"; import "babylonjs-procedural-textures/wood/woodProceduralTexture.fragment"; export class WoodProceduralTexture extends ProceduralTexture { private _ampScale; private _woodColor; constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; ampScale: number; woodColor: Color3; /** * Serializes this wood procedural texture * @returns a serialized wood procedural texture object */ serialize(): any; /** * Creates a Wood Procedural Texture from parsed wood procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing wood procedural texture information * @returns a parsed Wood Procedural Texture */ static Parse(parsedTexture: any, scene: Scene, rootUrl: string): WoodProceduralTexture; } } declare module "babylonjs-procedural-textures/wood/index" { export * from "babylonjs-procedural-textures/wood/woodProceduralTexture"; } declare module "babylonjs-procedural-textures/index" { export * from "babylonjs-procedural-textures/brick/index"; export * from "babylonjs-procedural-textures/cloud/index"; export * from "babylonjs-procedural-textures/fire/index"; export * from "babylonjs-procedural-textures/grass/index"; export * from "babylonjs-procedural-textures/marble/index"; export * from "babylonjs-procedural-textures/normalMap/index"; export * from "babylonjs-procedural-textures/perlinNoise/index"; export * from "babylonjs-procedural-textures/road/index"; export * from "babylonjs-procedural-textures/starfield/index"; export * from "babylonjs-procedural-textures/wood/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-brick" { export * from "babylonjs-procedural-textures/brick/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-cloud" { export * from "babylonjs-procedural-textures/cloud/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-fire" { export * from "babylonjs-procedural-textures/fire/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-grass" { export * from "babylonjs-procedural-textures/grass/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-marble" { export * from "babylonjs-procedural-textures/marble/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-normalMap" { export * from "babylonjs-procedural-textures/normalMap/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-perlinNoise" { export * from "babylonjs-procedural-textures/perlinNoise/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-road" { export * from "babylonjs-procedural-textures/road/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-starfield" { export * from "babylonjs-procedural-textures/starfield/index"; } declare module "babylonjs-procedural-textures/legacy/legacy-wood" { export * from "babylonjs-procedural-textures/wood/index"; } declare module "babylonjs-procedural-textures/legacy/legacy" { export * from "babylonjs-procedural-textures/index"; } declare module "babylonjs-procedural-textures" { export * from "babylonjs-procedural-textures/legacy/legacy"; } declare module BABYLON { /** @hidden */ export var brickProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class BrickProceduralTexture extends BABYLON.ProceduralTexture { private _numberOfBricksHeight; private _numberOfBricksWidth; private _jointColor; private _brickColor; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; numberOfBricksHeight: number; numberOfBricksWidth: number; jointColor: BABYLON.Color3; brickColor: BABYLON.Color3; /** * Serializes this brick procedural texture * @returns a serialized brick procedural texture object */ serialize(): any; /** * Creates a Brick Procedural BABYLON.Texture from parsed brick procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing brick procedural texture information * @returns a parsed Brick Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): BrickProceduralTexture; } } declare module BABYLON { /** @hidden */ export var cloudProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class CloudProceduralTexture extends BABYLON.ProceduralTexture { private _skyColor; private _cloudColor; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; skyColor: BABYLON.Color4; cloudColor: BABYLON.Color4; /** * Serializes this cloud procedural texture * @returns a serialized cloud procedural texture object */ serialize(): any; /** * Creates a Cloud Procedural BABYLON.Texture from parsed cloud procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing cloud procedural texture information * @returns a parsed Cloud Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): CloudProceduralTexture; } } declare module BABYLON { /** @hidden */ export var fireProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class FireProceduralTexture extends BABYLON.ProceduralTexture { private _time; private _speed; private _autoGenerateTime; private _fireColors; private _alphaThreshold; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; render(useCameraPostProcess?: boolean): void; static readonly PurpleFireColors: BABYLON.Color3[]; static readonly GreenFireColors: BABYLON.Color3[]; static readonly RedFireColors: BABYLON.Color3[]; static readonly BlueFireColors: BABYLON.Color3[]; autoGenerateTime: boolean; fireColors: BABYLON.Color3[]; time: number; speed: BABYLON.Vector2; alphaThreshold: number; /** * Serializes this fire procedural texture * @returns a serialized fire procedural texture object */ serialize(): any; /** * Creates a Fire Procedural BABYLON.Texture from parsed fire procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing fire procedural texture information * @returns a parsed Fire Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): FireProceduralTexture; } } declare module BABYLON { /** @hidden */ export var grassProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class GrassProceduralTexture extends BABYLON.ProceduralTexture { private _grassColors; private _groundColor; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; grassColors: BABYLON.Color3[]; groundColor: BABYLON.Color3; /** * Serializes this grass procedural texture * @returns a serialized grass procedural texture object */ serialize(): any; /** * Creates a Grass Procedural BABYLON.Texture from parsed grass procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing grass procedural texture information * @returns a parsed Grass Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): GrassProceduralTexture; } } declare module BABYLON { /** @hidden */ export var marbleProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class MarbleProceduralTexture extends BABYLON.ProceduralTexture { private _numberOfTilesHeight; private _numberOfTilesWidth; private _amplitude; private _jointColor; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; numberOfTilesHeight: number; amplitude: number; numberOfTilesWidth: number; jointColor: BABYLON.Color3; /** * Serializes this marble procedural texture * @returns a serialized marble procedural texture object */ serialize(): any; /** * Creates a Marble Procedural BABYLON.Texture from parsed marble procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing marble procedural texture information * @returns a parsed Marble Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): MarbleProceduralTexture; } } declare module BABYLON { /** @hidden */ export var normalMapProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class NormalMapProceduralTexture extends BABYLON.ProceduralTexture { private _baseTexture; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; render(useCameraPostProcess?: boolean): void; resize(size: any, generateMipMaps: any): void; baseTexture: BABYLON.Texture; /** * Serializes this normal map procedural texture * @returns a serialized normal map procedural texture object */ serialize(): any; /** * Creates a Normal Map Procedural BABYLON.Texture from parsed normal map procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing normal map procedural texture information * @returns a parsed Normal Map Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): NormalMapProceduralTexture; } } declare module BABYLON { /** @hidden */ export var perlinNoiseProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class PerlinNoiseProceduralTexture extends BABYLON.ProceduralTexture { time: number; timeScale: number; translationSpeed: number; private _currentTranslation; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; render(useCameraPostProcess?: boolean): void; resize(size: any, generateMipMaps: any): void; /** * Serializes this perlin noise procedural texture * @returns a serialized perlin noise procedural texture object */ serialize(): any; /** * Creates a Perlin Noise Procedural BABYLON.Texture from parsed perlin noise procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing perlin noise procedural texture information * @returns a parsed Perlin Noise Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): PerlinNoiseProceduralTexture; } } declare module BABYLON { /** @hidden */ export var roadProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class RoadProceduralTexture extends BABYLON.ProceduralTexture { private _roadColor; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; roadColor: BABYLON.Color3; /** * Serializes this road procedural texture * @returns a serialized road procedural texture object */ serialize(): any; /** * Creates a Road Procedural BABYLON.Texture from parsed road procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing road procedural texture information * @returns a parsed Road Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): RoadProceduralTexture; } } declare module BABYLON { /** @hidden */ export var starfieldProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class StarfieldProceduralTexture extends BABYLON.ProceduralTexture { private _time; private _alpha; private _beta; private _zoom; private _formuparam; private _stepsize; private _tile; private _brightness; private _darkmatter; private _distfading; private _saturation; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; time: number; alpha: number; beta: number; formuparam: number; stepsize: number; zoom: number; tile: number; brightness: number; darkmatter: number; distfading: number; saturation: number; /** * Serializes this starfield procedural texture * @returns a serialized starfield procedural texture object */ serialize(): any; /** * Creates a Starfield Procedural BABYLON.Texture from parsed startfield procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing startfield procedural texture information * @returns a parsed Starfield Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): StarfieldProceduralTexture; } } declare module BABYLON { /** @hidden */ export var woodProceduralTexturePixelShader: { name: string; shader: string; }; } declare module BABYLON { export class WoodProceduralTexture extends BABYLON.ProceduralTexture { private _ampScale; private _woodColor; constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean); updateShaderUniforms(): void; ampScale: number; woodColor: BABYLON.Color3; /** * Serializes this wood procedural texture * @returns a serialized wood procedural texture object */ serialize(): any; /** * Creates a Wood Procedural BABYLON.Texture from parsed wood procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing wood procedural texture information * @returns a parsed Wood Procedural BABYLON.Texture */ static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): WoodProceduralTexture; } }
the_stack
* @module ContentView */ import * as React from "react"; import classnames from "classnames"; import { Pane } from "./Pane"; import { Resizer } from "./Resizer"; /** * Props for [[SplitPane]] component * @public */ export interface SplitPaneProps { /** Pass false to disable resizing */ allowResize?: boolean; /** The array of two react nodes, one for each pane. */ children: React.ReactNode[]; /** Determines which pane maintains its size when browser window is resized.*/ primary?: "first" | "second"; minSize?: string | number; /** You can limit the maximal size of the 'fixed' pane using the maxSize parameter with a positive value * (measured in pixels but state just a number). If you wrap the SplitPane into a container component * (yes you can, just remember the container has to have the relative or absolute positioning), then you'll need to limit * the movement of the splitter (resizer) at the end of the SplitPane (otherwise it can be dragged outside the SplitPane * and you don't catch it never more). For this purpose use the maxSize parameter with value 0. When dragged the splitter/resizer * will stop at the border of the SplitPane component and think this you'll be able to pick it again and drag it back then. * And more: if you set the maxSize to negative value (e.g. -200), then the splitter stops 200px before the border * (in other words it sets the minimal size of the 'resizable' pane in this case). This can be useful also in the * full-screen case of use. */ maxSize?: string | number; /** Default initial size of primary pane */ defaultSize?: string | number; /** Size of primary pane */ size?: string | number; /** You can use the step prop to only allow resizing in fixed increments. */ step?: number; split?: "vertical" | "horizontal"; /** This callback is invoked when a drag start. */ onDragStarted?: () => void; /** This callback is invoked when a drag ends. */ onDragFinished?: (newSize: number) => void; /** Callback is invoked with the current drag during a drag event.*/ onChange?: (newSize: number) => void; /** Callback is invoked if user clicks on Resizer. */ onResizerClick?: (event: MouseEvent) => void; /** Callback is invoked if user double clicks on Resizer. */ onResizerDoubleClick?: (event: MouseEvent) => void; /** Styling to be applied to the main container */ style?: React.CSSProperties; /** Styling to be applied to both panes */ paneStyle?: React.CSSProperties; /** Styling to be applied to the first pane, with precedence over paneStyle */ pane1Style?: React.CSSProperties; /** Styling to be applied to the second pane, with precedence over paneStyle */ pane2Style?: React.CSSProperties; /** Styling to be applied to the resizer bar */ resizerStyle?: React.CSSProperties; /** Class name to be added to the SplitPane div */ className?: string; /** Class name to be added to each Pane's div */ paneClassName?: string; /** Class name to be added to Pane1's div */ pane1ClassName?: string; /** Class name to be added to Pane2's div */ pane2ClassName?: string; } function unFocus(ownerDoc: Document | undefined) { // istanbul ignore next if (!ownerDoc) return; const docSelection = ownerDoc.getSelection(); // istanbul ignore else if (docSelection) { docSelection.empty(); } else { // istanbul ignore next try { const winSelection = ownerDoc.defaultView?.getSelection(); winSelection?.removeAllRanges(); } catch (_e) { } } } function getDefaultSize(defaultSize?: number | string, minSize?: string | number, maxSize?: string | number, draggedSize?: number) { // istanbul ignore next if (typeof draggedSize === "number") { const min = typeof minSize === "number" ? minSize : 0; const max = typeof maxSize === "number" && maxSize >= 0 ? maxSize : Infinity; return Math.max(min, Math.min(max, draggedSize)); } if (defaultSize !== undefined) { return defaultSize; } return minSize; } function removeNullChildren(children: React.ReactNode[]) { return React.Children.toArray(children).filter((c) => c); } /** * Local TypeScript implementation of `SplitPane` from `react-split-pane` package since that * package is not regularly maintained. * See https://github.com/tomkp/react-split-pane/blob/master/LICENSE. * @public */ export function SplitPane(props: SplitPaneProps) { const { style, size, defaultSize, maxSize, children, paneStyle, pane1Style, pane2Style, className, paneClassName, pane1ClassName, pane2ClassName, onDragStarted, onDragFinished, step, onChange, onResizerClick, onResizerDoubleClick, } = props; // honor same defaults as react-split-pane const allowResize = React.useMemo(() => undefined !== props.allowResize ? props.allowResize : true, [props.allowResize]); const minSize = React.useMemo(() => undefined !== props.minSize ? props.minSize : 50, [props.minSize]); const primary = React.useMemo(() => undefined !== props.primary ? props.primary : "first", [props.primary]); const split = React.useMemo(() => undefined !== props.split ? props.split : "vertical", [props.split]); const initialSize = size !== undefined ? size : getDefaultSize(defaultSize, minSize, maxSize); const [position, setPosition] = React.useState(0); const [draggedSize, setDraggedSize] = React.useState<number | undefined>(); const [active, setActive] = React.useState(false); const [pane1Size, setPane1Size] = React.useState(() => primary === "first" ? initialSize : undefined); const [pane2Size, setPane2Size] = React.useState(() => primary === "second" ? initialSize : undefined); const splitPane = React.useRef<HTMLDivElement>(null); const pane1 = React.useRef<HTMLDivElement>(null); const pane2 = React.useRef<HTMLDivElement>(null); const notNullChildren = React.useMemo(() => removeNullChildren(children), [children]); React.useEffect(() => { primary === "first" ? setPane1Size(initialSize) : setPane2Size(initialSize); primary === "first" ? setPane2Size(undefined) : setPane1Size(undefined); }, [initialSize, primary]); const splitPaneStyle = React.useMemo(() => { const directionSpecificParts = (split === "vertical") ? { flexDirection: "row", left: 0, right: 0, } : { bottom: 0, flexDirection: "column", minHeight: "100%", top: 0, width: "100%", }; return { display: "flex", flex: 1, height: "100%", position: "absolute", outline: "none", overflow: "hidden", MozUserSelect: "text", WebkitUserSelect: "text", msUserSelect: "text", userSelect: "text", ...style, ...directionSpecificParts, } as React.CSSProperties; }, [split, style]); const pane1DivStyle = { ...paneStyle, ...pane1Style }; const pane2DivStyle = { ...paneStyle, ...pane2Style }; const resizerStyle = React.useMemo(() => props.resizerStyle ?? {}, [props.resizerStyle]); const resizerClasses = React.useMemo(() => classnames("Resizer", !allowResize && "disabled"), [allowResize]); const splitPaneClasses = React.useMemo(() => classnames("SplitPane", className, split, !allowResize && "disabled"), [className, split, allowResize]); const pane1Classes = React.useMemo(() => classnames("Pane1", paneClassName, pane1ClassName), [paneClassName, pane1ClassName]); const pane2Classes = React.useMemo(() => classnames("Pane2", paneClassName, pane2ClassName), [paneClassName, pane2ClassName]); const initializeDrag = React.useCallback((x: number, y: number) => { // istanbul ignore next unFocus(splitPane.current?.ownerDocument); const newPosition = split === "vertical" ? x : y; onDragStarted && onDragStarted(); setActive(true); setPosition(newPosition); }, [onDragStarted, split]); const onTouchStart = React.useCallback((event: TouchEvent) => { // istanbul ignore else if (allowResize) { initializeDrag(event.touches[0].clientX, event.touches[0].clientY); } }, [allowResize, initializeDrag]); const processMove = React.useCallback((x: number, y: number) => { // istanbul ignore next unFocus(splitPane.current?.ownerDocument); const isPrimaryFirst = primary === "first"; const ref = isPrimaryFirst ? pane1.current : pane2.current; const ref2 = isPrimaryFirst ? pane2.current : pane1.current; const splitPaneDiv = splitPane.current; // istanbul ignore else if (ref && ref2 && splitPaneDiv) { const node = ref; const node2 = ref2; // istanbul ignore else if (node.getBoundingClientRect) { const width = node.getBoundingClientRect().width; const height = node.getBoundingClientRect().height; // istanbul ignore next const current = split === "vertical" ? x : y; // istanbul ignore next const oldSize = split === "vertical" ? width : height; let positionDelta = position - current; if (step) { // istanbul ignore next if (Math.abs(positionDelta) < step) { return; } // Integer division // eslint-disable-next-line no-bitwise positionDelta = ~~(positionDelta / step) * step; } let sizeDelta = isPrimaryFirst ? positionDelta : -positionDelta; // istanbul ignore next const pane1Order = parseInt(node.ownerDocument?.defaultView?.getComputedStyle(node).order ?? "0", 10); // istanbul ignore next const pane2Order = parseInt(node2.ownerDocument?.defaultView?.getComputedStyle(node2).order ?? "0", 10); // istanbul ignore next if (pane1Order > pane2Order) { sizeDelta = -sizeDelta; } let newMaxSize = maxSize; // istanbul ignore next if (typeof maxSize === "number" && maxSize !== undefined && maxSize <= 0) { if (split === "vertical") { newMaxSize = splitPaneDiv.getBoundingClientRect().width + maxSize; } else { newMaxSize = splitPaneDiv.getBoundingClientRect().height + maxSize; } } let newSize = oldSize - sizeDelta; const newPosition = position - positionDelta; // istanbul ignore next if (typeof minSize === "number" && newSize < minSize) { newSize = minSize; } else if (typeof newMaxSize === "number" && newMaxSize !== undefined && newSize > newMaxSize) { newSize = newMaxSize; } else { setPosition(newPosition); } onChange && onChange(newSize); setDraggedSize(newSize); isPrimaryFirst ? setPane1Size(newSize) : setPane2Size(newSize); } } }, [maxSize, minSize, onChange, position, primary, split, step]); const onTouchMove = React.useCallback((event: TouchEvent) => { // istanbul ignore next if (!allowResize || !active) return; processMove(event.touches[0].clientX, event.touches[0].clientY); }, [active, allowResize, processMove]); const onMouseMove = React.useCallback((event: MouseEvent) => { if (!allowResize || !active) return; processMove(event.clientX, event.clientY); }, [active, allowResize, processMove]); const onMouseDown = React.useCallback((event: MouseEvent) => { // istanbul ignore else if (allowResize) { event.preventDefault(); initializeDrag(event.clientX, event.clientY); } }, [allowResize, initializeDrag]); const processResizeFinished = React.useCallback(() => { // istanbul ignore else if (undefined !== draggedSize && allowResize && active) { onDragFinished && onDragFinished(draggedSize); } setActive(false); }, [draggedSize, allowResize, active, onDragFinished]); const onMouseUp = React.useCallback((event: MouseEvent) => { event.preventDefault(); processResizeFinished(); }, [processResizeFinished]); React.useEffect(() => { // istanbul ignore next const ownerDoc = splitPane.current?.ownerDocument; // istanbul ignore next if (!ownerDoc) return; ownerDoc.addEventListener("mouseup", onMouseUp); ownerDoc.addEventListener("mousemove", onMouseMove); ownerDoc.addEventListener("touchmove", onTouchMove); return () => { ownerDoc.removeEventListener("mouseup", onMouseUp); ownerDoc.removeEventListener("mousemove", onMouseMove); ownerDoc.removeEventListener("touchmove", onTouchMove); }; }, [onMouseMove, onMouseUp, onTouchMove]); return ( <div className={splitPaneClasses} ref={splitPane} style={splitPaneStyle} > <Pane className={pane1Classes} key="pane1" eleRef={pane1} size={pane1Size} split={split} style={pane1DivStyle} > {notNullChildren[0]} </Pane> <Resizer className={resizerClasses} onClick={onResizerClick} onDoubleClick={onResizerDoubleClick} onMouseDown={onMouseDown} onTouchStart={onTouchStart} onTouchEnd={processResizeFinished} key="resizer" split={split} style={resizerStyle} /> <Pane className={pane2Classes} key="pane2" eleRef={pane2} size={pane2Size} split={split} style={pane2DivStyle} > {notNullChildren[1]} </Pane> </div> ); }
the_stack
import { BlockchainLifecycle, web3Factory } from '@0x/dev-utils'; import { RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders'; import { providerUtils } from '@0x/utils'; import { TxData, Web3Wrapper } from '@0x/web3-wrapper'; import * as _ from 'lodash'; import * as mocha from 'mocha'; import * as process from 'process'; import { provider, providerConfigs, txDefaults, web3Wrapper } from './web3_wrapper'; // tslint:disable: no-namespace only-arrow-functions no-unbound-method max-classes-per-file export type ISuite = mocha.ISuite; export type ISuiteCallbackContext = mocha.ISuiteCallbackContext; export type SuiteCallback = (this: ISuiteCallbackContext) => void; export type ContextDefinitionCallback<T> = (description: string, callback: SuiteCallback) => T; export type BlockchainSuiteCallback = (this: ISuiteCallbackContext, env: BlockchainTestsEnvironment) => void; export type BlockchainContextDefinitionCallback<T> = (description: string, callback: BlockchainSuiteCallback) => T; export interface ContextDefinition extends mocha.IContextDefinition { optional: ContextDefinitionCallback<ISuite | void>; } /** * `blockchainTests()` config options. */ export interface BlockchainContextConfig { fork: Partial<{ // Accounts to unlock on ganache. unlockedAccounts: string[]; }>; } let TEST_ENV_CONFIG: Partial<BlockchainContextConfig> = {}; /** * Interface for `blockchainTests()`. */ export interface BlockchainContextDefinition { (description: string, callback: BlockchainSuiteCallback): ISuite; configure: (config?: Partial<BlockchainContextConfig>) => void; only: BlockchainContextDefinitionCallback<ISuite>; skip: BlockchainContextDefinitionCallback<void>; optional: BlockchainContextDefinitionCallback<ISuite | void>; resets: BlockchainContextDefinitionCallback<ISuite | void> & { only: BlockchainContextDefinitionCallback<ISuite>; skip: BlockchainContextDefinitionCallback<void>; optional: BlockchainContextDefinitionCallback<ISuite | void>; }; fork: BlockchainContextDefinitionCallback<ISuite | void> & { only: BlockchainContextDefinitionCallback<ISuite>; skip: BlockchainContextDefinitionCallback<void>; optional: BlockchainContextDefinitionCallback<ISuite | void>; resets: BlockchainContextDefinitionCallback<ISuite | void>; }; live: BlockchainContextDefinitionCallback<ISuite | void> & { only: BlockchainContextDefinitionCallback<ISuite>; skip: BlockchainContextDefinitionCallback<void>; optional: BlockchainContextDefinitionCallback<ISuite | void>; }; } /** * Describes the environment object passed into the `blockchainTests()` callback. */ export interface BlockchainTestsEnvironment { blockchainLifecycle: BlockchainLifecycle; provider: Web3ProviderEngine; txDefaults: Partial<TxData>; web3Wrapper: Web3Wrapper; getChainIdAsync(): Promise<number>; getAccountAddressesAsync(): Promise<string[]>; } class BlockchainTestsEnvironmentBase { public blockchainLifecycle!: BlockchainLifecycle; public provider!: Web3ProviderEngine; public txDefaults!: Partial<TxData>; public web3Wrapper!: Web3Wrapper; public async getChainIdAsync(): Promise<number> { return providerUtils.getChainIdAsync(this.provider); } public async getAccountAddressesAsync(): Promise<string[]> { return this.web3Wrapper.getAvailableAddressesAsync(); } } interface BlockchainEnvironmentFactory { create(): BlockchainTestsEnvironment; } /** * `BlockchainTestsEnvironment` that uses the default ganache provider. */ export class StandardBlockchainTestsEnvironmentSingleton extends BlockchainTestsEnvironmentBase { private static _instance: StandardBlockchainTestsEnvironmentSingleton | undefined; // Create or retrieve the singleton instance of this class. public static create(): StandardBlockchainTestsEnvironmentSingleton { if (StandardBlockchainTestsEnvironmentSingleton._instance === undefined) { StandardBlockchainTestsEnvironmentSingleton._instance = new StandardBlockchainTestsEnvironmentSingleton(); } return StandardBlockchainTestsEnvironmentSingleton._instance; } // Reset the singleton. public static reset(): void { StandardBlockchainTestsEnvironmentSingleton._instance = undefined; } // Get the singleton instance of this class. public static getInstance(): StandardBlockchainTestsEnvironmentSingleton | undefined { return StandardBlockchainTestsEnvironmentSingleton._instance; } protected constructor() { super(); this.blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); this.provider = provider; this.txDefaults = txDefaults; this.web3Wrapper = web3Wrapper; } } /** * `BlockchainTestsEnvironment` that uses a forked ganache provider. */ export class ForkedBlockchainTestsEnvironmentSingleton extends BlockchainTestsEnvironmentBase { private static _instance: ForkedBlockchainTestsEnvironmentSingleton | undefined; // Create or retrieve the singleton instance of this class. public static create(): ForkedBlockchainTestsEnvironmentSingleton { if (ForkedBlockchainTestsEnvironmentSingleton._instance === undefined) { ForkedBlockchainTestsEnvironmentSingleton._instance = new ForkedBlockchainTestsEnvironmentSingleton(); } return ForkedBlockchainTestsEnvironmentSingleton._instance; } // Reset the singleton. public static reset(): void { ForkedBlockchainTestsEnvironmentSingleton._instance = undefined; } protected static _createWeb3Provider(forkHost: string): Web3ProviderEngine { const forkConfig = TEST_ENV_CONFIG.fork || {}; const unlockedAccounts = forkConfig.unlockedAccounts; return web3Factory.getRpcProvider({ ...providerConfigs, fork: forkHost, blockTime: 0, ...(unlockedAccounts ? { unlocked_accounts: unlockedAccounts } : {}), }); } // Get the singleton instance of this class. public static getInstance(): ForkedBlockchainTestsEnvironmentSingleton | undefined { return ForkedBlockchainTestsEnvironmentSingleton._instance; } protected constructor() { super(); this.txDefaults = txDefaults; this.provider = process.env.FORK_RPC_URL ? ForkedBlockchainTestsEnvironmentSingleton._createWeb3Provider(process.env.FORK_RPC_URL) : // Create a dummy provider if no RPC backend supplied. createDummyProvider(); this.web3Wrapper = new Web3Wrapper(this.provider); this.blockchainLifecycle = new BlockchainLifecycle(this.web3Wrapper); } } /** * `BlockchainTestsEnvironment` that uses a live web3 provider. */ export class LiveBlockchainTestsEnvironmentSingleton extends BlockchainTestsEnvironmentBase { private static _instance: LiveBlockchainTestsEnvironmentSingleton | undefined; // Create or retrieve the singleton instance of this class. public static create(): LiveBlockchainTestsEnvironmentSingleton { if (LiveBlockchainTestsEnvironmentSingleton._instance === undefined) { LiveBlockchainTestsEnvironmentSingleton._instance = new LiveBlockchainTestsEnvironmentSingleton(); } return LiveBlockchainTestsEnvironmentSingleton._instance; } // Reset the singleton. public static reset(): void { LiveBlockchainTestsEnvironmentSingleton._instance = undefined; } protected static _createWeb3Provider(rpcHost: string): Web3ProviderEngine { const providerEngine = new Web3ProviderEngine(); providerEngine.addProvider(new RPCSubprovider(rpcHost)); providerUtils.startProviderEngine(providerEngine); return providerEngine; } // Get the singleton instance of this class. public static getInstance(): LiveBlockchainTestsEnvironmentSingleton | undefined { return LiveBlockchainTestsEnvironmentSingleton._instance; } protected constructor() { super(); this.txDefaults = txDefaults; this.provider = process.env.LIVE_RPC_URL ? LiveBlockchainTestsEnvironmentSingleton._createWeb3Provider(process.env.LIVE_RPC_URL) : // Create a dummy provider if no RPC backend supplied. createDummyProvider(); this.web3Wrapper = new Web3Wrapper(this.provider); const snapshotHandlerAsync = async (): Promise<void> => { throw new Error('Snapshots are not supported with a live provider.'); }; this.blockchainLifecycle = { startAsync: snapshotHandlerAsync, revertAsync: snapshotHandlerAsync, } as any; } } // The original `describe()` global provided by mocha. const mochaDescribe = (global as any).describe as mocha.IContextDefinition; /** * An augmented version of mocha's `describe()`. */ export const describe = _.assign(mochaDescribe, { optional(description: string, callback: SuiteCallback): ISuite | void { const describeCall = process.env.TEST_ALL ? mochaDescribe : mochaDescribe.skip; return describeCall(description, callback); }, }) as ContextDefinition; /** * Like mocha's `describe()`, but sets up a blockchain environment for you. */ export const blockchainTests: BlockchainContextDefinition = _.assign( function(description: string, callback: BlockchainSuiteCallback): ISuite { return defineBlockchainSuite(StandardBlockchainTestsEnvironmentSingleton, description, callback, describe); }, { configure(config?: Partial<BlockchainContextConfig>): void { // Update the global config and reset all environment singletons. TEST_ENV_CONFIG = { ...TEST_ENV_CONFIG, ...config, }; ForkedBlockchainTestsEnvironmentSingleton.reset(); StandardBlockchainTestsEnvironmentSingleton.reset(); LiveBlockchainTestsEnvironmentSingleton.reset(); }, only(description: string, callback: BlockchainSuiteCallback): ISuite { return defineBlockchainSuite( StandardBlockchainTestsEnvironmentSingleton, description, callback, describe.only, ); }, skip(description: string, callback: BlockchainSuiteCallback): void { return defineBlockchainSuite( StandardBlockchainTestsEnvironmentSingleton, description, callback, describe.skip, ); }, optional(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineBlockchainSuite( StandardBlockchainTestsEnvironmentSingleton, description, callback, process.env.TEST_ALL ? describe : describe.skip, ); }, fork: _.assign( function(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineBlockchainSuite( ForkedBlockchainTestsEnvironmentSingleton, description, callback, process.env.FORK_RPC_URL ? describe : describe.skip, ); }, { only(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineBlockchainSuite( ForkedBlockchainTestsEnvironmentSingleton, description, callback, process.env.FORK_RPC_URL ? describe.only : describe.skip, ); }, skip(description: string, callback: BlockchainSuiteCallback): void { return defineBlockchainSuite( ForkedBlockchainTestsEnvironmentSingleton, description, callback, describe.skip, ); }, optional(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineBlockchainSuite( ForkedBlockchainTestsEnvironmentSingleton, description, callback, process.env.FORK_RPC_URL ? describe.optional : describe.skip, ); }, resets(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineResetsBlockchainSuite( ForkedBlockchainTestsEnvironmentSingleton, description, callback, process.env.FORK_RPC_URL ? describe : describe.skip, ); }, }, ), live: _.assign( function(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineBlockchainSuite( LiveBlockchainTestsEnvironmentSingleton, description, callback, process.env.LIVE_RPC_URL ? describe : describe.skip, ); }, { only(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineBlockchainSuite( LiveBlockchainTestsEnvironmentSingleton, description, callback, process.env.LIVE_RPC_URL ? describe.only : describe.skip, ); }, skip(description: string, callback: BlockchainSuiteCallback): void { return defineBlockchainSuite( LiveBlockchainTestsEnvironmentSingleton, description, callback, describe.skip, ); }, optional(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineBlockchainSuite( LiveBlockchainTestsEnvironmentSingleton, description, callback, process.env.LIVE_RPC_URL ? describe.optional : describe.skip, ); }, }, ), resets: _.assign( function(description: string, callback: BlockchainSuiteCallback): ISuite { return defineResetsBlockchainSuite( StandardBlockchainTestsEnvironmentSingleton, description, callback, describe, ); }, { only(description: string, callback: BlockchainSuiteCallback): ISuite { return defineResetsBlockchainSuite( StandardBlockchainTestsEnvironmentSingleton, description, callback, describe.only, ); }, skip(description: string, callback: BlockchainSuiteCallback): void { return defineResetsBlockchainSuite( StandardBlockchainTestsEnvironmentSingleton, description, callback, describe.skip, ); }, optional(description: string, callback: BlockchainSuiteCallback): ISuite | void { return defineResetsBlockchainSuite( StandardBlockchainTestsEnvironmentSingleton, description, callback, describe.optional, ); }, }, ), }, ) as BlockchainContextDefinition; function defineBlockchainSuite<T>( envFactory: BlockchainEnvironmentFactory, description: string, callback: BlockchainSuiteCallback, describeCall: ContextDefinitionCallback<T>, ): T { return describeCall(description, function(this: ISuiteCallbackContext): void { callback.call(this, envFactory.create()); }); } function defineResetsBlockchainSuite<T>( envFactory: BlockchainEnvironmentFactory, description: string, callback: BlockchainSuiteCallback, describeCall: ContextDefinitionCallback<T>, ): T { return describeCall(description, function(this: ISuiteCallbackContext): void { const env = envFactory.create(); beforeEach(async () => env.blockchainLifecycle.startAsync()); afterEach(async () => env.blockchainLifecycle.revertAsync()); callback.call(this, env); }); } function createDummyProvider(): Web3ProviderEngine { return { addProvider: _.noop, on: _.noop, send: _.noop, sendAsync: _.noop, start: _.noop, stop: _.noop, }; }
the_stack
import { assert } from 'chai' import { XrplNetwork } from 'xpring-common-js' import IssuedCurrencyClient from '../../src/XRP/issued-currency-client' import XRPTestUtils from './helpers/xrp-test-utils' import { TransactionResult, TransactionStatus, XrpError, XrpUtils, } from '../../src/XRP/shared' import IssuedCurrency from '../../src/XRP/shared/issued-currency' // A timeout for these tests. // eslint-disable-next-line @typescript-eslint/no-magic-numbers -- 1 minute in milliseconds const timeoutMs = 60 * 1000 // An IssuedCurrencyClient that makes requests. const rippledGrpcUrl = 'test.xrp.xpring.io:50051' const rippledWebSocketUrl = 'wss://wss.test.xrp.xpring.io' const issuedCurrencyClient = IssuedCurrencyClient.issuedCurrencyClientWithEndpoint( rippledGrpcUrl, rippledWebSocketUrl, console.log, XrplNetwork.Test, ) describe('Issued Currency Payment Integration Tests', function (): void { // Retry integration tests on failure. this.retries(3) const currencyNameFOO = 'FOO' const currencyNameBAR = 'BAR' const trustLineLimit = '10000' let issuerWalletFOO let issuerWalletBAR let customerWallet1 let customerWallet2 let issuerFOOClassicAddress let issuerBARClassicAddress before(async function () { this.timeout(timeoutMs * 2) const walletPromise1 = XRPTestUtils.randomWalletFromFaucet().then( (wallet) => { issuerWalletFOO = wallet }, ) const walletPromise2 = XRPTestUtils.randomWalletFromFaucet().then( (wallet) => { issuerWalletBAR = wallet }, ) const walletPromise3 = XRPTestUtils.randomWalletFromFaucet().then( (wallet) => { customerWallet1 = wallet }, ) const walletPromise4 = XRPTestUtils.randomWalletFromFaucet().then( (wallet) => { customerWallet2 = wallet }, ) await Promise.all([ walletPromise1, walletPromise2, walletPromise3, walletPromise4, ]) await issuedCurrencyClient.enableRippling(issuerWalletFOO) await issuedCurrencyClient.enableRippling(issuerWalletBAR) issuerFOOClassicAddress = XrpUtils.decodeXAddress( issuerWalletFOO.getAddress()!, )!.address issuerBARClassicAddress = XrpUtils.decodeXAddress( issuerWalletBAR.getAddress()!, )!.address // both customers trust issuer of FOO await issuedCurrencyClient.createTrustLine( issuerWalletFOO.getAddress(), currencyNameFOO, trustLineLimit, customerWallet1, ) await issuedCurrencyClient.createTrustLine( issuerWalletFOO.getAddress(), currencyNameFOO, trustLineLimit, customerWallet2, ) // only customer2 trusts issuer of BAR await issuedCurrencyClient.createTrustLine( issuerWalletBAR.getAddress(), currencyNameBAR, trustLineLimit, customerWallet2, ) }) after(function (done) { issuedCurrencyClient.webSocketNetworkClient.close() done() }) it('createIssuedCurrency, combined cases', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN two existing, funded testnet accounts serving as an issuing address and operational address, respectively const issuerWallet = await XRPTestUtils.randomWalletFromFaucet() const operationalWallet = await XRPTestUtils.randomWalletFromFaucet() // WHEN there does not yet exist a trust line between the accounts, and the issuer attempts to create some issued currency let transactionResult = await issuedCurrencyClient.createIssuedCurrency( issuerWallet, operationalWallet.getAddress(), 'USD', '200', ) // THEN the transaction fails with ClaimedCostOnly_PathDry. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.ClaimedCostOnly_PathDry, true, ), ) // next, GIVEN a trust line created from the operational address to the issuer address, but with a limit that is too low const trustLineLimit = '100' const trustLineCurrency = 'USD' await issuedCurrencyClient.createTrustLine( issuerWallet.getAddress(), trustLineCurrency, trustLineLimit, operationalWallet, ) // WHEN the issuer attempts to create an amount of issued currency above the trust line limit transactionResult = await issuedCurrencyClient.createIssuedCurrency( issuerWallet, operationalWallet.getAddress(), trustLineCurrency, '200', ) // THEN the transaction fails with ClaimedCostOnly_PathPartial assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.ClaimedCostOnly_PathPartial, true, ), ) // but, WHEN the issuer attempts to create an amount of issued currency at or below the trust line limit transactionResult = await issuedCurrencyClient.createIssuedCurrency( issuerWallet, operationalWallet.getAddress(), trustLineCurrency, '100', ) // THEN the transaction finally succeeds. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.Succeeded, true, ), ) }) it('sendIssuedCurrencyPayment - failure to send from non-issuing account to customer account without rippling enabled on issuer', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an operational address with some issued currency, and an issuing address that has not enabled rippling const issuerWalletNoRippling = await XRPTestUtils.randomWalletFromFaucet() const operationalWallet = await XRPTestUtils.randomWalletFromFaucet() // establish trust line between operational and issuing const trustLineLimit = '1000' const trustLineCurrency = 'BAZ' await issuedCurrencyClient.createTrustLine( issuerWalletNoRippling.getAddress(), trustLineCurrency, trustLineLimit, operationalWallet, ) // fund operational with issued currency await issuedCurrencyClient.createIssuedCurrency( issuerWalletNoRippling, operationalWallet.getAddress(), trustLineCurrency, '500', ) // Must create trust line from customer account to issuing account such that rippling *could* happen through issuing account // Even though it won't because the issuing account hasn't enabled rippling - just isolating what's being tested. await issuedCurrencyClient.createTrustLine( issuerWalletNoRippling.getAddress(), trustLineCurrency, trustLineLimit, customerWallet1, ) // WHEN an issued currency payment is made to another funded account const issuedCurrency: IssuedCurrency = { currency: trustLineCurrency, issuer: issuerWalletNoRippling.getAddress(), value: '100', } const transactionResult = await issuedCurrencyClient.sendIssuedCurrencyPayment( operationalWallet, customerWallet1.getAddress(), issuedCurrency, ) // THEN the payment fails with CalimedCostOnly_PathDry assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.ClaimedCostOnly_PathDry, true, ), ) }) it('sendIssuedCurrencyPayment - success sending issued currency from non-issuing account to another account', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN an operational address with some issued currency, and an issuing address that has enabled rippling but set no transfer fees, // and a customer account who also has a trust line to the issuer. // fund operational with issued currency await issuedCurrencyClient.createIssuedCurrency( issuerWalletFOO, customerWallet1.getAddress(), currencyNameFOO, '500', ) // WHEN an issued currency payment is made to another funded account const issuedCurrency: IssuedCurrency = { currency: currencyNameFOO, issuer: issuerWalletFOO.getAddress(), value: '100', } const transactionResult = await issuedCurrencyClient.sendIssuedCurrencyPayment( customerWallet1, customerWallet2.getAddress(), issuedCurrency, ) // THEN the transaction succeeds. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.Succeeded, true, ), ) }) it('sendIssuedCurrencyPayment - sending issued currency with applicable transfer fees, combined cases', async function (): Promise<void> { this.timeout(timeoutMs * 2) // GIVEN an operational address with some issued currency, and an issuing address that has enabled rippling and established a transfer fee const issuerWalletWithTransferFee = await XRPTestUtils.randomWalletFromFaucet() await issuedCurrencyClient.enableRippling(issuerWalletWithTransferFee) await issuedCurrencyClient.setTransferFee( 1005000000, issuerWalletWithTransferFee, ) // establish trust line from operational to issuing const trustLineLimit = '1000' await issuedCurrencyClient.createTrustLine( issuerWalletWithTransferFee.getAddress(), currencyNameFOO, trustLineLimit, customerWallet1, ) // fund operational with some FOO from this issuer await issuedCurrencyClient.createIssuedCurrency( issuerWalletWithTransferFee, customerWallet1.getAddress(), currencyNameFOO, '500', ) // Must create trust line from customer account to issuing account such that rippling can happen through issuing account await issuedCurrencyClient.createTrustLine( issuerWalletWithTransferFee.getAddress(), currencyNameFOO, trustLineLimit, customerWallet2, ) // WHEN an issued currency payment is made to another funded account, without the transferFee argument supplied const issuedCurrency: IssuedCurrency = { currency: currencyNameFOO, issuer: issuerWalletWithTransferFee.getAddress(), value: '100', } let transactionResult = await issuedCurrencyClient.sendIssuedCurrencyPayment( customerWallet1, customerWallet2.getAddress(), issuedCurrency, ) // THEN the transaction fails with ClaimedCostOnly_PathPartial. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.ClaimedCostOnly_PathPartial, true, ), ) // but, WHEN an issued currency payment is made to another funded account with the correct transferFee supplied transactionResult = await issuedCurrencyClient.sendIssuedCurrencyPayment( customerWallet1, customerWallet2.getAddress(), issuedCurrency, 0.5, ) // THEN the transaction succeeds. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.Succeeded, true, ), ) }) it('redeemIssuedCurrency', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN a customer account with some issued currency, and an issuing address // fund the customer wallet directly with some FOO await issuedCurrencyClient.createIssuedCurrency( issuerWalletFOO, customerWallet1.getAddress(), currencyNameFOO, '500', ) // WHEN an issued currency payment is made back to the issuer const issuedCurrency: IssuedCurrency = { currency: currencyNameFOO, issuer: issuerWalletFOO.getAddress(), value: '100', } const transactionResult = await issuedCurrencyClient.redeemIssuedCurrency( customerWallet1, issuedCurrency, ) // THEN the payment succeeds. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.Succeeded, true, ), ) }) it('sendCrossCurrencyPayment - success, XRP -> Issued Currency with default path', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN a customer account with some issued currency, an issuing address that has enabled rippling, and an offer to exchange // XRP for FOO // create an offer by Issuer of FOO to exchange XRP for FOO: const takerGetsAmount: IssuedCurrency = { currency: currencyNameFOO, issuer: issuerFOOClassicAddress, value: '100', } const takerPaysAmount = '100000000' // drops of XRP = 100 XRP, 1:1 exchange rate await issuedCurrencyClient.createOffer( issuerWalletFOO, takerGetsAmount, takerPaysAmount, ) // WHEN a cross currency payment is made that sends XRP and delivers FOO. const sourceAmount = '100000000' // spend up to 100 XRP const deliverAmount = { currency: currencyNameFOO, issuer: issuerFOOClassicAddress, value: '80', } const transactionResult = await issuedCurrencyClient.sendCrossCurrencyPayment( customerWallet2, customerWallet1.getAddress(), sourceAmount, deliverAmount, ) // THEN the cross currency payment succeeds. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.Succeeded, true, ), ) }) it('sendCrossCurrencyPayment - success, Issued Currency -> Issued Currency with no default path', async function (): Promise<void> { this.timeout(timeoutMs * 2) // GIVEN two different issued currencies by two different issuers, and order books for each currency to exchange with XRP, // a payer who wants to pay in FOO, and a payee who wants to receive BAR // create a trustline to FOO issuer and then an offer by third party to take FOO and provide XRP: const offererWallet = await XRPTestUtils.randomWalletFromFaucet() await issuedCurrencyClient.createTrustLine( issuerWalletFOO.getAddress(), currencyNameFOO, trustLineLimit, offererWallet, ) const takerGetsXRP = '100000000' // 100 XRP const takerPaysFOO: IssuedCurrency = { currency: currencyNameFOO, issuer: issuerFOOClassicAddress, value: '100', } await issuedCurrencyClient.createOffer( offererWallet, takerGetsXRP, takerPaysFOO, ) // create offer by issuer of BAR to accept XRP in exchange for BAR const takerGetsBAR: IssuedCurrency = { currency: currencyNameBAR, issuer: issuerBARClassicAddress, value: '100', } const takerPaysXRP = '100000000' // 100 XRP await issuedCurrencyClient.createOffer( issuerWalletBAR, takerGetsBAR, takerPaysXRP, ) // fund sending customer with some FOO await issuedCurrencyClient.createIssuedCurrency( issuerWalletFOO, customerWallet1.getAddress(), currencyNameFOO, '500', ) // WHEN a cross currency payment is made that sends FOO and delivers BAR. const sourceAmount: IssuedCurrency = { currency: currencyNameFOO, issuer: issuerFOOClassicAddress, value: '80', } const deliverAmount = { currency: currencyNameBAR, issuer: issuerBARClassicAddress, value: '80', } const transactionResult = await issuedCurrencyClient.sendCrossCurrencyPayment( customerWallet1, customerWallet2.getAddress(), sourceAmount, deliverAmount, ) // THEN the cross currency payment succeeds. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.Succeeded, true, ), ) }) it('sendCrossCurrencyPayment - combined cases: failure then success, Issued Currency -> XRP', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN a customer account trying to spend BAZ, an issuing address for BAZ that has enabled rippling, // a recipient looking to be paid in XRP, but no offers for exchange. const freshIssuerWallet = await XRPTestUtils.randomWalletFromFaucet() await issuedCurrencyClient.enableRippling(freshIssuerWallet) const freshIssuerClassicAddress = XrpUtils.decodeXAddress( freshIssuerWallet.getAddress(), )!.address // fund customer with some BAZ const currencyNameBAZ = 'BAZ' await issuedCurrencyClient.createTrustLine( freshIssuerWallet.getAddress(), currencyNameBAZ, trustLineLimit, customerWallet1, ) await issuedCurrencyClient.createIssuedCurrency( freshIssuerWallet, customerWallet1.getAddress(), currencyNameBAZ, '500', ) // WHEN a cross currency payment is made that tries to send BAZ and deliver XRP. let sourceAmount = { currency: currencyNameBAZ, issuer: freshIssuerClassicAddress, value: '80', } let deliverAmount = '100000000' // THEN the cross currency payment fails with an error indicating that no paths exist. try { await issuedCurrencyClient.sendCrossCurrencyPayment( customerWallet1, customerWallet2.getAddress(), sourceAmount, deliverAmount, ) } catch (error) { assert(error instanceof XrpError) assert( error.message == 'No paths exist to execute cross-currency payment.', ) } // BUT THEN GIVEN a customer account with some issued BAZ, an issuing address that has enabled rippling, a recipient interested // in being paid in XRP, and a third party offer to exchange the two await issuedCurrencyClient.createTrustLine( freshIssuerWallet.getAddress(), currencyNameBAZ, trustLineLimit, customerWallet2, ) // create offer by third party to take BAZ in exchange for XRP const takerGetsXRP = '100000000' // 100 XRP const takerPaysBAZ: IssuedCurrency = { currency: currencyNameBAZ, issuer: freshIssuerClassicAddress, value: '100', } await issuedCurrencyClient.createOffer( customerWallet2, takerGetsXRP, takerPaysBAZ, ) // WHEN a cross currency payment is made that sends BAZ and delivers XRP. sourceAmount = { currency: currencyNameBAZ, issuer: freshIssuerClassicAddress, value: '80', } deliverAmount = '80000000' // deliver 80 XRP const transactionResult = await issuedCurrencyClient.sendCrossCurrencyPayment( customerWallet1, customerWallet1.getAddress(), sourceAmount, deliverAmount, ) // THEN the cross currency payment succeeds. assert.deepEqual( transactionResult, TransactionResult.createFinalTransactionResult( transactionResult.hash, TransactionStatus.Succeeded, true, ), ) }) })
the_stack
import * as tf from '@tensorflow/tfjs'; // tslint:disable-next-line:max-line-length import {LayerVariable, ModelCompileConfig, Tensor, Variable} from '@tensorflow/tfjs'; export type VarList = Array<Tensor|Variable|LayerVariable>; export type SerializedVariable = { dtype: tf.DataType, shape: number[], data: ArrayBuffer }; export const dtypeToTypedArrayCtor = { 'float32': Float32Array, 'int32': Int32Array, 'bool': Uint8Array }; export async function serializeVar(variable: tf.Tensor): Promise<SerializedVariable> { const data = await variable.data(); // small TypedArrays are views into a larger buffer const copy = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); return {dtype: variable.dtype, shape: variable.shape.slice(), data: copy}; } export async function serializeVars(vars: VarList) { const varsP: Array<Promise<SerializedVariable>> = []; vars.forEach((value, key) => { // tslint:disable-next-line:no-any const lv = (value as any); if (lv.write != null) { varsP.push(serializeVar(lv.read())); } else { varsP.push(serializeVar(lv)); } }); return Promise.all(varsP); } export function stackSerialized(vars: SerializedVariable[][]) { const updateCount = vars.length; const weightCount = vars[0].length; const stackedVars = []; for (let wt = 0; wt < weightCount; wt++) { const singleVar = vars[0][wt]; const byteLength = singleVar.data.byteLength; const stackedVar = new Uint8Array(byteLength * updateCount); for (let up = 0; up < updateCount; up++) { const update = vars[up][wt].data; stackedVar.set(new Uint8Array(update), up * byteLength); } stackedVars.push({ dtype: singleVar.dtype, shape: [updateCount].concat(singleVar.shape), data: stackedVar.buffer.slice( stackedVar.byteOffset, stackedVar.byteOffset + stackedVar.byteLength) }); } return stackedVars; } export function deserializeVars(vars: SerializedVariable[]) { return vars.map(deserializeVar); } export function serializedToArray(serialized: SerializedVariable) { const {dtype, shape, data: dataBuffer} = serialized; let data; // Because socket.io will deserialise JS ArrayBuffers into Nodejs Buffers if (dataBuffer instanceof ArrayBuffer) { data = dataBuffer; // tslint:disable-next-line no-any } else if ((dataBuffer as any) instanceof Buffer) { // tslint:disable-next-line no-any const dataAsBuffer = dataBuffer as any as Buffer; data = dataAsBuffer.buffer.slice( dataAsBuffer.byteOffset, dataAsBuffer.byteOffset + dataAsBuffer.byteLength); } const numel = shape.reduce((x, y) => x * y, 1); const ctor = dtypeToTypedArrayCtor[dtype]; return new ctor(data, 0, numel); } export function deserializeVar(serialized: SerializedVariable): tf.Tensor { const array = serializedToArray(serialized); return tf.tensor(array, serialized.shape, serialized.dtype); } export type LossOrMetricFn = (yTrue: Tensor, yPred: Tensor) => Tensor; export type TfModelCallback = () => Promise<tf.Model>; export type AsyncTfModel = string|tf.Model|TfModelCallback; export type VersionCallback = (oldVersion: string, newVersion: string) => void; export type UploadCallback = (msg: UploadMsg) => void; export enum Events { Download = 'downloadVars', Upload = 'uploadVars', } export type ModelMsg = { version: string, vars: SerializedVariable[] }; export type UploadMsg = { model: ModelMsg, clientId: string, metrics?: number[] }; export type DownloadMsg = { model: ModelMsg, hyperparams: ClientHyperparams }; export type FederatedFitConfig = { learningRate?: number, epochs?: number, batchSize?: number }; export type FederatedCompileConfig = { loss?: string|LossOrMetricFn, metrics?: string[] }; export type ClientHyperparams = { batchSize?: number, // batch size (usually not relevant) learningRate?: number, // step size epochs?: number, // number of steps examplesPerUpdate?: number, // min examples before fitting weightNoiseStddev?: number // how much noise to add to weights }; export type ServerHyperparams = { aggregation?: string, minUpdatesPerVersion?: number }; export const DEFAULT_CLIENT_HYPERPARAMS: ClientHyperparams = { examplesPerUpdate: 5, learningRate: 0.001, batchSize: 32, epochs: 5, weightNoiseStddev: 0 }; export const DEFAULT_SERVER_HYPERPARAMS: ServerHyperparams = { aggregation: 'mean', minUpdatesPerVersion: 20 }; // tslint:disable-next-line:no-any function override(defaults: any, choices: any) { // tslint:disable-next-line:no-any const result: any = {}; for (const key in defaults) { result[key] = (choices || {})[key] || defaults[key]; } for (const key in (choices || {})) { if (!(key in defaults)) { throw new Error(`Unrecognized key "${key}"`); } } return result; } export function clientHyperparams(hps?: ClientHyperparams): ClientHyperparams { try { return override(DEFAULT_CLIENT_HYPERPARAMS, hps); } catch (err) { throw new Error(`Error setting clientHyperparams: ${err.message}`); } } export function serverHyperparams(hps?: ServerHyperparams): ServerHyperparams { try { return override(DEFAULT_SERVER_HYPERPARAMS, hps); } catch (err) { throw new Error(`Error setting serverHyperparams: ${err.message}`); } } export async function fetchModel(asyncModel: AsyncTfModel): Promise<tf.Model> { if (typeof asyncModel === 'string') { return await tf.loadModel(asyncModel); } else if (typeof asyncModel === 'function') { return await asyncModel(); } else { return asyncModel as tf.Model; } } export interface FederatedModel { /** * Trains the model to better predict the given targets. * * @param x `tf.Tensor` of training input data. * @param y `tf.Tensor` of training target data. * @param config optional fit configuration. * * @return A `Promise` resolved when training is done. */ fit(x: Tensor, y: Tensor, config?: FederatedFitConfig): Promise<void>; /** * Makes predictions on input data. * * @param x `tf.Tensor` of input data. * * @return model ouputs */ predict(x: Tensor): Tensor; /** * Evaluates performance on data. * * @param x `tf.Tensor` of input data. * @param y `tf.Tensor` of target data. * * @return An array of evaluation metrics. */ evaluate(x: Tensor, y: Tensor): number[]; /** * Gets the model's variables. * * @return A list of `tf.Variable`s or LayerVariables representing the model's * trainable weights. */ getVars(): Tensor[]; /** * Sets the model's variables to given values. * * @param vals An array of `tf.Tensor`s representing updated model weights */ setVars(vals: Tensor[]): void; /** * Shape of model inputs (not including the batch dimension) */ inputShape: number[]; /** * Shape of model outputs (not including the batch dimension) */ outputShape: number[]; } export class FederatedTfModel implements FederatedModel { model: tf.Model; compileConfig: ModelCompileConfig; private _initialModel: AsyncTfModel; constructor(initialModel?: AsyncTfModel, config?: FederatedCompileConfig) { this._initialModel = initialModel; this.compileConfig = { loss: config.loss || 'categoricalCrossentropy', metrics: config.metrics || ['accuracy'], optimizer: 'sgd' }; } async fetchInitial() { if (this._initialModel) { this.model = await fetchModel(this._initialModel); this.model.compile(this.compileConfig); } else { throw new Error('no initial model provided!'); } } async fit(x: Tensor, y: Tensor, config?: FederatedFitConfig) { if (config.learningRate) { (this.model.optimizer as tf.SGDOptimizer) .setLearningRate(config.learningRate); } await this.model.fit(x, y, { epochs: config.epochs || DEFAULT_CLIENT_HYPERPARAMS.epochs, batchSize: config.batchSize || DEFAULT_CLIENT_HYPERPARAMS.batchSize }); } predict(x: Tensor) { return this.model.predict(x) as Tensor; } evaluate(x: Tensor, y: Tensor) { return tf.tidy(() => { const results = this.model.evaluate(x, y); if (results instanceof Array) { return results.map(r => r.dataSync()[0]); } else { return [results.dataSync()[0]]; } }); } getVars(): tf.Tensor[] { return this.model.trainableWeights.map((v) => v.read()); } // TODO: throw friendly error if passed variable of wrong shape? setVars(vals: tf.Tensor[]) { for (let i = 0; i < vals.length; i++) { this.model.trainableWeights[i].write(vals[i]); } } get inputShape() { return this.model.inputLayers[0].batchInputShape.slice(1); } get outputShape() { return (this.model.outputShape as number[]).slice(1); } } export class FederatedDynamicModel implements FederatedModel { isFederatedClientModel = true; version: string; vars: tf.Variable[]; predict: (inputs: tf.Tensor) => tf.Tensor; loss: (labels: tf.Tensor, preds: tf.Tensor) => tf.Scalar; optimizer: tf.SGDOptimizer; inputShape: number[]; outputShape: number[]; constructor(args: { vars: tf.Variable[]; predict: (inputs: tf.Tensor) => tf.Tensor; loss: (labels: tf.Tensor, preds: tf.Tensor) => tf.Scalar; inputShape: number[]; outputShape: number[]; }) { this.vars = args.vars; this.predict = args.predict; this.loss = args.loss; this.optimizer = tf.train.sgd(DEFAULT_CLIENT_HYPERPARAMS.learningRate); this.inputShape = args.inputShape; this.outputShape = args.outputShape; } async setup() { return Promise.resolve(); } async fit(x: tf.Tensor, y: tf.Tensor, config?: FederatedFitConfig): Promise<void> { if (config.learningRate) { this.optimizer.setLearningRate(config.learningRate); } const epochs = (config && config.epochs) || 1; for (let i = 0; i < epochs; i++) { const ret = this.optimizer.minimize(() => this.loss(y, this.predict(x))); tf.dispose(ret); } } evaluate(x: tf.Tensor, y: tf.Tensor): number[] { return Array.prototype.slice.call(this.loss(y, this.predict(x)).dataSync()); } getVars() { return this.vars; } setVars(vals: tf.Tensor[]) { this.vars.forEach((v, i) => { v.assign(vals[i]); }); } }
the_stack
import * as coreClient from "@azure/core-client"; export const TelemetryItem: coreClient.CompositeMapper = { type: { name: "Composite", className: "TelemetryItem", modelProperties: { version: { defaultValue: 1, serializedName: "ver", type: { name: "Number" } }, name: { serializedName: "name", required: true, type: { name: "String" } }, time: { serializedName: "time", required: true, type: { name: "DateTime" } }, sampleRate: { defaultValue: 100, serializedName: "sampleRate", type: { name: "Number" } }, sequence: { constraints: { MaxLength: 64 }, serializedName: "seq", type: { name: "String" } }, instrumentationKey: { serializedName: "iKey", type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, data: { serializedName: "data", type: { name: "Composite", className: "MonitorBase" } } } } }; export const MonitorBase: coreClient.CompositeMapper = { type: { name: "Composite", className: "MonitorBase", modelProperties: { baseType: { serializedName: "baseType", type: { name: "String" } }, baseData: { serializedName: "baseData", type: { name: "Composite", className: "MonitorDomain" } } } } }; export const MonitorDomain: coreClient.CompositeMapper = { type: { name: "Composite", className: "MonitorDomain", additionalProperties: { type: { name: "Object" } }, modelProperties: { version: { defaultValue: 2, serializedName: "ver", required: true, type: { name: "Number" } } } } }; export const TrackResponse: coreClient.CompositeMapper = { type: { name: "Composite", className: "TrackResponse", modelProperties: { itemsReceived: { serializedName: "itemsReceived", type: { name: "Number" } }, itemsAccepted: { serializedName: "itemsAccepted", type: { name: "Number" } }, errors: { serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "TelemetryErrorDetails" } } } } } } }; export const TelemetryErrorDetails: coreClient.CompositeMapper = { type: { name: "Composite", className: "TelemetryErrorDetails", modelProperties: { index: { serializedName: "index", type: { name: "Number" } }, statusCode: { serializedName: "statusCode", type: { name: "Number" } }, message: { serializedName: "message", type: { name: "String" } } } } }; export const MetricDataPoint: coreClient.CompositeMapper = { type: { name: "Composite", className: "MetricDataPoint", modelProperties: { namespace: { constraints: { MaxLength: 256 }, serializedName: "ns", type: { name: "String" } }, name: { constraints: { MaxLength: 1024 }, serializedName: "name", required: true, type: { name: "String" } }, dataPointType: { serializedName: "kind", type: { name: "String" } }, value: { serializedName: "value", required: true, type: { name: "Number" } }, count: { serializedName: "count", nullable: true, type: { name: "Number" } }, min: { serializedName: "min", nullable: true, type: { name: "Number" } }, max: { serializedName: "max", nullable: true, type: { name: "Number" } }, stdDev: { serializedName: "stdDev", nullable: true, type: { name: "Number" } } } } }; export const TelemetryExceptionDetails: coreClient.CompositeMapper = { type: { name: "Composite", className: "TelemetryExceptionDetails", modelProperties: { id: { serializedName: "id", type: { name: "Number" } }, outerId: { serializedName: "outerId", type: { name: "Number" } }, typeName: { constraints: { MaxLength: 1024 }, serializedName: "typeName", type: { name: "String" } }, message: { constraints: { MaxLength: 32768 }, serializedName: "message", required: true, type: { name: "String" } }, hasFullStack: { defaultValue: true, serializedName: "hasFullStack", type: { name: "Boolean" } }, stack: { constraints: { MaxLength: 32768 }, serializedName: "stack", type: { name: "String" } }, parsedStack: { serializedName: "parsedStack", type: { name: "Sequence", element: { type: { name: "Composite", className: "StackFrame" } } } } } } }; export const StackFrame: coreClient.CompositeMapper = { type: { name: "Composite", className: "StackFrame", modelProperties: { level: { serializedName: "level", required: true, type: { name: "Number" } }, method: { constraints: { MaxLength: 1024 }, serializedName: "method", required: true, type: { name: "String" } }, assembly: { constraints: { MaxLength: 1024 }, serializedName: "assembly", type: { name: "String" } }, fileName: { constraints: { MaxLength: 1024 }, serializedName: "fileName", type: { name: "String" } }, line: { serializedName: "line", type: { name: "Number" } } } } }; export const AvailabilityData: coreClient.CompositeMapper = { type: { name: "Composite", className: "AvailabilityData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, id: { constraints: { MaxLength: 512 }, serializedName: "id", required: true, type: { name: "String" } }, name: { constraints: { MaxLength: 1024 }, serializedName: "name", required: true, type: { name: "String" } }, duration: { serializedName: "duration", required: true, type: { name: "String" } }, success: { serializedName: "success", required: true, type: { name: "Boolean" } }, runLocation: { constraints: { MaxLength: 1024 }, serializedName: "runLocation", type: { name: "String" } }, message: { constraints: { MaxLength: 8192 }, serializedName: "message", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } }, measurements: { serializedName: "measurements", type: { name: "Dictionary", value: { type: { name: "Number" } } } } } } }; export const TelemetryEventData: coreClient.CompositeMapper = { type: { name: "Composite", className: "TelemetryEventData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, name: { constraints: { MaxLength: 512 }, serializedName: "name", required: true, type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } }, measurements: { serializedName: "measurements", type: { name: "Dictionary", value: { type: { name: "Number" } } } } } } }; export const TelemetryExceptionData: coreClient.CompositeMapper = { type: { name: "Composite", className: "TelemetryExceptionData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, exceptions: { serializedName: "exceptions", required: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "TelemetryExceptionDetails" } } } }, severityLevel: { serializedName: "severityLevel", nullable: true, type: { name: "String" } }, problemId: { constraints: { MaxLength: 1024 }, serializedName: "problemId", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } }, measurements: { serializedName: "measurements", type: { name: "Dictionary", value: { type: { name: "Number" } } } } } } }; export const MessageData: coreClient.CompositeMapper = { type: { name: "Composite", className: "MessageData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, message: { constraints: { MaxLength: 32768 }, serializedName: "message", required: true, type: { name: "String" } }, severityLevel: { serializedName: "severityLevel", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } }, measurements: { serializedName: "measurements", type: { name: "Dictionary", value: { type: { name: "Number" } } } } } } }; export const MetricsData: coreClient.CompositeMapper = { type: { name: "Composite", className: "MetricsData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, metrics: { serializedName: "metrics", required: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "MetricDataPoint" } } } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } } } } }; export const PageViewData: coreClient.CompositeMapper = { type: { name: "Composite", className: "PageViewData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, id: { constraints: { MaxLength: 512 }, serializedName: "id", required: true, type: { name: "String" } }, name: { constraints: { MaxLength: 1024 }, serializedName: "name", required: true, type: { name: "String" } }, url: { constraints: { MaxLength: 2048 }, serializedName: "url", type: { name: "String" } }, duration: { serializedName: "duration", type: { name: "String" } }, referredUri: { constraints: { MaxLength: 2048 }, serializedName: "referredUri", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } }, measurements: { serializedName: "measurements", type: { name: "Dictionary", value: { type: { name: "Number" } } } } } } }; export const PageViewPerfData: coreClient.CompositeMapper = { type: { name: "Composite", className: "PageViewPerfData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, id: { constraints: { MaxLength: 512 }, serializedName: "id", required: true, type: { name: "String" } }, name: { constraints: { MaxLength: 1024 }, serializedName: "name", required: true, type: { name: "String" } }, url: { constraints: { MaxLength: 2048 }, serializedName: "url", type: { name: "String" } }, duration: { serializedName: "duration", type: { name: "String" } }, perfTotal: { serializedName: "perfTotal", type: { name: "String" } }, networkConnect: { serializedName: "networkConnect", type: { name: "String" } }, sentRequest: { serializedName: "sentRequest", type: { name: "String" } }, receivedResponse: { serializedName: "receivedResponse", type: { name: "String" } }, domProcessing: { serializedName: "domProcessing", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } }, measurements: { serializedName: "measurements", type: { name: "Dictionary", value: { type: { name: "Number" } } } } } } }; export const RemoteDependencyData: coreClient.CompositeMapper = { type: { name: "Composite", className: "RemoteDependencyData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, id: { constraints: { MaxLength: 512 }, serializedName: "id", type: { name: "String" } }, name: { constraints: { MaxLength: 1024 }, serializedName: "name", required: true, type: { name: "String" } }, resultCode: { constraints: { MaxLength: 1024 }, serializedName: "resultCode", type: { name: "String" } }, data: { constraints: { MaxLength: 8192 }, serializedName: "data", type: { name: "String" } }, type: { constraints: { MaxLength: 1024 }, serializedName: "type", type: { name: "String" } }, target: { constraints: { MaxLength: 1024 }, serializedName: "target", type: { name: "String" } }, duration: { serializedName: "duration", required: true, type: { name: "String" } }, success: { defaultValue: true, serializedName: "success", type: { name: "Boolean" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } }, measurements: { serializedName: "measurements", type: { name: "Dictionary", value: { type: { name: "Number" } } } } } } }; export const RequestData: coreClient.CompositeMapper = { type: { name: "Composite", className: "RequestData", additionalProperties: { type: { name: "Object" } }, modelProperties: { ...MonitorDomain.type.modelProperties, id: { constraints: { MaxLength: 512 }, serializedName: "id", required: true, type: { name: "String" } }, name: { constraints: { MaxLength: 1024 }, serializedName: "name", type: { name: "String" } }, duration: { serializedName: "duration", required: true, type: { name: "String" } }, success: { defaultValue: true, serializedName: "success", required: true, type: { name: "Boolean" } }, responseCode: { constraints: { MaxLength: 1024 }, serializedName: "responseCode", required: true, type: { name: "String" } }, source: { constraints: { MaxLength: 1024 }, serializedName: "source", type: { name: "String" } }, url: { constraints: { MaxLength: 2048 }, serializedName: "url", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "String" }, constraints: { MaxLength: 8192 } } } }, measurements: { serializedName: "measurements", type: { name: "Dictionary", value: { type: { name: "Number" } } } } } } };
the_stack
import {FakeTransportBuilder, frameRequest, TriggerableTransport} from "./index"; import {PingRequest, PingResponse} from "../../../integration_test/ts/_proto/improbable/grpcweb/test/test_pb"; import {TestService} from "../../../integration_test/ts/_proto/improbable/grpcweb/test/test_pb_service"; import {grpc} from "@improbable-eng/grpc-web"; describe("FakeTransportBuilder", () => { describe("stubs", () => { it("should allow the response messages to be stubbed", done => { const pingResponseMsg = makePingResponse("hello"); const transport = new FakeTransportBuilder() .withMessages([ pingResponseMsg ]) .build(); doPingRequest(transport, new PingRequest(), data => { expect(data.receivedMessages).toEqual( [ pingResponseMsg ]); done(); }) }); it("should allow the response trailers to be stubbed", done => { const expectedTrailers = new grpc.Metadata({ foo: "bar" }); const transport = new FakeTransportBuilder() .withTrailers(expectedTrailers) .build(); doPingRequest(transport, new PingRequest(), data => { expect(data.trailers).toEqual(expectedTrailers); done(); }) }); it("should allow an error to be injected before any headers are sent", done => { const transport = new FakeTransportBuilder() .withPreHeadersError(500) .withMessages([ makePingResponse("hello") ]) .build(); doPingRequest(transport, new PingRequest(), data => { expect(data.message).toBe(""); expect(data.code).toBe(grpc.Code.Unknown); // message should not have been sent as an error should have been injected before any messages were sent. expect(data.receivedMessages).toEqual([]); done(); }) }); it("should allow an error to be injected before any messages are sent", done => { const pingResponseMsg = makePingResponse("hello"); const trailers = new grpc.Metadata({ foo: "bar" }); const transport = new FakeTransportBuilder() .withPreMessagesError(grpc.Code.FailedPrecondition, "failed precondition :)") .withMessages([ pingResponseMsg ]) .withTrailers(trailers) .build(); doPingRequest(transport, new PingRequest(), data => { expect(data.code).toBe(grpc.Code.FailedPrecondition); expect(data.message).toBe("failed precondition :)"); // message should not have been sent as an error should have been injected before any messages were sent. expect(data.receivedMessages).toEqual([]); // custom trailer ("foo") should not have been sent as an error was injected before any messages were sent. expectMetadataEqual(data.trailers, { "grpc-message": [ "failed precondition :)"], "grpc-status": [ `${grpc.Code.FailedPrecondition}` ], }); done(); }) }); it("should allow an error to be injected after messages are sent", done => { const pingResponseMsg = makePingResponse("hello"); const trailers = new grpc.Metadata({ foo: "bar" }); const transport = new FakeTransportBuilder() .withPreTrailersError(grpc.Code.FailedPrecondition, "failed precondition :)") .withMessages([ pingResponseMsg ]) .withTrailers(trailers) .build(); doPingRequest(transport, new PingRequest(), data => { expect(data.code).toBe(grpc.Code.FailedPrecondition); expect(data.message).toBe("failed precondition :)"); expect(data.receivedMessages).toEqual([ pingResponseMsg ]); // custom trailer ("foo") should not have been sent as an error was injected before any messages were sent. expectMetadataEqual(data.trailers, { "grpc-message": [ "failed precondition :)"], "grpc-status": [ `${grpc.Code.FailedPrecondition}` ], }); done(); }) }); }); describe("hooks", () => { describe("withMessageListener", () => { it("should not be called if no message is sent", done => { const messageSpy = jest.fn(); const transport = new FakeTransportBuilder() .withMessageListener(messageSpy) .build(); doPingStreamRequest(transport, [], () => { expect(messageSpy).toHaveBeenCalledTimes(0); done(); }); }); it("should be called once with the message bytes if a single message is sent", done => { const messageSpy = jest.fn(); const req = makePingRequest("hello"); const expectedBytes = frameRequest(req); const transport = new FakeTransportBuilder() .withMessageListener(messageBytes => { messageSpy(messageBytes); }) .build(); doPingStreamRequest(transport, [ req ], () => { expect(messageSpy).toHaveBeenCalledTimes(1); expect(messageSpy).toHaveBeenCalledWith(expectedBytes); done(); }); }); it("should be called twice, in message order, when two messages are sent", done => { const messageSpy = jest.fn(); const reqA = makePingRequest("req A"); const reqB = makePingRequest("req B"); const expectedBytes = [ frameRequest(reqA), frameRequest(reqB) ]; const transport = new FakeTransportBuilder() .withMessageListener(messageSpy) .build(); doPingStreamRequest(transport, [ reqA, reqB ], () => { expect(messageSpy).toHaveBeenCalledTimes(2); for (let i = 0; i < messageSpy.mock.calls.length; i++) { expect(messageSpy.mock.calls[i][0]).toEqual(expectedBytes[i]); } done(); }); }); }); describe("withHeadersListener", () => { it("should be called once with the metadata object passed to client.start()", done => { const headersSpy = jest.fn(); const expectedHeaders = new grpc.Metadata({ expected: "header" }); const transport = new FakeTransportBuilder() .withHeadersListener(headersSpy) .build(); const client = makeClient(TestService.PingStream, transport, () => { expect(headersSpy).toHaveBeenCalledTimes(1); const receivedHeaders = headersSpy.mock.calls[0][0]; expect(receivedHeaders.get("expected")).toEqual([ "header" ]); done(); }); client.start(expectedHeaders); client.finishSend(); }) }); describe("withRequestListener", () => { it("should be called once with the grpc.TransportOptions that were used to make the request", done => { const requestSpy = jest.fn(); const transport = new FakeTransportBuilder() .withRequestListener(requestSpy) .build(); doPingRequest(transport, new PingRequest(), () => { expect(requestSpy).toHaveBeenCalledTimes(1); const actual: grpc.TransportOptions = requestSpy.mock.calls[0][0]; expect(actual.methodDefinition).toBe(TestService.Ping); expect(actual.url).toBe("localhost/improbable.grpcweb.test.TestService/Ping"); done(); }); }) }); describe("withCancelListener", () => { it("should be called once should the request be cancelled by the client", done => { const cancelSpy = jest.fn(); const transport = new FakeTransportBuilder() .withCancelListener(cancelSpy) .build(); const client = makeClient(TestService.Ping, transport, () => {}); client.start(); expect(cancelSpy).not.toHaveBeenCalled(); client.close(); expect(cancelSpy).toHaveBeenCalledTimes(1); done(); }) }); describe("withFinishSendListener", () => { it("should be called once when the client finishes sending messages to the server", done => { const finishSendSpy = jest.fn(); const transport = new FakeTransportBuilder() .withFinishSendListener(finishSendSpy) .build(); const client = makeClient(TestService.Ping, transport, () => {}); client.start(); client.send(new PingResponse()); expect(finishSendSpy).not.toHaveBeenCalled(); client.finishSend(); expect(finishSendSpy).toHaveBeenCalledTimes(1); done(); }) }); }); describe("manual trigger", () => { it("should allow the consumer to control the lifecycle of the server response", () => { const onHeadersSpy = jest.fn(); const onMessageSpy = jest.fn(); const onEndSpy = jest.fn(); const transport = new FakeTransportBuilder() .withManualTrigger() .withHeaders(new grpc.Metadata({ header: "value" })) .withMessages([ makePingResponse("msgA") ]) .withTrailers(new grpc.Metadata({ trailer: "value" })) .build(); const client = grpc.client(TestService.Ping, { host: "localhost", transport, }); client.onHeaders(onHeadersSpy); client.onMessage(onMessageSpy); client.onEnd(onEndSpy); client.start(); client.send(new PingRequest()); client.finishSend(); expect(onHeadersSpy).not.toHaveBeenCalled(); expect(onMessageSpy).not.toHaveBeenCalled(); expect(onEndSpy).not.toHaveBeenCalled(); transport.sendHeaders(); expect(onHeadersSpy).toHaveBeenCalled(); expect(onMessageSpy).not.toHaveBeenCalled(); expect(onEndSpy).not.toHaveBeenCalled(); transport.sendMessages(); expect(onHeadersSpy).toHaveBeenCalled(); expect(onMessageSpy).toHaveBeenCalled(); expect(onEndSpy).not.toHaveBeenCalled(); transport.sendTrailers(); expect(onHeadersSpy).toHaveBeenCalled(); expect(onMessageSpy).toHaveBeenCalled(); expect(onEndSpy).toHaveBeenCalled(); }); }); // Ideally this would be a custom matcher, but this also works :) function expectMetadataEqual(actual: grpc.Metadata, expectedMetadataEntries: { [k: string]: string[] }) { const actualMetadataEntries: { [k: string]: string[] } = {}; actual.forEach((key: string, values: string[]) => { actualMetadataEntries[key] = values; }); expect(actualMetadataEntries).toEqual(expectedMetadataEntries); } function makePingRequest(value: string): PingRequest { const r = new PingRequest(); r.setValue(value); return r; } function makePingResponse(value: string): PingResponse { const r = new PingResponse(); r.setValue(value); return r; } interface RequestResponse<T> { receivedMessages: T[] code: grpc.Code message: string receivedHeaders: grpc.Metadata trailers: grpc.Metadata } function makeClient<TRequest extends grpc.ProtobufMessage, TResponse extends grpc.ProtobufMessage, M extends grpc.MethodDefinition<TRequest, TResponse>>(method: M, transport: TriggerableTransport, callback: (data: RequestResponse<TResponse>) => void) { const client = grpc.client(method, { host: "localhost", transport, }); const receivedMessages: TResponse[] = []; let receivedHeaders: grpc.Metadata = new grpc.Metadata(); client.onMessage(message => receivedMessages.push(message as TResponse)); client.onHeaders(headers => receivedHeaders = headers); client.onEnd((code, message, trailers) => callback({ receivedMessages, receivedHeaders, code, message, trailers })); return client; } function doPingRequest(transport: TriggerableTransport, req: PingRequest, callback: (data: RequestResponse<PingResponse>) => void) { const client = makeClient(TestService.Ping, transport, callback); client.start(); client.send(req); client.finishSend(); } function doPingStreamRequest(transport: TriggerableTransport, requests: PingRequest[], callback: (data: RequestResponse<PingResponse>) => void) { const client = makeClient(TestService.PingStream, transport, callback); client.start(); for (const req of requests) { client.send(req); } client.finishSend(); } });
the_stack
* First 10 predefined colors used for plotting by Mathematica. * * Also known as _indexed color scheme #97_. */ const MATHEMATICA_COLORS: Record<string, string> = { m0: '#3F3D99', // Strong blue m1: '#993D71', // Strong cerise m2: '#998B3D', // Strong gold m3: '#3D9956', // Malachite green m4: '#3D5A99', // Strong cobalt blue m5: '#993D90', // Strong orchid m6: '#996D3D', // Strong orange m7: '#43993D', // Strong sap green m8: '#3D7999', // Cornflower blue m9: '#843D99', // Mulberry }; // ColorData97 (Mathematica standard lines) // rgb(0.368417, 0.506779, 0.709798), #5e81b5 // rgb(0.880722, 0.611041, 0.142051), // rgb(0.560181, 0.691569, 0.194885), // rgb(0.922526, 0.385626, 0.209179), // rgb(0.528488, 0.470624, 0.701351), // rgb(0.772079, 0.431554, 0.102387), // rgb(0.363898, 0.618501, 0.782349), // rgb(1, 0.75, 0), // rgb(0.647624, 0.37816, 0.614037), // rgb(0.571589, 0.586483, 0.), // rgb(0.915, 0.3325, 0.2125), // rgb(0.40082222609352647, 0.5220066643438841, 0.85), // rgb(0.9728288904374106, 0.621644452187053, 0.07336199581899142), // rgb(0.736782672705901, 0.358, 0.5030266573755369), // rgb(0.28026441037696703, 0.715, 0.4292089322474965) /** * Matlab colors */ export const MATLAB_COLORS: Record<string, string> = { blue: '#0072BD', // [0, 0.4470, 0.7410] blue orange: '#D95319', // [0.8500, 0.3250, 0.0980] orange yellow: '#EDB120', // [0.9290, 0.6940, 0.1250] yellow purple: '#7E2F8E', // [0.4940, 0.1840, 0.5560] purple green: '#77AC30', // [0.4660, 0.6740, 0.1880] green cyan: '#4DBEEE', // [0.3010, 0.7450, 0.9330] cyan red: '#A2142F', // [0.6350, 0.0780, 0.1840] dark red }; // Colors from Chromatic 100 design scale export const BACKGROUND_COLORS = { 'red': '#fbbbb6', 'orange': '#ffe0c2', 'yellow': '#fff1c2', 'lime': '#d0e8b9', 'green': '#bceac4', 'teal': '#b9f1f1', 'blue': '#b6d9fb', 'indigo': '#d1c2f0', 'purple': '#e3baf8', 'magenta': '#f9c8e0', 'black': '#353535', 'dark-grey': '#8C8C8C', 'grey': '#D0D0D0', 'light-grey': '#F0F0F0', 'white': '#ffffff', }; // Colors from Chromatic 500 (and 600, 700) design scale export const FOREGROUND_COLORS = { 'red': '#d7170b', //<- 700, 500 ->'#f21c0d' 'orange': '#fe8a2b', 'yellow': '#ffc02b', // <- 600, 500 -> '#ffcf33', 'lime': '#63b215', 'green': '#21ba3a', 'teal': '#17cfcf', 'blue': '#0d80f2', 'indigo': '#63c', 'purple': '#a219e6', 'magenta': '#eb4799', 'black': '#000', 'dark-grey': '#666', 'grey': '#A6A6A6', 'light-grey': '#d4d5d2', 'white': '#ffffff', }; // Map some of the DVIPS color names to Chromatic const DVIPS_TO_CHROMATIC = { Red: 'red', Orange: 'orange', Yellow: 'yellow', LimeGreen: 'lime', Green: 'green', TealBlue: 'teal', Blue: 'blue', Violet: 'indigo', Purple: 'purple', Magenta: 'magenta', Black: 'black', Gray: 'grey', White: 'white', }; /** * 68 colors (+ white) known to dvips used in LaTeX. * * The color names are based on the names of the _Crayola Crayon_ box of * 64 crayons. * * See: * - {@link https://ctan.org/pkg/colordvi | ColorDVI.tex} * - {@link https://en.wikibooks.org/w/index.php?title=LaTeX/Colors | Wikibooks:LaTeX/Colors} * * We use the Matlab colors for common colors by default. * */ const DVIPS_COLORS: Record<string, string> = { Apricot: '#FBB982', Aquamarine: '#00B5BE', Bittersweet: '#C04F17', Black: '#221E1F', // Indeed. Blue: '#2D2F92', BlueGreen: '#00B3B8', BlueViolet: '#473992', BrickRed: '#B6321C', Brown: '#792500', BurntOrange: '#F7921D', CadetBlue: '#74729A', CarnationPink: '#F282B4', Cerulean: '#00A2E3', CornflowerBlue: '#41B0E4', Cyan: '#00AEEF', Dandelion: '#FDBC42', DarkOrchid: '#A4538A', Emerald: '#00A99D', ForestGreen: '#009B55', Fuchsia: '#8C368C', Goldenrod: '#FFDF42', Gray: '#949698', Green: '#00A64F', GreenYellow: '#DFE674', JungleGreen: '#00A99A', Lavender: '#F49EC4', Limegreen: '#8DC73E', Magenta: '#EC008C', Mahogany: '#A9341F', Maroon: '#AF3235', Melon: '#F89E7B', MidnightBlue: '#006795', Mulberry: '#A93C93', NavyBlue: '#006EB8', OliveGreen: '#3C8031', Orange: '#F58137', OrangeRed: '#ED135A', Orchid: '#AF72B0', Peach: '#F7965A', Periwinkle: '#7977B8', PineGreen: '#008B72', Plum: '#92268F', ProcessBlue: '#00B0F0', Purple: '#99479B', RawSienna: '#974006', Red: '#ED1B23', RedOrange: '#F26035', RedViolet: '#A1246B', Rhodamine: '#EF559F', RoyalBlue: '#0071BC', RoyalPurple: '#613F99', RubineRed: '#ED017D', Salmon: '#F69289', SeaGreen: '#3FBC9D', Sepia: '#671800', SkyBlue: '#46C5DD', SpringGreen: '#C6DC67', Tan: '#DA9D76', TealBlue: '#00AEB3', Thistle: '#D883B7', Turquoise: '#00B4CE', Violet: '#58429B', VioletRed: '#EF58A0', White: '#FFFFFF', WildStrawberry: '#EE2967', Yellow: '#FFF200', YellowGreen: '#98CC70', YellowOrange: '#FAA21A', }; // Other color lists: SVG colors, x11 colors /* aliceblue rgb(240, 248, 255) antiquewhite rgb(250, 235, 215) aqua rgb( 0, 255, 255) aquamarine rgb(127, 255, 212) azure rgb(240, 255, 255) beige rgb(245, 245, 220) bisque rgb(255, 228, 196) black rgb( 0, 0, 0) blanchedalmond rgb(255, 235, 205) blue rgb( 0, 0, 255) blueviolet rgb(138, 43, 226) brown rgb(165, 42, 42) burlywood rgb(222, 184, 135) cadetblue rgb( 95, 158, 160) chartreuse rgb(127, 255, 0) chocolate rgb(210, 105, 30) coral rgb(255, 127, 80) cornflowerblue rgb(100, 149, 237) cornsilk rgb(255, 248, 220) crimson rgb(220, 20, 60) cyan rgb( 0, 255, 255) darkblue rgb( 0, 0, 139) darkcyan rgb( 0, 139, 139) darkgoldenrod rgb(184, 134, 11) darkgray rgb(169, 169, 169) darkgreen rgb( 0, 100, 0) darkgrey rgb(169, 169, 169) darkkhaki rgb(189, 183, 107) darkmagenta rgb(139, 0, 139) darkolivegreen rgb( 85, 107, 47) darkorange rgb(255, 140, 0) darkorchid rgb(153, 50, 204) darkred rgb(139, 0, 0) darksalmon rgb(233, 150, 122) darkseagreen rgb(143, 188, 143) darkslateblue rgb( 72, 61, 139) darkslategray rgb( 47, 79, 79) darkslategrey rgb( 47, 79, 79) darkturquoise rgb( 0, 206, 209) darkviolet rgb(148, 0, 211) deeppink rgb(255, 20, 147) deepskyblue rgb( 0, 191, 255) dimgray rgb(105, 105, 105) dimgrey rgb(105, 105, 105) dodgerblue rgb( 30, 144, 255) firebrick rgb(178, 34, 34) floralwhite rgb(255, 250, 240) forestgreen rgb( 34, 139, 34) fuchsia rgb(255, 0, 255) gainsboro rgb(220, 220, 220) ghostwhite rgb(248, 248, 255) gold rgb(255, 215, 0) goldenrod rgb(218, 165, 32) gray rgb(128, 128, 128) grey rgb(128, 128, 128) green rgb( 0, 128, 0) greenyellow rgb(173, 255, 47) honeydew rgb(240, 255, 240) hotpink rgb(255, 105, 180) indianred rgb(205, 92, 92) indigo rgb( 75, 0, 130) ivory rgb(255, 255, 240) khaki rgb(240, 230, 140) lavender rgb(230, 230, 250) lavenderblush rgb(255, 240, 245) lawngreen rgb(124, 252, 0) lemonchiffon rgb(255, 250, 205) lightblue rgb(173, 216, 230) lightcoral rgb(240, 128, 128) lightcyan rgb(224, 255, 255) lightgoldenrodyellow rgb(250, 250, 210) lightgray rgb(211, 211, 211) lightgreen rgb(144, 238, 144) lightgrey rgb(211, 211, 211) lightpink rgb(255, 182, 193) lightsalmon rgb(255, 160, 122) lightseagreen rgb( 32, 178, 170) lightskyblue rgb(135, 206, 250) lightslategray rgb(119, 136, 153) lightslategrey rgb(119, 136, 153) lightsteelblue rgb(176, 196, 222) lightyellow rgb(255, 255, 224) lime rgb( 0, 255, 0) limegreen rgb( 50, 205, 50) linen rgb(250, 240, 230) magenta rgb(255, 0, 255) maroon rgb(128, 0, 0) mediumaquamarine rgb(102, 205, 170) mediumblue rgb( 0, 0, 205) mediumorchid rgb(186, 85, 211) mediumpurple rgb(147, 112, 219) mediumseagreen rgb( 60, 179, 113) mediumslateblue rgb(123, 104, 238) mediumspringgreen rgb( 0, 250, 154) mediumturquoise rgb( 72, 209, 204) mediumvioletred rgb(199, 21, 133) midnightblue rgb( 25, 25, 112) mintcream rgb(245, 255, 250) mistyrose rgb(255, 228, 225) moccasin rgb(255, 228, 181) navajowhite rgb(255, 222, 173) navy rgb( 0, 0, 128) oldlace rgb(253, 245, 230) olive rgb(128, 128, 0) olivedrab rgb(107, 142, 35) orange rgb(255, 165, 0) orangered rgb(255, 69, 0) orchid rgb(218, 112, 214) palegoldenrod rgb(238, 232, 170) palegreen rgb(152, 251, 152) paleturquoise rgb(175, 238, 238) palevioletred rgb(219, 112, 147) papayawhip rgb(255, 239, 213) peachpuff rgb(255, 218, 185) peru rgb(205, 133, 63) pink rgb(255, 192, 203) plum rgb(221, 160, 221) powderblue rgb(176, 224, 230) purple rgb(128, 0, 128) red rgb(255, 0, 0) rosybrown rgb(188, 143, 143) royalblue rgb( 65, 105, 225) saddlebrown rgb(139, 69, 19) salmon rgb(250, 128, 114) sandybrown rgb(244, 164, 96) seagreen rgb( 46, 139, 87) seashell rgb(255, 245, 238) sienna rgb(160, 82, 45) silver rgb(192, 192, 192) skyblue rgb(135, 206, 235) slateblue rgb(106, 90, 205) slategray rgb(112, 128, 144) slategrey rgb(112, 128, 144) snow rgb(255, 250, 250) springgreen rgb( 0, 255, 127) steelblue rgb( 70, 130, 180) tan rgb(210, 180, 140) teal rgb( 0, 128, 128) thistle rgb(216, 191, 216) tomato rgb(255, 99, 71) turquoise rgb( 64, 224, 208) violet rgb(238, 130, 238) wheat rgb(245, 222, 179) white rgb(255, 255, 255) whitesmoke rgb(245, 245, 245) yellow rgb(255, 255, 0) yellowgreen rgb(154, 205, 50) */ /** * Return a CSS color (#rrggbb) from a string. * * Possible formats include: * - named colors from the DVI color set: 'Yellow', 'red'... Case sensitive. * - colors from the Mathematica set: 'M1'...'M9' * - 3-digit hex: `'#d50'` * - 6-digit hex: `'#dd5500'` * - RGB functional: `'rgb(240, 20, 10)'` * * In addition, colors can be mixed using the following syntax: * `<mix> = <color>![<value>][!<mix>]` * For example: * - `'Blue!20'` = 20% blue + 80% white * - `'Blue!20!Black'` = 20% + 80% black * - `'Blue!20!Black!30!Green'` = (20% + 80% black) * 30 % + 70% green * * If the input string is prefixed with a dash, the complementary color * of the expression is returned. * * This creative syntax is defined by the {@link http://mirror.jmu.edu/pub/CTAN/macros/latex/contrib/xcolor/xcolor.pdf | `xcolor` LaTeX package}. * * @param s - An expression representing a color value * @return An RGB color expressed as a hex-triplet preceded by `#` */ export function defaultColorMap(s: string): string | undefined { const colorSpec = s.split('!'); let baseRed: number; let baseGreen: number; let baseBlue: number; let red = 255; let green = 255; let blue = 255; let mix = -1; // If the string is prefixed with a '-', use the complementary color const complementary = colorSpec.length > 0 && colorSpec[0].startsWith('-'); if (complementary) colorSpec[0] = colorSpec[0].slice(1); for (let i = 0; i < colorSpec.length; i++) { baseRed = red; baseGreen = green; baseBlue = blue; const colorName = colorSpec[i].trim().match(/^([A-Za-z\d]+)/)?.[1]; const lcColorName = colorName?.toLowerCase(); const color = !colorName ? colorSpec[i].trim() : FOREGROUND_COLORS[lcColorName!] ?? FOREGROUND_COLORS[DVIPS_TO_CHROMATIC[colorName]] ?? MATLAB_COLORS[colorName] ?? DVIPS_COLORS[colorName] ?? MATHEMATICA_COLORS[colorName] ?? colorSpec[i].trim(); let m = color.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i); if (m?.[1] && m[2] && m[3]) { // It's a six-digit hex number red = Math.max(0, Math.min(255, Number.parseInt(m[1], 16))); green = Math.max(0, Math.min(255, Number.parseInt(m[2], 16))); blue = Math.max(0, Math.min(255, Number.parseInt(m[3], 16))); } else { m = color.match(/^#([\da-f]{3})$/i); if (m?.[1]) { // It's a three-digit hex number const r1 = Number.parseInt(m[1][0], 16); const g1 = Number.parseInt(m[1][1], 16); const b1 = Number.parseInt(m[1][2], 16); red = Math.max(0, Math.min(255, r1 * 16 + r1)); green = Math.max(0, Math.min(255, g1 * 16 + g1)); blue = Math.max(0, Math.min(255, b1 * 16 + b1)); } else { // It's a rgb functional m = color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i); if (m?.[1] && m[2] && m[3]) { red = Math.max(0, Math.min(255, Number.parseInt(m[1]))); green = Math.max(0, Math.min(255, Number.parseInt(m[2]))); blue = Math.max(0, Math.min(255, Number.parseInt(m[3]))); } else { return undefined; } } } if (mix >= 0) { red = (1 - mix) * red + mix * baseRed; green = (1 - mix) * green + mix * baseGreen; blue = (1 - mix) * blue + mix * baseBlue; mix = -1; } if (i + 1 < colorSpec.length) { mix = Math.max(0, Math.min(100, Number.parseInt(colorSpec[++i]))) / 100; } } if (mix >= 0) { red = mix * red + (1 - mix) * baseRed!; green = mix * green + (1 - mix) * baseGreen!; blue = mix * blue + (1 - mix) * baseBlue!; } if (complementary) { red = 255 - red; green = 255 - green; blue = 255 - blue; } return ( '#' + ('00' + Math.round(red).toString(16)).slice(-2) + ('00' + Math.round(green).toString(16)).slice(-2) + ('00' + Math.round(blue).toString(16)).slice(-2) ); } export function defaultBackgroundColorMap(s: string): string | undefined { s = s.trim(); return ( BACKGROUND_COLORS[s.toLowerCase()] ?? BACKGROUND_COLORS[DVIPS_TO_CHROMATIC[s]] ?? defaultColorMap(s) ); } function parseHex( hex: string ): undefined | { r: number; g: number; b: number } { if (!hex) return undefined; if (hex[0] !== '#') return undefined; hex = hex.slice(1); let result; if (hex.length <= 4) { result = { r: parseInt(hex[0] + hex[0], 16), g: parseInt(hex[1] + hex[1], 16), b: parseInt(hex[2] + hex[2], 16), }; if (hex.length === 4) { result.a = parseInt(hex[3] + hex[3], 16) / 255; } } else { result = { r: parseInt(hex[0] + hex[1], 16), g: parseInt(hex[2] + hex[3], 16), b: parseInt(hex[4] + hex[5], 16), }; if (hex.length === 8) { result.a = parseInt(hex[6] + hex[7], 16) / 255; } } if (result && result.a === undefined) result.a = 1.0; return result; } function hueToRgbChannel(t1: number, t2: number, hue: number): number { if (hue < 0) hue += 6; if (hue >= 6) hue -= 6; if (hue < 1) return (t2 - t1) * hue + t1; else if (hue < 3) return t2; else if (hue < 4) return (t2 - t1) * (4 - hue) + t1; return t1; } function hslToRgb(hsl: { h: number; s: number; l: number }): { r: number; g: number; b: number; } { let [hue, sat, light] = [hsl.h, hsl.s, hsl.l]; hue = ((hue + 360) % 360) / 60.0; light = Math.max(0, Math.min(light, 1.0)); sat = Math.max(0, Math.min(sat, 1.0)); const t2 = light <= 0.5 ? light * (sat + 1) : light + sat - light * sat; const t1 = light * 2 - t2; return { r: Math.round(255 * hueToRgbChannel(t1, t2, hue + 2)), g: Math.round(255 * hueToRgbChannel(t1, t2, hue)), b: Math.round(255 * hueToRgbChannel(t1, t2, hue - 2)), }; } function clampByte(v: number): number { if (v < 0) return 0; if (v > 255) return 255; return Math.round(v); } function rgbToHexstring(rgb: { r: number; g: number; b: number }): string { const { r, g, b } = rgb; let hexString = ( (1 << 24) + (clampByte(r) << 16) + (clampByte(g) << 8) + clampByte(b) ) .toString(16) .slice(1); if ( hexString[0] === hexString[1] && hexString[2] === hexString[3] && hexString[4] === hexString[5] && hexString[6] === hexString[7] ) { hexString = hexString[0] + hexString[2] + hexString[4]; } return '#' + hexString; } function rgbToHsl(rgb: { r: number; g: number; b: number }): { h: number; s: number; l: number; } { let { r, g, b } = rgb; r = r / 255; g = g / 255; b = b / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return { h: h, s: s, l: l }; } export function highlight(color: string): string { // eslint-disable-next-line prefer-const let rgb = parseHex(color); if (!rgb) return color; // eslint-disable-next-line prefer-const let { h, s, l } = rgbToHsl(rgb); s += 0.1; l -= 0.1; return rgbToHexstring(hslToRgb({ h, s, l })); }
the_stack
import { ApplicationLogJSON, assertTriggerTypeJSON, BinaryWriter, BlockJSON, CallReceiptJSON, common, ConfirmedTransactionJSON, ContractJSON, crypto, FailedTransactionJSON, HeaderJSON, JSONHelper, NativeContractJSON, Nep17BalancesJSON, Nep17TransfersJSON, Nep17TransferSource, NetworkSettingsJSON, Peer, PrivateNetworkSettings, RelayTransactionResultJSON, scriptHashToAddress, SendRawTransactionResultJSON, StorageItemJSON, toVerifyResultJSON, toVMStateJSON, TransactionDataJSON, TransactionJSON, TransactionReceiptJSON, TriggerTypeJSON, UInt256, UnclaimedGASJSON, ValidateAddressJSON, ValidatorJSON, VerificationCostJSON, VerifyResultModel, VerifyResultModelExtended, VersionJSON, } from '@neo-one/client-common'; import { AggregationType, globalStats, MeasureUnit, TagMap } from '@neo-one/client-switch'; import { createChild, nodeLogger } from '@neo-one/logger'; import { Blockchain, getEndpointConfig, NativeContainer, Nep17Transfer, Nep17TransferKey, Node, Signers, StorageKey, Transaction, TransactionData, } from '@neo-one/node-core'; import { Labels, labelToTag, utils } from '@neo-one/utils'; import { BN } from 'bn.js'; import { filter, map, switchMap, take, timeout, toArray } from 'rxjs/operators'; const logger = createChild(nodeLogger, { component: 'rpc-handler' }); export type HandlerPrimitive = string | number | boolean; export type HandlerResult = | object | undefined | ReadonlyArray<object | HandlerPrimitive> | undefined | HandlerPrimitive | undefined | void; // tslint:disable-next-line no-any export type Handler = (args: readonly any[]) => Promise<HandlerResult>; interface Handlers { readonly [method: string]: Handler; } interface JSONRPCRequest { readonly jsonrpc: '2.0'; readonly id?: number | undefined; readonly method: string; readonly params?: readonly object[] | object; } export class JSONRPCError { public readonly code: number; public readonly message: string; public constructor(code: number, message: string) { this.code = code; this.message = message; } } const RPC_METHODS: { readonly [key: string]: string } = { // Blockchain getbestblockhash: 'getbestblockhash', getblock: 'getblock', getblockcount: 'getblockcount', getblockheadercount: 'getblockheadercount', getblockhash: 'getblockhash', getblockheader: 'getblockheader', getcontractstate: 'getcontractstate', getrawmempool: 'getrawmempool', getrawtransaction: 'getrawtransaction', getstorage: 'getstorage', getnextblockvalidators: 'getnextblockvalidators', gettransactionheight: 'gettransactionheight', // Node getconnectioncount: 'getconnectioncount', getpeers: 'getpeers', getversion: 'getversion', sendrawtransaction: 'sendrawtransaction', submitblock: 'submitblock', getcommittee: 'getcommittee', getnativecontracts: 'getnativecontracts', getstateroot: 'getstateroot', getstate: 'getstate', findstate: 'findstate', // SmartContract invokefunction: 'invokefunction', invokescript: 'invokescript', getunclaimedgas: 'getunclaimedgas', testtransaction: 'testtransaction', // Utilities listplugins: 'listplugins', validateaddress: 'validateaddress', getapplicationlog: 'getapplicationlog', // Wallet closewallet: 'closewallet', dumpprivkey: 'dumpprivkey', getnewaddress: 'getnewaddress', getwalletbalance: 'getwalletbalance', getwalletunclaimedgas: 'getwalletunclaimedgas', importprivkey: 'importprivkey', listaddress: 'listaddress', calculatenetworkfee: 'calculatenetworkfee', invokecontractverify: 'invokecontractverify', openwallet: 'openwallet', sendfrom: 'sendfrom', sendmany: 'sendmany', sendtoaddress: 'sendtoaddress', // NEP17 getnep17transfers: 'getnep17transfers', getnep17balances: 'getnep17balances', // Settings updatesettings: 'updatesettings', getsettings: 'getsettings', // NEO•ONE gettransactiondata: 'gettransactiondata', getfailedtransactions: 'getfailedtransactions', getfeeperbyte: 'getfeeperbyte', getexecfeefactor: 'getexecfeefactor', getverificationcost: 'getverificationcost', relaytransaction: 'relaytransaction', getallstorage: 'getallstorage', gettransactionreceipt: 'gettransactionreceipt', getnetworksettings: 'getnetworksettings', runconsensusnow: 'runconsensusnow', fastforwardoffset: 'fastforwardoffset', fastforwardtotime: 'fastforwardtotime', reset: 'reset', getneotrackerurl: 'getneotrackerurl', resetproject: 'resetproject', UNKNOWN: 'UNKNOWN', INVALID: 'INVALID', }; const mapToTransfers = ({ key, value }: { readonly key: Nep17TransferKey; readonly value: Nep17Transfer }) => ({ timestamp: key.timestampMS.toNumber(), assethash: common.uInt160ToString(key.assetScriptHash), transferaddress: value.userScriptHash.equals(common.ZERO_UINT160) ? // tslint:disable-next-line: no-null-keyword null : scriptHashToAddress(common.uInt160ToString(value.userScriptHash)), amount: value.amount.toString(), blockindex: value.blockIndex, transfernotifyindex: key.blockTransferNotificationIndex, txhash: common.uInt256ToString(value.txHash), source: value.source === Nep17TransferSource.Block ? 'Block' : 'Transaction', state: toVMStateJSON(value.state), }); const getScriptHashAndAddress = (param: string, addressVersion: number) => { if (param.length < 40) { return { address: param, scriptHash: crypto.addressToScriptHash({ addressVersion, address: param }) }; } const scriptHash = JSONHelper.readUInt160(param); return { scriptHash, address: crypto.scriptHashToAddress({ addressVersion, scriptHash }) }; }; const getVerifyResultErrorMessage = (extendedResult?: VerifyResultModelExtended) => { if (extendedResult !== undefined && extendedResult.verifyResult !== undefined) { return `Verification failed: ${extendedResult.verifyResult}${ extendedResult.failureReason === undefined ? '.' : `: ${extendedResult.failureReason}` }`; } return 'Verification failed.'; }; const rpcTag = labelToTag(Labels.RPC_METHOD); const requestDurations = globalStats.createMeasureDouble('request/duration', MeasureUnit.MS); const requestErrors = globalStats.createMeasureInt64('request/failures', MeasureUnit.UNIT); const SINGLE_REQUESTS_HISTOGRAM = globalStats.createView( 'jsonrpc_server_single_request_duration_ms', requestDurations, AggregationType.DISTRIBUTION, [rpcTag], 'Distribution of request durations', [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000], ); globalStats.registerView(SINGLE_REQUESTS_HISTOGRAM); const SINGLE_REQUEST_ERRORS_COUNTER = globalStats.createView( 'jsonrpc_server_single_request_failures_total', requestErrors, AggregationType.COUNT, [rpcTag], 'Total number of request errors', ); globalStats.registerView(SINGLE_REQUEST_ERRORS_COUNTER); const createJSONRPCHandler = (handlers: Handlers) => { // tslint:disable-next-line no-any const validateRequest = (request: any): JSONRPCRequest => { if ( request !== undefined && typeof request === 'object' && request.jsonrpc === '2.0' && request.method !== undefined && typeof request.method === 'string' && (request.params === undefined || Array.isArray(request.params) || typeof request.params === 'object') && (request.id === undefined || typeof request.id === 'string' || typeof request.id === 'number') ) { return request; } throw new JSONRPCError(-32600, 'Invalid Request'); }; // tslint:disable-next-line no-any const handleSingleRequest = async (requestIn: any) => { const startTime = utils.nowSeconds(); let labels = {}; let method = RPC_METHODS.UNKNOWN; try { let request; try { request = validateRequest(requestIn); } finally { if (request !== undefined) { ({ method } = request); } else if (typeof requestIn === 'object') { ({ method } = requestIn); } if ((RPC_METHODS[method] as string | undefined) === undefined) { method = RPC_METHODS.INVALID; } labels = { [Labels.RPC_METHOD]: method }; } const handler = handlers[request.method] as Handler | undefined; if (handler === undefined) { throw new JSONRPCError(-32601, 'Method not found'); } const { params } = request; let handlerParams: readonly object[]; if (params === undefined) { handlerParams = []; } else if (Array.isArray(params)) { handlerParams = params; } else { handlerParams = [params]; } const result = await handler(handlerParams); logger.debug({ name: 'jsonrpc_server_single_request', ...labels }); globalStats.record([ { measure: requestDurations, value: utils.nowSeconds() - startTime, }, ]); return { jsonrpc: '2.0', result, id: request.id === undefined ? undefined : request.id, }; } catch (err) { logger.error({ name: 'jsonrpc_server_single_request', ...labels, err }); const tags = new TagMap(); tags.set(rpcTag, { value: method }); globalStats.record( [ { measure: requestErrors, value: 1, }, ], tags, ); throw err; } }; const handleRequest = async (request: unknown) => { if (Array.isArray(request)) { return Promise.all(request.map(async (batchRequest) => handleSingleRequest(batchRequest))); } return handleSingleRequest(request); }; const handleRequestSafe = async ( labels: Record<string, string>, request: unknown, ): Promise<object | readonly object[]> => { try { // tslint:disable-next-line: no-any let result: any; try { result = await handleRequest(request); logger.debug({ name: 'jsonrpc_server_request', ...labels }); } catch (err) { logger.error({ name: 'jsonrpc_server_request', ...labels, err }); throw err; } return result; } catch (error) { let errorResponse = { code: -32603, message: error.message === undefined ? 'Internal error' : error.message, }; if ( error.code !== undefined && error.message !== undefined && typeof error.code === 'number' && typeof error.message === 'string' ) { errorResponse = { code: error.code, message: error.message }; } return { jsonrpc: '2.0', error: errorResponse, id: undefined, }; } }; return async (request: unknown) => handleRequestSafe({ [Labels.RPC_TYPE]: 'jsonrpc' }, request); }; // tslint:disable-next-line no-any export type RPCHandler = (request: unknown) => Promise<any>; export const createHandler = ({ blockchain, native, node, handleGetNEOTrackerURL, handleResetProject, }: { readonly blockchain: Blockchain; readonly native: NativeContainer; readonly node: Node; readonly handleGetNEOTrackerURL: () => Promise<string | undefined>; readonly handleResetProject: () => Promise<void>; }): RPCHandler => { const checkHeight = async (height: number) => { if (height < 0 || height > (await blockchain.getCurrentIndex())) { throw new JSONRPCError(-100, 'Invalid Height'); } }; const toScriptHash = (input: string) => { const keyword = input.toLowerCase(); // tslint:disable-next-line: no-loop-statement for (const nat of native.nativeContracts) { if (keyword === nat.name || keyword === nat.id.toString()) { return nat.hash; } } return JSONHelper.readUInt160(input); }; const getTransactionReceiptJSON = (value: TransactionData): TransactionReceiptJSON => ({ blockIndex: value.blockIndex, blockHash: JSONHelper.writeUInt256(value.blockHash), transactionIndex: value.transactionIndex, globalIndex: JSONHelper.writeUInt64(value.globalIndex), }); const handlers: Handlers = { // Blockchain [RPC_METHODS.getbestblockhash]: async (): Promise<string> => JSONHelper.writeUInt256(blockchain.currentBlock.hash), [RPC_METHODS.getblock]: async (args): Promise<BlockJSON | string> => { let hashOrIndex: number | UInt256 = args[0]; if (typeof args[0] === 'string') { hashOrIndex = JSONHelper.readUInt256(args[0]); } let watchTimeoutMS; if (args[1] !== undefined && typeof args[1] === 'number' && args[1] !== 1) { // eslint-disable-next-line watchTimeoutMS = args[1]; } else if (args[2] !== undefined && typeof args[2] === 'number') { // eslint-disable-next-line watchTimeoutMS = args[2]; } let block = await blockchain.getBlock(hashOrIndex); if (block === undefined) { if (watchTimeoutMS === undefined) { throw new JSONRPCError(-100, 'Unknown block'); } try { block = await blockchain.block$ .pipe( filter((value) => value.hashHex === args[0] || value.index === args[0]), take(1), timeout(new Date(Date.now() + watchTimeoutMS)), ) .toPromise(); } catch { throw new JSONRPCError(-100, 'Unknown block'); } } if (args[1] === true || args[1] === 1) { const confirmations = blockchain.currentBlockIndex - block.index + 1; const hash = await blockchain.getNextBlockHash(block.hash); const nextblockhash = hash ? JSONHelper.writeUInt256(hash) : undefined; const result = await block.serializeJSON(blockchain.serializeJSONContext); return { ...result, confirmations, nextblockhash, }; } return block.serializeWire().toString('base64'); }, [RPC_METHODS.getblockheadercount]: async (): Promise<number> => blockchain.headerCache.last?.index ?? (await blockchain.getCurrentIndex()) + 1, [RPC_METHODS.getblockcount]: async (): Promise<number> => (await blockchain.getCurrentIndex()) + 1, [RPC_METHODS.getblockhash]: async (args): Promise<string | undefined> => { const height = args[0]; await checkHeight(height); const hash = await blockchain.getBlockHash(height); return hash === undefined ? undefined : JSONHelper.writeUInt256(hash); }, [RPC_METHODS.getblockheader]: async (args): Promise<HeaderJSON | string> => { let hashOrIndex = args[0]; if (typeof args[0] === 'string') { hashOrIndex = JSONHelper.readUInt256(args[0]); } const verbose = args.length >= 2 ? !!args[1] : false; const header = await blockchain.getHeader(hashOrIndex); if (header === undefined) { throw new JSONRPCError(-100, 'Unknown block'); } if (verbose) { const confirmations = (await blockchain.getCurrentIndex()) - header.index + 1; const hash = await blockchain.getBlockHash(header.index + 1); const nextblockhash = hash ? JSONHelper.writeUInt256(hash) : undefined; return { ...header.serializeJSON(blockchain.serializeJSONContext), confirmations, nextblockhash }; } return header.serializeWire().toString('base64'); }, [RPC_METHODS.getcontractstate]: async (args): Promise<ContractJSON> => { const hash = toScriptHash(args[0]); const contract = await native.ContractManagement.getContract({ storages: blockchain.storages }, hash); if (contract === undefined) { throw new JSONRPCError(-100, 'Unknown contract'); } return contract.serializeJSON(); }, [RPC_METHODS.getrawmempool]: async (): Promise<readonly string[]> => Object.values(node.memPool).map((transaction) => JSONHelper.writeUInt256(transaction.hash)), [RPC_METHODS.getrawtransaction]: async (args): Promise<TransactionJSON | ConfirmedTransactionJSON | string> => { const hash = JSONHelper.readUInt256(args[0]); const verbose = args.length >= 2 && !!args[1]; let tx = node.memPool[common.uInt256ToHex(hash)] as Transaction | undefined; if (tx && !verbose) { return JSONHelper.writeBase64Buffer(tx.serializeWire()); } const state = await blockchain.getTransaction(hash); tx = tx ?? state?.transaction; if (tx === undefined) { throw new JSONRPCError(-100, 'Unknown Transaction'); } if (!verbose) { return JSONHelper.writeBase64Buffer(tx.serializeWire()); } if (state !== undefined) { const index = await blockchain.getBlockHash(state.blockIndex); if (index === undefined) { return tx.serializeJSON(); } const block = await blockchain.getBlock(index); if (block === undefined) { return tx.serializeJSON(); } return tx.serializeJSONWithData(blockchain.serializeJSONContext); } return tx.serializeJSON(); }, [RPC_METHODS.getstorage]: async (args): Promise<StorageItemJSON | string> => { const hash = JSONHelper.readUInt160(args[0]); const verbose = args.length >= 3 ? !!args[2] : false; const state = await native.ContractManagement.getContract({ storages: blockchain.storages }, hash); if (state === undefined) { throw new JSONRPCError(-100, 'Unknown contract'); } const id = state.id; const key = JSONHelper.readBase64Buffer(args[1]); const storageKey = new StorageKey({ id, key }); const item = await blockchain.storages.tryGet(storageKey); if (item === undefined) { throw new JSONRPCError(-100, 'Unknown storage'); } if (verbose) { return item.serializeJSON(storageKey); } return JSONHelper.writeBase64Buffer(item.value); }, [RPC_METHODS.getnextblockvalidators]: async (): Promise<readonly ValidatorJSON[]> => { const [validators, candidates] = await Promise.all([ native.NEO.computeNextBlockValidators({ storages: blockchain.storages }), native.NEO.getCandidates({ storages: blockchain.storages }), ]); if (candidates.length > 0) { return candidates.map((candidate) => ({ publickey: JSONHelper.writeECPoint(candidate.publicKey), votes: candidate.votes.toString(), active: validators.some((validator) => validator.equals(candidate.publicKey)), })); } return validators.map((validator) => ({ publickey: JSONHelper.writeECPoint(validator), votes: '0', active: true, })); }, [RPC_METHODS.gettransactionheight]: async (args) => { const hash = JSONHelper.readUInt256(args[0]); const state = await blockchain.getTransaction(hash); if (state === undefined) { throw new JSONRPCError(-100, 'Unknown transaction'); } return state.blockIndex; }, // Node [RPC_METHODS.getconnectioncount]: async (): Promise<number> => node.connectedPeers.length, [RPC_METHODS.getpeers]: async (): Promise<{ readonly connected: readonly Peer[] }> => ({ connected: node.connectedPeers.map((endpoint) => { const { host, port } = getEndpointConfig(endpoint); return { address: host, port }; }), }), [RPC_METHODS.getversion]: async (): Promise<VersionJSON> => { const { tcpPort: tcpport, wsPort: wsport, nonce, useragent } = node.version; const { network, maxValidUntilBlockIncrement, memoryPoolMaxTransactions, maxTransactionsPerBlock, addressVersion, validatorsCount, millisecondsPerBlock, maxTraceableBlocks, initialGasDistribution, } = blockchain.settings; return { tcpport, wsport, nonce, useragent, protocol: { addressversion: addressVersion, network, maxvaliduntilblockincrement: maxValidUntilBlockIncrement, maxtransactionsperblock: maxTransactionsPerBlock, validatorscount: validatorsCount, msperblock: millisecondsPerBlock, maxtraceableblocks: maxTraceableBlocks, memorypoolmaxtransactions: memoryPoolMaxTransactions, initialgasdistribution: initialGasDistribution.toNumber(), }, }; }, [RPC_METHODS.sendrawtransaction]: async (args): Promise<SendRawTransactionResultJSON> => { const transaction = Transaction.deserializeWire({ context: blockchain.deserializeWireContext, buffer: JSONHelper.readBase64Buffer(args[0]), }); try { const { verifyResult: result } = await node.relayTransaction(transaction, { forceAdd: true }); if (result !== undefined && result.verifyResult !== VerifyResultModel.Succeed) { throw new JSONRPCError(-500, getVerifyResultErrorMessage(result)); } return { hash: common.uInt256ToString(transaction.hash) }; } catch (error) { throw new JSONRPCError(-500, error.message); } }, [RPC_METHODS.submitblock]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.getcommittee]: async (): Promise<readonly string[]> => (await native.NEO.getCommittee({ storages: blockchain.storages })).map((member) => common.ecPointToString(member), ), [RPC_METHODS.getnativecontracts]: async (): Promise<readonly NativeContractJSON[]> => native.nativeContracts.map((nativeContract) => nativeContract.serializeJSON()), [RPC_METHODS.getstateroot]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.getstate]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.findstate]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, // SmartContract [RPC_METHODS.invokefunction]: async (_args) => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.invokescript]: async (args): Promise<CallReceiptJSON> => { const script = JSONHelper.readBase64Buffer(args[0]); const signers = args[1] !== undefined ? Signers.fromJSON(args[1]) : undefined; const receipt = blockchain.invokeScript({ script, signers }); return { result: receipt.result.serializeJSON(), actions: receipt.actions.map((action) => action.serializeJSON()), }; }, [RPC_METHODS.testtransaction]: async (args): Promise<CallReceiptJSON> => { const transaction = Transaction.deserializeWire({ context: blockchain.deserializeWireContext, buffer: JSONHelper.readBuffer(args[0]), }); const receipt = blockchain.testTransaction(transaction); return { result: receipt.result.serializeJSON(), actions: receipt.actions.map((action) => action.serializeJSON()), }; }, [RPC_METHODS.getunclaimedgas]: async (args): Promise<UnclaimedGASJSON> => { const address = args[0]; if (typeof address !== 'string') { throw new JSONRPCError(-100, 'Invalid argument at position 0'); } const scriptHash = crypto.addressToScriptHash({ address, addressVersion: blockchain.settings.addressVersion }); const isValidAddress = common.isUInt160(scriptHash); if (!isValidAddress) { throw new JSONRPCError(-100, 'Invalid address'); } const unclaimed = await native.NEO.unclaimedGas( { storages: blockchain.storages }, scriptHash, (await blockchain.getCurrentIndex()) + 1, ); return { unclaimed: unclaimed.toString(10), address: JSONHelper.writeUInt160(address), }; }, // Utilities [RPC_METHODS.validateaddress]: async (args): Promise<ValidateAddressJSON> => { let scriptHash; try { scriptHash = crypto.addressToScriptHash({ addressVersion: blockchain.settings.addressVersion, address: args[0], }); } catch { // Ignore errors } return { address: args[0], isvalid: scriptHash !== undefined }; }, [RPC_METHODS.listplugins]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.getapplicationlog]: async (args): Promise<ApplicationLogJSON> => { const hash = JSONHelper.readUInt256(args[0]); let trigger: TriggerTypeJSON | undefined; if (args.length >= 2 && args[1] != undefined) { try { trigger = assertTriggerTypeJSON(args[1]); } catch { // do nothing } } const value = await blockchain.applicationLogs.tryGet(hash); if (value === undefined) { throw new JSONRPCError(-100, 'Unknown transaction/blockhash'); } const { txid, blockhash, executions } = value; return { txid, blockhash, executions: trigger === undefined ? executions : executions.filter((execution) => execution.trigger === trigger), }; }, // Wallet [RPC_METHODS.closewallet]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.dumpprivkey]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.getnewaddress]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.getwalletbalance]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.getwalletunclaimedgas]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.importprivkey]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.listaddress]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.calculatenetworkfee]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.invokecontractverify]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.openwallet]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.sendfrom]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.sendmany]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, [RPC_METHODS.sendtoaddress]: async () => { throw new JSONRPCError(-101, 'Not implemented'); }, // NEP17 [RPC_METHODS.getnep17transfers]: async (args): Promise<Nep17TransfersJSON> => { const addressVersion = blockchain.settings.addressVersion; const { address, scriptHash } = getScriptHashAndAddress(args[0], addressVersion); const SEVEN_DAYS_IN_MS = 7 * 24 * 60 * 60 * 1000; const startTime = args[1] == undefined ? Date.now() - SEVEN_DAYS_IN_MS : args[1]; const endTime = args[2] == undefined ? Date.now() : args[2]; let source = Nep17TransferSource.Transaction; if (args[3] === 'All') { source = Nep17TransferSource.All; } if (args[3] === 'Block') { source = Nep17TransferSource.Block; } const useMaxVal = args[4] !== undefined; const ULONG_MAX = new BN('18446744073709551615', 10); // 64-bit unsigned int if (endTime < startTime) { throw new JSONRPCError(-32602, 'Invalid params'); } const startTimeBytes = new BinaryWriter().writeUInt64LE(new BN(startTime)).toBuffer(); const endTimeBytes = new BinaryWriter().writeUInt64LE(new BN(useMaxVal ? ULONG_MAX : endTime)).toBuffer(); const gte = Buffer.concat([scriptHash, startTimeBytes]); const lte = Buffer.concat([scriptHash, endTimeBytes]); const sentPromise = blockchain.nep17TransfersSent .find$(gte, lte) .pipe( filter(({ value }) => (source === Nep17TransferSource.All ? true : value.source === source)), map(mapToTransfers), toArray(), ) .toPromise(); const receivedPromise = blockchain.nep17TransfersReceived .find$(gte, lte) .pipe( filter(({ value }) => (source === Nep17TransferSource.All ? true : value.source === source)), map(mapToTransfers), toArray(), ) .toPromise(); const [sent, received] = await Promise.all([sentPromise, receivedPromise]); return { sent, received, address, }; }, [RPC_METHODS.getnep17balances]: async (args): Promise<Nep17BalancesJSON> => { // tslint:disable-next-line: no-suspicious-comment // TODO: need to check/test method this but probably good const { address, scriptHash } = getScriptHashAndAddress(args[0], blockchain.settings.addressVersion); const storedBalances = await blockchain.nep17Balances.find$(scriptHash).pipe(toArray()).toPromise(); const validBalances = await Promise.all( storedBalances.map(async ({ key, value }) => { const assetStillExists = await native.ContractManagement.getContract( { storages: blockchain.storages }, key.assetScriptHash, ); if (!assetStillExists) { return undefined; } return { assethash: common.uInt160ToString(key.assetScriptHash), amount: value.balance.toString(), lastupdatedblock: value.lastUpdatedBlock, }; }), ); return { balance: validBalances.filter(utils.notNull), address, }; }, // Settings [RPC_METHODS.updatesettings]: async (args): Promise<boolean> => { const { settings } = blockchain; const newSettings = { ...settings, millisecondsPerBlock: args[0].millisecondsPerBlock, }; blockchain.updateSettings(newSettings); return true; }, [RPC_METHODS.getsettings]: async (): Promise<PrivateNetworkSettings> => ({ millisecondsPerBlock: blockchain.settings.millisecondsPerBlock, }), // NEO•ONE [RPC_METHODS.relaytransaction]: async (args): Promise<RelayTransactionResultJSON> => { const transaction = Transaction.deserializeWire({ context: blockchain.deserializeWireContext, buffer: JSONHelper.readBuffer(args[0]), }); try { const transactionJSON = transaction.serializeJSON(); const { verifyResult: result } = await node.relayTransaction(transaction, { forceAdd: true }); const resultJSON = result !== undefined && result.verifyResult !== undefined ? toVerifyResultJSON(result.verifyResult) : undefined; return { transaction: transactionJSON, verifyResult: resultJSON, failureMessage: result?.failureReason, }; } catch (error) { throw new JSONRPCError(-110, `Relay transaction failed: ${error.message}`); } }, [RPC_METHODS.getallstorage]: async (args): Promise<readonly StorageItemJSON[]> => { const hash = JSONHelper.readUInt160(args[0]); if (native.nativeHashes.some((natHash) => natHash.equals(hash))) { throw new Error("Can't get all storage for native contracts."); } const contract = await native.ContractManagement.getContract({ storages: blockchain.storages }, hash); if (contract === undefined) { return []; } const buffer = new BinaryWriter().writeInt32LE(contract.id).toBuffer(); return blockchain.storages .find$(buffer) .pipe( map(({ key, value }) => value.serializeJSON(key)), toArray(), ) .toPromise(); }, [RPC_METHODS.gettransactionreceipt]: async (args): Promise<TransactionReceiptJSON | undefined> => { const hash = JSONHelper.readUInt256(args[0]); const transactionData = await blockchain.transactionData.tryGet({ hash }); let watchTimeoutMS; if (args[1] !== undefined && typeof args[1] === 'number') { // eslint-disable-next-line watchTimeoutMS = args[1]; } let result; if (transactionData === undefined) { if (watchTimeoutMS === undefined) { throw new JSONRPCError(-100, 'Unknown transaction'); } try { result = await blockchain.block$ .pipe( switchMap(async () => { const data = await blockchain.transactionData.tryGet({ hash }); return data === undefined ? undefined : getTransactionReceiptJSON(data); }), filter((receipt) => receipt !== undefined), take(1), timeout(new Date(Date.now() + watchTimeoutMS)), ) .toPromise(); } catch { throw new JSONRPCError(-100, 'Unknown transaction'); } } else { result = getTransactionReceiptJSON(transactionData); } return result; }, [RPC_METHODS.gettransactiondata]: async (args): Promise<TransactionDataJSON> => { const state = await blockchain.getTransaction(JSONHelper.readUInt256(args[0])); if (state === undefined) { throw new JSONRPCError(-100, 'Unknown transaction'); } const result = await state.transaction.serializeJSONWithData(blockchain.serializeJSONContext); if (result.transactionData === undefined) { throw new JSONRPCError(-103, 'No transaction data found'); } return result.transactionData; }, [RPC_METHODS.getfailedtransactions]: async (): Promise<{ readonly results: FailedTransactionJSON[]; readonly length: number; }> => { // tslint:disable-next-line: no-array-mutation const results = await blockchain.failedTransactions.all$ .pipe( map((tx) => tx.serializeJSON()), toArray(), ) .toPromise(); const sorted = results.sort((a, b) => { if (a.blockIndex < b.blockIndex) { return -1; } if (a.blockIndex > b.blockIndex) { return 1; } return 0; }); return { results: sorted, length: results.length, }; }, [RPC_METHODS.getnetworksettings]: async (): Promise<NetworkSettingsJSON> => { const { decrementInterval, generationAmount, privateKeyVersion, standbyValidators, network, maxValidUntilBlockIncrement, addressVersion, standbyCommittee, committeeMembersCount, validatorsCount, millisecondsPerBlock, memoryPoolMaxTransactions, maxTraceableBlocks, initialGasDistribution, maxBlockSize, maxBlockSystemFee, maxTransactionsPerBlock, nativeUpdateHistory, } = blockchain.settings; return { blockcount: blockchain.currentBlockIndex + 1, decrementinterval: decrementInterval, generationamount: generationAmount, privatekeyversion: privateKeyVersion, standbyvalidators: standbyValidators.map((val) => common.ecPointToString(val)), network, maxvaliduntilblockincrement: maxValidUntilBlockIncrement, addressversion: addressVersion, standbycommittee: standbyCommittee.map((val) => common.ecPointToString(val)), committeememberscount: committeeMembersCount, validatorscount: validatorsCount, millisecondsperblock: millisecondsPerBlock, memorypoolmaxtransactions: memoryPoolMaxTransactions, maxtraceableblocks: maxTraceableBlocks, initialgasdistribution: initialGasDistribution.toNumber(), maxblocksize: maxBlockSize, maxblocksystemfee: maxBlockSystemFee.toNumber(), maxtransactionsperblock: maxTransactionsPerBlock, nativeupdatehistory: nativeUpdateHistory, }; }, [RPC_METHODS.getfeeperbyte]: async (): Promise<string> => { const feePerByte = await blockchain.getFeePerByte(); return feePerByte.toString(); }, [RPC_METHODS.getexecfeefactor]: async (): Promise<number> => native.Policy.getExecFeeFactor({ storages: blockchain.storages }), [RPC_METHODS.getverificationcost]: async (args): Promise<VerificationCostJSON> => { const hash = JSONHelper.readUInt160(args[0]); const transaction = Transaction.deserializeWire({ context: blockchain.deserializeWireContext, buffer: JSONHelper.readBuffer(args[1]), }); const { fee, size } = await blockchain.getVerificationCost(hash, transaction); return { fee: fee.toString(), size }; }, [RPC_METHODS.runconsensusnow]: async (): Promise<boolean> => { if (node.consensus) { await node.consensus.runConsensusNow(); } else { throw new Error('This node does not support triggering consensus.'); } return true; }, [RPC_METHODS.fastforwardoffset]: async (args): Promise<boolean> => { if (node.consensus) { await node.consensus.fastForwardOffset(args[0]); } else { throw new Error('This node does not support fast forwarding.'); } return true; }, [RPC_METHODS.fastforwardtotime]: async (args): Promise<boolean> => { if (node.consensus !== undefined) { await node.consensus.fastForwardToTime(args[0]); } else { throw new Error('This node does not support fast forwarding.'); } return true; }, [RPC_METHODS.reset]: async (): Promise<boolean> => { if (node.consensus !== undefined) { await node.consensus.pause(); await node.consensus.reset(); } await node.reset(); await blockchain.reset(); if (node.consensus !== undefined) { await node.consensus.resume(); } return true; }, [RPC_METHODS.getneotrackerurl]: async (): Promise<string | undefined> => handleGetNEOTrackerURL(), [RPC_METHODS.resetproject]: async (): Promise<boolean> => { await handleResetProject(); return true; }, }; return createJSONRPCHandler(handlers); };
the_stack
import { Address, Algorithm, Amount, ChainId, Nonce, PubkeyBundle, PubkeyBytes, Token, TokenTicker, } from "@iov/bcp"; import { fromHex } from "@iov/encoding"; import { Erc20Options, Erc20TokensMap } from "./erc20"; import { EthereumConnectionOptions } from "./ethereumconnection"; import { SmartContractTokenType, SmartContractType } from "./smartcontracts/definitions"; export interface Erc20TransferTest { readonly amount: Amount; } export interface EthereumNetworkConfig { readonly env: string; readonly baseHttp: string; readonly baseWs: string; readonly connectionOptions: EthereumConnectionOptions; readonly chainId: ChainId; readonly minHeight: number; readonly mnemonic: string; readonly accountStates: { /** An account with ETH and ERC20 balance */ readonly default: { readonly pubkey: PubkeyBundle; readonly address: Address; /** expected balance for the `address` */ readonly expectedBalance: readonly Amount[]; /** expected nonce for the `address` */ readonly expectedNonce: Nonce; }; /** An account with ERC20 balances but no ETH */ readonly noEth: { readonly address: Address; /** expected balance for the `address` */ readonly expectedBalance: readonly Amount[]; }; /** An account not used on this network */ readonly unused: { readonly pubkey: PubkeyBundle; readonly address: Address; }; }; readonly gasPrice: Amount; readonly gasLimit: string; readonly expectedErrorMessages: { readonly insufficientFunds: RegExp; readonly invalidSignature: RegExp; readonly gasLimitTooLow: RegExp; }; readonly erc20Tokens: Erc20TokensMap; readonly erc20TransferTests: readonly Erc20TransferTest[]; readonly expectedTokens: readonly Token[]; } // Set environment variable ETHEREUM_NETWORK to "local" (default), "ropsten", "rinkeby" const env = process.env.ETHEREUM_NETWORK || "local"; const local: EthereumNetworkConfig = { env: "local", baseHttp: "http://localhost:8545", baseWs: "ws://localhost:8545/ws", connectionOptions: { // Low values to speedup test execution on the local ganache chain (using instant mine) pollInterval: 0.1, // Local scraper not used by default in CI to avoid circular dependency (@iov/ethereum <- scraper <- @iov/ethereum). // Comment out and set the ETHEREUM_SCRAPER environment variable for manual testing. // scraperApiUrl: "http://localhost:8546/api", scraperApiUrl: undefined, atomicSwapEtherContractAddress: "0xE1C9Ea25A621Cf5C934a7E112ECaB640eC7D8d18" as Address, atomicSwapErc20ContractAddress: "0x9768ae2339B48643d710B11dDbDb8A7eDBEa15BC" as Address, customSmartContractConfig: { type: SmartContractType.EscrowSmartContract, address: "0x11BfB4D394cF0dfADEEf269a6852E89C333449b2" as Address, fractionalDigits: 18, tokenType: SmartContractTokenType.ETHER, tokenTicker: "ETH" as TokenTicker, }, }, chainId: "ethereum-eip155-5777" as ChainId, minHeight: 0, // ganache does not auto-generate a genesis block mnemonic: "oxygen fall sure lava energy veteran enroll frown question detail include maximum", accountStates: { default: { pubkey: { algo: Algorithm.Secp256k1, data: fromHex( "041d4c015b00cbd914e280b871d3c6ae2a047ca650d3ecea4b5246bb3036d4d74960b7feb09068164d2b82f1c7df9e95839b29ae38e90d60578b2318a54e108cf8", ) as PubkeyBytes, }, address: "0x0A65766695A712Af41B5cfECAaD217B1a11CB22A" as Address, expectedBalance: [ { tokenTicker: "ASH" as TokenTicker, quantity: "33445566", fractionalDigits: 12, }, { tokenTicker: "ETH" as TokenTicker, quantity: "1234567890987654321", fractionalDigits: 18, }, { tokenTicker: "TRASH" as TokenTicker, quantity: "33445566", fractionalDigits: 9, }, ], expectedNonce: 0 as Nonce, }, noEth: { address: "0x0000000000111111111122222222223333333333" as Address, expectedBalance: [ { tokenTicker: "ASH" as TokenTicker, quantity: "38", fractionalDigits: 12, }, // ETH balance should be listed anyway { tokenTicker: "ETH" as TokenTicker, quantity: "0", fractionalDigits: 18, }, { tokenTicker: "TRASH" as TokenTicker, quantity: "38", fractionalDigits: 9, }, ], }, unused: { pubkey: { algo: Algorithm.Secp256k1, data: fromHex( "049555be4c5136102e1645f9ce53475b2fed172078de78d3b7d0befed14f5471a077123dd459624055c93f85c0d8f99d9178b79b151f597f714ac759bca9dd3cb1", ) as PubkeyBytes, }, address: "0x52dF0e01583E12978B0885C5836c9683f22b0618" as Address, }, }, gasPrice: { quantity: "20000000000", fractionalDigits: 18, tokenTicker: "ETH" as TokenTicker, }, gasLimit: "2100000", expectedErrorMessages: { insufficientFunds: /sender doesn't have enough funds to send tx/i, invalidSignature: /invalid signature/i, gasLimitTooLow: /base fee exceeds gas limit/i, }, erc20Tokens: new Map([ [ "ASH" as TokenTicker, { contractAddress: "0xCb642A87923580b6F7D07D1471F93361196f2650" as Address, decimals: 12, symbol: "ASH", }, ], [ "TRASH" as TokenTicker, { contractAddress: "0xF01231195AE56d38fa03F5F2933863A2606A6052" as Address, decimals: 9, symbol: "TRASH", name: "Trash Token", }, ], ]), erc20TransferTests: [ { amount: { quantity: "3", tokenTicker: "ASH" as TokenTicker, fractionalDigits: 12, }, }, { amount: { quantity: "5678", tokenTicker: "TRASH" as TokenTicker, fractionalDigits: 9, }, }, ], expectedTokens: [ { tokenTicker: "ASH" as TokenTicker, tokenName: "Ash Token", fractionalDigits: 12, }, { tokenTicker: "ETH" as TokenTicker, tokenName: "Ether", fractionalDigits: 18, }, { tokenTicker: "TRASH" as TokenTicker, tokenName: "Trash Token", fractionalDigits: 9, }, ], }; /** Ropsten config is not well maintained and probably outdated. Use at your won risk. */ const ropsten: EthereumNetworkConfig = { env: "ropsten", baseHttp: "https://ropsten.infura.io/", baseWs: "wss://ropsten.infura.io/ws", connectionOptions: { scraperApiUrl: "https://api-ropsten.etherscan.io/api", }, chainId: "ethereum-eip155-3" as ChainId, minHeight: 4284887, mnemonic: "oxygen fall sure lava energy veteran enroll frown question detail include maximum", accountStates: { default: { pubkey: { algo: Algorithm.Secp256k1, data: fromHex( "04965fb72aad79318cd8c8c975cf18fa8bcac0c091605d10e89cd5a9f7cff564b0cb0459a7c22903119f7a42947c32c1cc6a434a86f0e26aad00ca2b2aff6ba381", ) as PubkeyBytes, }, address: "0x88F3b5659075D0E06bB1004BE7b1a7E66F452284" as Address, expectedBalance: [ { tokenTicker: "ETH" as TokenTicker, quantity: "2999979000000000000", fractionalDigits: 18, }, ], expectedNonce: 1 as Nonce, }, noEth: { address: "0x0000000000000000000000000000000000000000" as Address, expectedBalance: [ // ETH balance should be listed anyway { tokenTicker: "ETH" as TokenTicker, quantity: "0", fractionalDigits: 18, }, ], }, unused: { pubkey: { algo: Algorithm.Secp256k1, data: fromHex( "049555be4c5136102e1645f9ce53475b2fed172078de78d3b7d0befed14f5471a077123dd459624055c93f85c0d8f99d9178b79b151f597f714ac759bca9dd3cb1", ) as PubkeyBytes, }, address: "0x52dF0e01583E12978B0885C5836c9683f22b0618" as Address, }, }, gasPrice: { quantity: "1000000000", fractionalDigits: 18, tokenTicker: "ETH" as TokenTicker, }, gasLimit: "141000", expectedErrorMessages: { insufficientFunds: /insufficient funds for gas \* price \+ value/i, invalidSignature: /invalid sender/i, gasLimitTooLow: /intrinsic gas too low/i, }, erc20Tokens: new Map([]), erc20TransferTests: [], expectedTokens: [ { tokenTicker: "ETH" as TokenTicker, tokenName: "Ether", fractionalDigits: 18, }, ], }; const rinkeby: EthereumNetworkConfig = { env: "rinkeby", baseHttp: "https://rinkeby.infura.io", baseWs: "wss://rinkeby.infura.io/ws", connectionOptions: { scraperApiUrl: "https://api-rinkeby.etherscan.io/api", }, chainId: "ethereum-eip155-4" as ChainId, minHeight: 3211058, mnemonic: "retire bench island cushion panther noodle cactus keep danger assault home letter", accountStates: { default: { // Second account (m/44'/60'/0'/0/1) of // "retire bench island cushion panther noodle cactus keep danger assault home letter" pubkey: { algo: Algorithm.Secp256k1, data: fromHex( "045a977cdfa082bd486755a440b1e411a14c690fd9ac0bb6d866070f63911c54af75ae8f0f40c7069ce2df65c6facc45902d462f39e8812421502e0216da7ef51e", ) as PubkeyBytes, }, address: "0x2eF42084759d67CA34aA910DFE22d78bbb66964f" as Address, expectedBalance: [ { tokenTicker: "ETH" as TokenTicker, quantity: "1775182474000000000", fractionalDigits: 18, }, { tokenTicker: "WETH" as TokenTicker, quantity: "1123344550000000000", fractionalDigits: 18, }, ], expectedNonce: 3 as Nonce, }, noEth: { address: "0x2244224422448877887744444444445555555555" as Address, expectedBalance: [ { tokenTicker: "AVO" as TokenTicker, quantity: "7123400000000000000", fractionalDigits: 18, }, // ETH balance should be listed anyway { tokenTicker: "ETH" as TokenTicker, quantity: "0", fractionalDigits: 18, }, { tokenTicker: "WETH" as TokenTicker, quantity: "100000000000000000", fractionalDigits: 18, }, { tokenTicker: "ZEENUS" as TokenTicker, quantity: "5", fractionalDigits: 0, }, ], }, unused: { pubkey: { algo: Algorithm.Secp256k1, data: fromHex( "049555be4c5136102e1645f9ce53475b2fed172078de78d3b7d0befed14f5471a077123dd459624055c93f85c0d8f99d9178b79b151f597f714ac759bca9dd3cb1", ) as PubkeyBytes, }, address: "0x52dF0e01583E12978B0885C5836c9683f22b0618" as Address, }, }, gasPrice: { quantity: "3000000000", // 3 Gwei fractionalDigits: 18, tokenTicker: "ETH" as TokenTicker, }, gasLimit: "141000", expectedErrorMessages: { insufficientFunds: /insufficient funds for gas \* price \+ value/i, invalidSignature: /invalid sender/i, gasLimitTooLow: /intrinsic gas too low/i, }, erc20Tokens: new Map<TokenTicker, Erc20Options>([ [ "WETH" as TokenTicker, { contractAddress: "0xc778417e063141139fce010982780140aa0cd5ab" as Address, decimals: 18, symbol: "WETH", }, ], [ "AVO" as TokenTicker, { contractAddress: "0x0c8184c21a51cdb7df9e5dc415a6a54b3a39c991" as Address, decimals: 18, symbol: "AVO", }, ], [ // from https://ethereum.stackexchange.com/a/68072 "ZEENUS" as TokenTicker, { contractAddress: "0x1f9061B953bBa0E36BF50F21876132DcF276fC6e" as Address, decimals: 0, symbol: "ZEENUS", }, ], ]), erc20TransferTests: [ { amount: { quantity: "123", tokenTicker: "AVO" as TokenTicker, fractionalDigits: 18, }, }, { amount: { quantity: "456", tokenTicker: "WETH" as TokenTicker, fractionalDigits: 18, }, }, { amount: { tokenTicker: "ZEENUS" as TokenTicker, quantity: "1", fractionalDigits: 0, }, }, ], expectedTokens: [ { tokenTicker: "AVO" as TokenTicker, tokenName: "Avocado", fractionalDigits: 18, }, { tokenTicker: "ETH" as TokenTicker, tokenName: "Ether", fractionalDigits: 18, }, { tokenTicker: "WETH" as TokenTicker, tokenName: "Wrapped Ether", fractionalDigits: 18, }, { tokenTicker: "ZEENUS" as TokenTicker, tokenName: "Zeenus 💪", fractionalDigits: 0, }, ], }; const config = new Map<string, EthereumNetworkConfig>(); config.set("local", local); config.set("ropsten", ropsten); config.set("rinkeby", rinkeby); export const testConfig = config.get(env)!;
the_stack
import * as React from 'react'; import Toolbar from 'react-md/lib/Toolbars'; import Button from 'react-md/lib/Buttons/Button'; import CircularProgress from 'react-md/lib/Progress/CircularProgress'; import { Card, CardTitle, CardActions, CardText } from 'react-md/lib/Cards'; import Media, { MediaOverlay } from 'react-md/lib/Media'; import Dialog from 'react-md/lib/Dialogs'; import TextField from 'react-md/lib/TextFields'; import FileUpload from 'react-md/lib/FileInputs/FileUpload'; import { Link } from 'react-router'; import SetupActions from '../../actions/SetupActions'; import SetupStore from '../../stores/SetupStore'; import ConfigurationStore from '../../stores/ConfigurationsStore'; import ConfigurationsActions from '../../actions/ConfigurationsActions'; import utils from '../../utils'; import IconPicker from './IconPicker'; import { downloadBlob } from '../Dashboard/DownloadFile'; const renderHTML = require('react-render-html'); const MultipleSpacesRegex = / +/g; const styles = { card: { width: 380, height: 280, marginBottom: 20 } as React.CSSProperties, media: { width: 380, height: 150, background: '#CCC', margin: 0, padding: 0 } as React.CSSProperties, preview: { width: 380, height: 150, backgroundRepeat: 'no-repeat', backgroundPosition: '50% 50%', backgroundSize: 'contain' } as React.CSSProperties, actions: { position: 'absolute', bottom: 0 } as React.CSSProperties }; interface IHomeState extends ISetupConfig { loaded?: boolean; errors?: any; templates?: IDashboardConfig[]; selectedTemplateId?: string; template?: IDashboardConfig; creationState?: string; infoVisible?: boolean; infoHtml?: string; importVisible?: boolean; importedFileContent?: any; fileName?: string; content?: string; infoTitle?: string; } export default class Home extends React.Component<any, IHomeState> { state: IHomeState = { admins: null, stage: 'none', enableAuthentication: false, allowHttp: false, redirectUrl: '', clientID: '', clientSecret: '', issuer: '', loaded: false, errors: null, templates: [], selectedTemplateId: null, template: null, creationState: null, infoVisible: false, infoHtml: '', infoTitle: '' }; private _fieldId; private _fieldName; private _fieldIcon; constructor(props: any) { super(props); this.onNewTemplateSelected = this.onNewTemplateSelected.bind(this); this.onNewTemplateCancel = this.onNewTemplateCancel.bind(this); this.onNewTemplateSave = this.onNewTemplateSave.bind(this); this.onOpenInfo = this.onOpenInfo.bind(this); this.onCloseInfo = this.onCloseInfo.bind(this); this.updateSetup = this.updateSetup.bind(this); this.updateConfiguration = this.updateConfiguration.bind(this); // import dashboard functionality this.onOpenImport = this.onOpenImport.bind(this); this.onCloseImport = this.onCloseImport.bind(this); this.onSubmitImport = this.onSubmitImport.bind(this); this.onLoad = this.onLoad.bind(this); this.setFile = this.setFile.bind(this); this.updateFileName = this.updateFileName.bind(this); this.onExportTemplate = this.onExportTemplate.bind(this); this.downloadTemplate = this.downloadTemplate.bind(this); this.onOpenImport = this.onOpenImport.bind(this); } updateConfiguration(state: { templates: IDashboardConfig[], template: IDashboardConfig, creationState: string, errors: any }) { this.setState({ templates: state.templates || [], template: state.template, creationState: state.creationState, errors: state.errors, }); if (this.state.stage === 'requestDownloadTemplate') { this.downloadTemplate(this.state.template); } } updateSetup(state: IHomeState) { this.setState(state); // Setup hasn't been configured yet if (state.stage === 'none') { window.location.replace('/setup'); } } componentDidMount() { this.setState(SetupStore.getState()); this.updateConfiguration(ConfigurationStore.getState()); SetupActions.load(); SetupStore.listen(this.updateSetup); ConfigurationStore.listen(this.updateConfiguration); } componentWillUnmount() { SetupStore.unlisten(this.updateSetup); ConfigurationStore.unlisten(this.updateConfiguration); } componentDidUpdate() { if (this.state.creationState === 'successful') { window.location.replace('/dashboard/' + this._fieldId.getField().value); } } onNewTemplateSelected(templateId: string) { this.setState({ selectedTemplateId: templateId }); ConfigurationsActions.loadTemplate(templateId); } onNewTemplateCancel() { this.setState({ selectedTemplateId: null }); } deepObjectExtend(target: any, source: any) { for (var prop in source) { if (prop in target) { this.deepObjectExtend(target[prop], source[prop]); } else { target[prop] = source[prop]; } } return target; } onNewTemplateSave() { let createParams = { id: this._fieldId.getField().value, name: this._fieldName.getField().value, icon: this._fieldIcon.getIcon(), url: this._fieldId.getField().value }; var dashboard: IDashboardConfig = this.deepObjectExtend({}, this.state.template); dashboard.id = createParams.id; dashboard.name = createParams.name; dashboard.icon = createParams.icon; dashboard.url = createParams.url; ConfigurationsActions.createDashboard(dashboard); } onOpenInfo(html: string, title: string) { this.setState({ infoVisible: true, infoHtml: html, infoTitle: title }); } onCloseInfo() { this.setState({ infoVisible: false }); } onOpenImport() { this.setState({ importVisible: true }); } onCloseImport() { this.setState({ importVisible: false }); } updateFileName(value: string) { this.setState({ fileName: value }); } onLoad(importedFileContent: any, uploadResult: string) { const { name, size, type, lastModifiedDate } = importedFileContent; this.setState({ fileName: name.substr(0, name.indexOf('.')), content: uploadResult }); } onSubmitImport() { var dashboardId = this.state.fileName; ConfigurationsActions.submitDashboardFile(this.state.content, dashboardId); this.setState({ importVisible: false }); } setFile(importedFileContent: string) { this.setState({ importedFileContent }); } onExportTemplate(templateId: string) { this.setState({ stage: 'requestDownloadTemplate' }); ConfigurationsActions.loadTemplate(templateId); } downloadTemplate(template: IDashboardConfig) { template.layouts = template.layouts || {}; let stringDashboard = utils.convertDashboardToString(template); var dashboardName = template.id.replace(MultipleSpacesRegex, ' '); dashboardName = template.id.replace(MultipleSpacesRegex, '_'); downloadBlob('return ' + stringDashboard, 'application/json', dashboardName + '.private.ts'); } render() { let { errors, loaded, redirectUrl, templates, selectedTemplateId, template } = this.state; let { importVisible } = this.state; let { importedFileContent, fileName } = this.state; let { infoVisible, infoHtml, infoTitle } = this.state; if (!redirectUrl) { redirectUrl = window.location.protocol + '//' + window.location.host + '/auth/openid/return'; } if (!loaded) { return <CircularProgress key="progress" id="contentLoadingProgress" />; } if (!templates) { return null; } // Create dashboard form validation let error = false; let errorText = null; if (errors && errors.error && errors.type && errors.type === 'id') { errorText = errors.error; error = true; } let createCard = (tmpl, index) => ( <Card key={index} className="templates md-cell" style={styles.card}> <Media style={styles.media}> <div className="preview" style={{ ...styles.preview, backgroundImage: `url(${tmpl.preview})` }} /> </Media> <CardTitle title={tmpl.name} subtitle={tmpl.description} /> <CardActions style={styles.actions}> <Button label="Download" tooltipLabel="Download template" flat onClick={this.onExportTemplate.bind(this, tmpl.id)} > file_download </Button> <Button label="Info" tooltipLabel="Show info" flat onClick={this.onOpenInfo.bind(this, tmpl.html || '<p>No info available</p>', tmpl.name)} > info </Button> <Button label="Create" tooltipLabel="Create dashboard" flat primary onClick={this.onNewTemplateSelected.bind(this, tmpl.id)} > add_circle_outline </Button> </CardActions> </Card> ); // Dividing templates into categories // General - All dashboards without any categories // Features - Dashboards appearing at the top of the creation screen let categories = { 'General': [], 'Featured': [] }; templates.forEach((tmpl, index) => { let category = tmpl.category || 'General'; if (tmpl.featured) { categories['Featured'].push(createCard(tmpl, index)); } categories[category] = categories[category] || []; categories[category].push(createCard(tmpl, index)); }); // Sort templates alphabetically let sortedCategories = { 'General': categories.General, 'Featured': categories.Featured }; const keys = Object.keys(categories).filter(category => category !== 'Featured').sort(); keys.forEach(key => sortedCategories[key] = categories[key]); categories = sortedCategories; let toolbarActions = []; toolbarActions.push( ( <Button flat tooltipLabel="Import dashboard" onClick={this.onOpenImport} label="Import dashboard" >file_upload </Button> ) ); return ( <div className="md-cell md-cell--12"> <Toolbar actions={toolbarActions} /> { Object.keys(categories).map((category, index) => { if (!categories[category].length) { return null; } return ( <div key={index}> <h1>{category}</h1> <div className="md-grid"> {categories[category]} </div> </div> ); }) } <Dialog id="ImportDashboard" visible={importVisible || false} title="Import dashboard" modal actions={[ { onClick: this.onCloseImport, primary: false, label: 'Cancel' }, { onClick: this.onSubmitImport, primary: true, label: 'Submit', disabled: !importedFileContent }, ]}> <FileUpload id="dashboardDefenitionFile" primary label="Choose File" accept="application/javascript" onLoadStart={this.setFile} onLoad={this.onLoad} /> <TextField id="dashboardFileName" label="Dashboard ID" value={fileName || ''} onChange={this.updateFileName} disabled={!importedFileContent} lineDirection="center" placeholder="Choose an ID for the imported dashboard" /> </Dialog> <Dialog id="templateInfoDialog" title={infoTitle} visible={infoVisible || false} onHide={this.onCloseInfo} dialogStyle={{ width: '80%' }} contentStyle={{ padding: '0', maxHeight: 'calc(100vh - 148px)' }} aria-label="Info" focusOnMount={false} > <div className="md-grid" style={{ padding: 20 }}> {renderHTML(infoHtml)} </div> </Dialog> <Dialog id="configNewDashboard" visible={selectedTemplateId !== null && template !== null} title="Configure the new dashboard" aria-labelledby="configNewDashboardDescription" dialogStyle={{ width: '50%' }} modal actions={[ { onClick: this.onNewTemplateCancel, primary: false, label: 'Cancel' }, { onClick: this.onNewTemplateSave, primary: true, label: 'Create', }, ]} > <IconPicker ref={field => this._fieldIcon = field} defaultLabel="Dashboard Icon" defaultIcon={template && template.icon || 'dashboard'} listStyle={{height: '136px'}} /> <TextField id="id" ref={field => this._fieldId = field} label="Dashboard Id" defaultValue={template && template.id || ''} lineDirection="center" placeholder="Choose an ID for the dashboard (will be used in the url)" error={error} errorText={errorText} /> <TextField id="name" ref={field => this._fieldName = field} label="Dashboard Name" defaultValue={template && template.name || ''} lineDirection="center" placeholder="Choose name for the dashboard (will be used in navigation)" /> </Dialog> </div> ); } }
the_stack
import { getParentBg, getParentFg, isContrasty, isTransparent, setContrastRatio, toRGB } from './lib/color'; import { INPUT_NODES, INPUT_PERMS, isDontRecurseNode, isInputNode, isInVisibleNode, isSubDocNode } from './lib/checks'; import { clearOverrides } from './lib/contrast'; declare function requestIdleCallback(callback: (idleDeadline: { didTimeout: boolean; timeRemaining: () => number; }) => any, options?: { timeout: number }): number; let DEFAULTS: { [key: string]: { fg: string, bg: string } } = {}; let topElementFixed = false; const getDefaultColors = () => { let probe_frame = document.createElementNS('http://www.w3.org/1999/xhtml', 'iframe') as HTMLIFrameElement; // probe_frame.src = 'about:blank'; probe_frame.style.width = '0'; probe_frame.style.height = '0'; document.documentElement.appendChild(probe_frame); let frame_doc = probe_frame.contentWindow!.document; // Get default style for general elements let par = frame_doc.createElement('p'); par.style.color = "initial"; par.style.backgroundColor = "initial"; frame_doc.body.appendChild(par); DEFAULTS['html'] = { fg: getComputedStyle(par).getPropertyValue('color'), bg: getComputedStyle(par).getPropertyValue('background-color') }; // Get default browser style, which should be the final non-transparent color frame_doc.body.style.color = '-moz-default-color'; frame_doc.body.style.backgroundColor = '-moz-default-background-color'; DEFAULTS['browser'] = { fg: getComputedStyle(frame_doc.body).getPropertyValue('color'), bg: getComputedStyle(frame_doc.body).getPropertyValue('background-color') }; // Get colors for input nodes for (const ip of INPUT_PERMS) { let probe = frame_doc.createElement(ip.nodeName); if (ip.props) { for (const key in ip.props) { (probe as any)[key] = ip.props[key]; } } frame_doc.body.appendChild(probe); DEFAULTS[ip.cssSelector] = { fg: getComputedStyle(probe).getPropertyValue('color'), bg: getComputedStyle(probe).getPropertyValue('background-color') } } document.documentElement.removeChild(probe_frame); } const getDefaultsForElement = (el: HTMLElement) => { for (const { cssSelector } of INPUT_PERMS) { if (el.matches(cssSelector)) { return DEFAULTS[cssSelector]; } } return DEFAULTS['html']; } const checkElement = (el: HTMLElement | null, { recurse }: { recurse?: boolean } = { recurse: false }): void => { if (!el) { return; } // If element has already been examined before, don't do any processing if ('_extensionTextContrast' in el.dataset) { return; } // Grab current and default styles const compStyle = getComputedStyle(el); let fg = compStyle.getPropertyValue('color'); let bg = compStyle.getPropertyValue('background-color'); let fg_default; let bg_default; if (INPUT_NODES.indexOf(el.nodeName) !== -1) { const def = getDefaultsForElement(el); fg_default = def.fg; bg_default = def.bg; } else { fg_default = DEFAULTS['html'].fg; bg_default = DEFAULTS['html'].bg; } // Check which styles have been overriden by site author const fgClrDefined = fg !== fg_default; const bgClrDefined = bg !== bg_default; const bgImgDefined = compStyle.getPropertyValue('background-image') !== 'none'; // Normalize styles (which could be something like 'transparent') to true rgba // values. let fg_rgba = toRGB(fg); let bg_rgba = toRGB(bg); let bg_fallback = true; // If color is transparent, recurse through all the parents to find a // non-transparent color to assume as the current color if (isTransparent(fg_rgba)) { let clr = getParentFg(el); fg_rgba = clr === null ? toRGB(DEFAULTS['browser'].fg) : clr; } if (isTransparent(bg_rgba)) { let clr = getParentBg(el); bg_rgba = clr === null ? toRGB(DEFAULTS['browser'].bg) : clr; // Remember if we had to use a fallback color here for later use bg_fallback = clr === null; } if (fgClrDefined && bgClrDefined) { // Both colors explicitly defined, nothing to do el.dataset._extensionTextContrast = ''; stdEmbeds(el); return; } else if (!fgClrDefined && bgClrDefined) { // Note that if background image exists, it may be transparent, so we // can't afford to skip setting the color if (!isContrasty(fg_rgba, bg_rgba) || bgImgDefined) { el.dataset._extensionTextContrast = 'fg'; stdEmbeds(el); return; } } else if (fgClrDefined && !bgClrDefined) { if (!isContrasty(fg_rgba, bg_rgba)) { el.dataset._extensionTextContrast = 'bg'; stdEmbeds(el); return; } } else if (bgImgDefined) { if (bg_fallback || !isContrasty(fg_rgba, bg_rgba) || isInputNode(el)) { // The image may or may not be transparent, and we can't really tell. If // the fallback background color was set above, then the author has never // defined a background color of their own, and so we should force a fix. // If the author has set the background before, the image may have // transparency effects that are relied on, so we only do the fix if // contrast is bad. Input elements don't really inherit correctly, so we // always apply the fix for those. el.dataset._extensionTextContrast = 'both'; } else { // Otherwise, the FG needs to at least be set since we don't know about // the background image state. el.dataset._extensionTextContrast = 'fg'; } stdEmbeds(el); return; } // If here, then either no colors were defined, or those that were still have // contrast. Need to continue checking child elements to ensure contrast is OK if (recurse === true && !isDontRecurseNode(el)) { const { children } = el; const len = children.length; for (let i = 0; i < len; i += 1) { // Don't look at non-renderable elements if (!isInVisibleNode(el.children[i])) { checkElement(el.children[i] as HTMLElement, { recurse }); } } } }; const checkInputs = (root = document.documentElement) => { if (!root) { return; } // Check all input elements const nodeIterator = document.createNodeIterator( root, NodeFilter.SHOW_ELEMENT, { acceptNode: (el: HTMLElement) => isInputNode(el) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT }, ); // Can't use for-of loop because a NodeIterator is not iteratable. // Thanks Javascript! let node = null; while ((node = nodeIterator.nextNode()) != null) { checkElement(node as HTMLElement); } }; const checkAll = () => { // Recursively check the document checkElement(document.documentElement, { recurse: true }); // Check input after checkInputs(); }; const checkParents = (el: HTMLElement, { recurse }: { recurse: boolean }) => { let parent = el.parentElement; if (topElementFixed) { // Still have to fix subdocs since style has been explicitly defined by us. stdEmbeds(el); return; } while (parent !== null) { if ('_extensionTextContrast' in parent.dataset) { // If any parents' were already handled, // new elements don't need recolor. if (parent === document.documentElement || parent === document.body) { // Style is already defined in top level document or body element, so all child elements (except for inputs) // will be ok. We can avoid this check for all subsequent element additions or changes. topElementFixed = true; } // Still have to fix subdocs since style has been explicitly defined by us. stdEmbeds(el); return; } parent = parent.parentElement; } checkElement(el, { recurse }); }; const stdEmbeds = (e: HTMLElement) => { const nodeIterator = document.createNodeIterator( e, NodeFilter.SHOW_ELEMENT, { acceptNode: (el: Element) => isSubDocNode(el) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT, }); // Can't use for-in loop because a NodeIterator is not an iterator. Thanks // Javascript. let node: Node | null = null; // eslint-disable-line init-declarations while ((node = nodeIterator.nextNode()) != null) { (node as HTMLElement).dataset._extensionTextContrastFF = ''; if ((node as HTMLIFrameElement).contentWindow !== null) { (node as HTMLIFrameElement).contentWindow!.postMessage('_tcfdt_subdoc_std', '*'); } } }; browser.storage.local.get({ 'tcfdt-cr': 4.5 }).then((items) => { getDefaultColors(); setContrastRatio(items['tcfdt-cr']); checkAll(); const dataObserver = new MutationObserver((mutations, observer) => { mutations.forEach((mutation) => { if (mutation.oldValue !== null) { // Something in the author JS has erased the previous attribute, so // restore it. // Disable ourselves, otherwise this enters infinite loop observer.disconnect(); const element = mutation.target as HTMLElement; element.dataset._extensionTextContrast = mutation.oldValue; // Restore observer now that we are done observer.observe(document.body, { attributes: true, attributeFilter: ['data-_extension-text-contrast'], subtree: true, attributeOldValue: true, }); } }); }); const observer = new MutationObserver((mutations) => { const mutLen = mutations.length; for (let i = 0; i < mutLen; i += 1) { if (mutations[i].type === 'attributes') { // This mutation represents a change to class or style of element // so this element also needs re-checking const changedNode = mutations[i].target; // Recurse here, as changed style may have effects farther down the tree requestIdleCallback(() => { checkParents(changedNode as HTMLElement, {recurse: true}); }); if (isInputNode(changedNode as HTMLElement)) { requestIdleCallback(() => { checkElement(changedNode as HTMLElement); }); } } else if (mutations[i].type === 'childList') { const addLen = mutations[i].addedNodes.length; for (let j = 0; j < addLen; j += 1) { const newNode = mutations[i].addedNodes[j]; if (!isInVisibleNode(newNode)) { requestIdleCallback(() => { // Don't recurse here, as added nodes are probably all considered here (unsure) checkParents(newNode as HTMLElement, {recurse: false}); }); } } } } }); observer.observe(document, { attributes: true, attributeFilter: ['class', 'style'], childList: true, subtree: true, }); dataObserver.observe(document.body, { attributes: true, attributeFilter: ['data-_extension-text-contrast'], subtree: true, attributeOldValue: true, }); browser.runtime.onMessage.addListener((message: {}) => { const request = (message as { request: 'off' }).request; if (request === 'off') { dataObserver.disconnect(); observer.disconnect(); clearOverrides(document); } }); window.addEventListener('message', (e) => { if (e.data === '_tcfdt_checkme') { // check all parents to see if extension has made any fixes // const src_win = ; try { let elem: HTMLElement | null = (e.source as Window).frameElement as HTMLElement; if ('_extensionTextContrastFF' in elem.dataset) { (e.source as Window).postMessage('_tcfdt_subdoc_std', '*'); } } catch { // Likely failed due to cross-origin issues. Have no way of determining which frame element requested the check. // Only remaining option is to re-send directive for fixing to all frames that need it. Super-awkward and // flicker-y, but it works. if (!document.documentElement) { e.stopPropagation(); return; } const nodeIterator = document.createNodeIterator( document.documentElement, NodeFilter.SHOW_ELEMENT, { acceptNode: (el: HTMLElement) => '_extensionTextContrastFF' in el.dataset ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT, }, ); let node = null; while ((node = nodeIterator.nextNode()) !== null) { (node as HTMLIFrameElement).contentWindow!.postMessage('_tcfdt_subdoc_std', '*'); } } e.stopPropagation(); } }, true); if (window.self !== window.top && (!('tcfdtFrameFixed' in window) || !(window as any).tcfdtFrameFixed)) { window.parent.postMessage('_tcfdt_checkme', '*'); } });
the_stack
import React, { useState } from 'react'; import { mount } from 'enzyme'; import ModalCurtain from './index'; const ESC_KEY = 27; const ENTER_KEY = 13; const BACKSPACE_KEY = 8; const SPACE_KEY = 32; const LOWERCASE_A_KEY = 65; describe('ModalCurtain', () => { test('renders a basic curtain', () => { const wrapper = mount(<ModalCurtain onCloseClick={jest.fn} />); expect(wrapper).toMatchSnapshot(); }); test('renders modal in `exited` stage', () => { const wrapper = mount(<ModalCurtain stage="exited" onCloseClick={jest.fn} />); expect(wrapper).toMatchSnapshot(); }); test('renders modal in `entering` stage', () => { const wrapper = mount(<ModalCurtain stage="entering" onCloseClick={jest.fn} />); expect(wrapper).toMatchSnapshot(); }); test('renders modal in `entered` stage', () => { const wrapper = mount(<ModalCurtain stage="entered" onCloseClick={jest.fn} />); expect(wrapper).toMatchSnapshot(); }); test('renders modal in `exiting` stage', () => { const wrapper = mount(<ModalCurtain stage="exiting" onCloseClick={jest.fn} />); expect(wrapper).toMatchSnapshot(); }); test('renders `accessibilityLabel`', () => { const wrapper = mount( <ModalCurtain accessibilityLabel="goosegoosegoose" onCloseClick={jest.fn} />, ); expect(wrapper.html()).toContain('goosegoosegoose'); expect(wrapper).toMatchSnapshot(); }); test('`children` receives `curtainOnClick` and `curtainClassName`', () => { let obj: { curtainOnClick?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void; curtainClassName?: string; } = {}; mount( <ModalCurtain onCloseClick={jest.fn}> {(args): JSX.Element => { obj = args; return <div />; }} </ModalCurtain>, ); expect(obj.curtainOnClick).toBeTruthy(); expect(obj.curtainClassName).toBeTruthy(); }); test("`children`'s `curtainOnClick` render prop calls `onCloseClick` prop when executed", () => { const onClick = jest.fn(); const wrapper = mount( <ModalCurtain onCloseClick={onClick}> {({ curtainOnClick }): JSX.Element => ( <button data-test-id="goose" onClick={curtainOnClick} type="button" /> )} </ModalCurtain>, ); expect(onClick).toHaveBeenCalledTimes(0); wrapper.find('button[data-test-id="goose"]').simulate('click'); expect(onClick).toHaveBeenCalledTimes(1); }); test('renders text that is passed in', () => { const wrapper = mount( <div> <button type="button" /> <ModalCurtain onCloseClick={jest.fn}> {(): JSX.Element => <div>Goose</div>} </ModalCurtain> </div>, ); expect(wrapper.find('ModalCurtain').text()).toEqual('Goose'); expect(wrapper).toMatchSnapshot(); }); test('initially traps focus to the root dialog node', () => { jest.useFakeTimers(); const onCloseClick = jest.fn(); const wrapper = mount( <ModalCurtain stage="entered" onCloseClick={onCloseClick}> {(): JSX.Element => ( <> <button type="button" /> </> )} </ModalCurtain>, ); // Run setTimeouts() in focus-trap to completion jest.runAllTimers(); const modalWrapper = wrapper.find('[role="dialog"]'); expect(modalWrapper.is(':focus')).toBe(true); jest.useRealTimers(); }); test('initially focuses `initialFocus` element if provided', () => { jest.useFakeTimers(); const onCloseClick = jest.fn(); const Example = (): React.ReactElement => { const [inputRef, setInputRef] = useState<HTMLInputElement | null>(null); return ( <ModalCurtain stage="entered" onCloseClick={onCloseClick} initialFocus={inputRef}> {(): JSX.Element => ( <div> <button type="button" data-testid="button" /> <input ref={(r): void => { setInputRef(r); }} data-testid="input" /> </div> )} </ModalCurtain> ); }; const wrapper = mount(<Example />); // Run setTimeouts() in focus-trap to completion jest.runAllTimers(); // We don't want focus to be on the outside wrapper. const modalWrapper = wrapper.find('[role="dialog"]'); expect(modalWrapper.is(':focus')).toBe(false); const button = wrapper.find('[data-testid="button"]'); const input = wrapper.find('[data-testid="input"]'); expect(button.is(':focus')).toBe(false); expect(input.is(':focus')).toBe(true); jest.useRealTimers(); }); test('`onCloseClick` is not called when non-ESC keys are pressed', () => { const onCloseClick = jest.fn(); mount(<ModalCurtain stage="entered" onCloseClick={onCloseClick} shouldCloseOnEscape />); expect(onCloseClick).toHaveBeenCalledTimes(0); // NOTE: it seems that Enzyme does not respond to the standard properties on // `KeyboardEventInit`, either `code: 'Escape'` or `key: 'Escape'`. It only responds to // the deprecated property `keyCode`, which is not in the type defintion. As such we // have to cast the type here to prevent an error. document.dispatchEvent( new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', keyCode: ENTER_KEY, } as KeyboardEventInit), ); document.dispatchEvent( new KeyboardEvent('keyup', { key: 'Backspace', code: 'Backspace', keyCode: BACKSPACE_KEY, } as KeyboardEventInit), ); document.dispatchEvent( new KeyboardEvent('keyup', { key: 'Space', code: 'Space', keyCode: SPACE_KEY, } as KeyboardEventInit), ); document.dispatchEvent( new KeyboardEvent('keyup', { key: 'a', code: 'a', keyCode: LOWERCASE_A_KEY, } as KeyboardEventInit), ); expect(onCloseClick).toHaveBeenCalledTimes(0); }); describe('closes modal on `ESC`', () => { test('when modal is open and `shouldCloseOnEscape` is `true`', () => { const onCloseClick = jest.fn(); mount(<ModalCurtain stage="entered" onCloseClick={onCloseClick} shouldCloseOnEscape />); expect(onCloseClick).toHaveBeenCalledTimes(0); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); }); test('when modal is open and `shouldCloseOnEscape` are `true`, become closed and `false`, then become open and `true` again', () => { const onCloseClick = jest.fn(); const wrapper = mount( <ModalCurtain stage="entered" onCloseClick={onCloseClick} shouldCloseOnEscape />, ); expect(onCloseClick).toHaveBeenCalledTimes(0); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); wrapper.setProps({ shouldCloseOnEscape: false, stage: 'exited' }); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); wrapper.setProps({ shouldCloseOnEscape: true, stage: 'exited' }); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); wrapper.setProps({ shouldCloseOnEscape: false, stage: 'entered' }); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); // Both are now true, so the event listener should be reactiviated. wrapper.setProps({ shouldCloseOnEscape: true, stage: 'entered' }); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(2); }); }); describe('does not close modal on `ESC`', () => { test('when modal is closed and `shouldCloseOnEscape` is `true`', () => { const onCloseClick = jest.fn(); mount(<ModalCurtain stage="exited" onCloseClick={onCloseClick} shouldCloseOnEscape />); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(0); }); test('when modal is closed and `shouldCloseOnEscape` is `false`', () => { const onCloseClick = jest.fn(); mount( <ModalCurtain stage="exited" onCloseClick={onCloseClick} shouldCloseOnEscape={false} />, ); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(0); }); test('when modal is open and `shouldCloseOnEscape` is `false`', () => { const onCloseClick = jest.fn(); mount( <ModalCurtain stage="entered" onCloseClick={onCloseClick} shouldCloseOnEscape={false} />, ); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(0); }); test('when modal is open then changes to closed', () => { const onCloseClick = jest.fn(); const wrapper = mount( <ModalCurtain stage="entered" onCloseClick={onCloseClick} shouldCloseOnEscape />, ); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); wrapper.setProps({ stage: 'exited' }); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); }); test('when `shouldCloseOnEscape` changes to `false` while mounted', () => { const onCloseClick = jest.fn(); const wrapper = mount( <ModalCurtain stage="entered" onCloseClick={onCloseClick} shouldCloseOnEscape />, ); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); wrapper.setProps({ shouldCloseOnEscape: false }); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); }); test('when `shouldCloseOnEscape` changes to `false` and the modal close while mounted', () => { const onCloseClick = jest.fn(); const wrapper = mount( <ModalCurtain stage="entered" onCloseClick={onCloseClick} shouldCloseOnEscape />, ); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); wrapper.setProps({ shouldCloseOnEscape: false, stage: 'exited' }); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); }); test('when component is unmounted', () => { const onCloseClick = jest.fn(); const wrapper = mount( <ModalCurtain stage="entered" onCloseClick={onCloseClick} shouldCloseOnEscape />, ); const event = new KeyboardEvent('keyup', { key: 'Escape', code: 'Escape', keyCode: ESC_KEY, } as KeyboardEventInit); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); wrapper.unmount(); document.dispatchEvent(event); expect(onCloseClick).toHaveBeenCalledTimes(1); }); }); });
the_stack
import { Component, SimpleChange, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { AppConfigService, DataRowEvent, ObjectDataRow, setupTestBed } from '@alfresco/adf-core'; import { ProcessListCloudService } from '../services/process-list-cloud.service'; import { ProcessListCloudComponent } from './process-list-cloud.component'; import { fakeCustomSchema, fakeProcessCloudList, processListSchemaMock } from '../mock/process-list-service.mock'; import { of } from 'rxjs'; import { skip } from 'rxjs/operators'; import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module'; import { TranslateModule } from '@ngx-translate/core'; import { ProcessListCloudSortingModel } from '../models/process-list-sorting.model'; @Component({ template: ` <adf-cloud-process-list #processListCloud> <data-columns> <data-column key="name" title="ADF_CLOUD_TASK_LIST.PROPERTIES.NAME" class="adf-full-width adf-name-column"></data-column> <data-column key="created" title="ADF_CLOUD_TASK_LIST.PROPERTIES.CREATED" class="adf-hidden"></data-column> <data-column key="startedBy" title="ADF_CLOUD_TASK_LIST.PROPERTIES.CREATED" class="adf-desktop-only dw-dt-col-3 adf-ellipsis-cell"> <ng-template let-entry="$implicit"> <div>{{getFullName(entry.row.obj.startedBy)}}</div> </ng-template> </data-column> </data-columns> </adf-cloud-process-list>` }) class CustomTaskListComponent { @ViewChild(ProcessListCloudComponent) processListCloud: ProcessListCloudComponent; } @Component({ template: ` <adf-cloud-process-list> <adf-custom-empty-content-template> <p id="custom-id">TEST</p> </adf-custom-empty-content-template> </adf-cloud-process-list> ` }) class EmptyTemplateComponent { } describe('ProcessListCloudComponent', () => { let component: ProcessListCloudComponent; let fixture: ComponentFixture<ProcessListCloudComponent>; let appConfig: AppConfigService; let processListCloudService: ProcessListCloudService; setupTestBed({ imports: [ TranslateModule.forRoot(), ProcessServiceCloudTestingModule ] }); beforeEach(() => { appConfig = TestBed.inject(AppConfigService); processListCloudService = TestBed.inject(ProcessListCloudService); fixture = TestBed.createComponent(ProcessListCloudComponent); component = fixture.componentInstance; appConfig.config = Object.assign(appConfig.config, { 'adf-cloud-process-list': { 'presets': { 'fakeCustomSchema': [ { 'key': 'fakeName', 'type': 'text', 'title': 'ADF_CLOUD_TASK_LIST.PROPERTIES.FAKE', 'sortable': true }, { 'key': 'fakeTaskName', 'type': 'text', 'title': 'ADF_CLOUD_TASK_LIST.PROPERTIES.TASK_FAKE', 'sortable': true } ] } } }); }); afterEach(() => fixture.destroy()); it('should use the default schemaColumn', () => { appConfig.config = Object.assign(appConfig.config, { 'adf-cloud-process-list': processListSchemaMock }); component.ngAfterContentInit(); fixture.detectChanges(); expect(component.columns).toBeDefined(); expect(component.columns.length).toEqual(10); }); it('should display empty content when process list is empty', () => { const emptyList = {list: {entries: []}}; spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(emptyList)); fixture.detectChanges(); expect(component.isLoading).toBe(true); let loadingContent = fixture.debugElement.query(By.css('mat-progress-spinner')); expect(loadingContent.nativeElement).toBeDefined(); const appName = new SimpleChange(null, 'FAKE-APP-NAME', true); component.ngOnChanges({ appName }); fixture.detectChanges(); loadingContent = fixture.debugElement.query(By.css('mat-progress-spinner')); expect(loadingContent).toBeFalsy(); const emptyContent = fixture.debugElement.query(By.css('.adf-empty-content')); expect(emptyContent.nativeElement).toBeDefined(); }); it('should load spinner and show the content', () => { spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); const appName = new SimpleChange(null, 'FAKE-APP-NAME', true); fixture.detectChanges(); expect(component.isLoading).toBe(true); let loadingContent = fixture.debugElement.query(By.css('mat-progress-spinner')); expect(loadingContent.nativeElement).toBeDefined(); component.ngOnChanges({ appName }); fixture.detectChanges(); expect(component.isLoading).toBe(false); loadingContent = fixture.debugElement.query(By.css('mat-progress-spinner')); expect(loadingContent).toBeFalsy(); const emptyContent = fixture.debugElement.query(By.css('.adf-empty-content')); expect(emptyContent).toBeFalsy(); expect(component.rows.length).toEqual(3); }); it('should the payload contain the appVersion if it is defined', () => { spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); component.appVersion = 1; component.reload(); expect(component.requestNode.appVersion).toEqual('1'); }); it('should the payload contain all the app versions joined by a comma separator', () => { spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); component.appVersion = [1, 2, 3]; component.reload(); expect(component.requestNode.appVersion).toEqual('1,2,3'); }); it('should the payload NOT contain any app version when appVersion does not have a value', () => { spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); component.appVersion = undefined; component.reload(); expect(component.requestNode.appVersion).toEqual(''); }); it('should use the custom schemaColumn from app.config.json', () => { component.presetColumn = 'fakeCustomSchema'; component.ngAfterContentInit(); fixture.detectChanges(); expect(component.columns).toEqual(fakeCustomSchema); }); it('should fetch custom schemaColumn when the input presetColumn is defined', () => { component.presetColumn = 'fakeCustomSchema'; fixture.detectChanges(); expect(component.columns).toBeDefined(); expect(component.columns.length).toEqual(2); }); it('should return the results if an application name is given', (done) => { spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); const appName = new SimpleChange(null, 'FAKE-APP-NAME', true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.rows.length).toEqual(3); expect(component.rows[0].entry['appName']).toBe('easy-peasy-japanesey'); expect(component.rows[0].entry['appVersion']).toBe(1); expect(component.rows[0].entry['id']).toBe('69eddfa7-d781-11e8-ae24-0a58646001fa'); expect(component.rows[0].entry['name']).toEqual('starring'); expect(component.rows[0].entry['processDefinitionId']).toBe('BasicProcess:1:d05062f1-c6fb-11e8-ae24-0a58646001fa'); expect(component.rows[0].entry['processDefinitionKey']).toBe('BasicProcess'); expect(component.rows[0].entry['initiator']).toBe('devopsuser'); expect(component.rows[0].entry['startDate']).toBe(1540381146275); expect(component.rows[0].entry['businessKey']).toBe('MyBusinessKey'); expect(component.rows[0].entry['status']).toBe('RUNNING'); expect(component.rows[0].entry['lastModified']).toBe(1540381146276); expect(component.rows[0].entry['lastModifiedTo']).toBeNull(); expect(component.rows[0].entry['lastModifiedFrom']).toBeNull(); done(); }); component.appName = appName.currentValue; component.ngOnChanges({ 'appName': appName }); fixture.detectChanges(); }); it('should reload tasks when reload() is called', (done) => { component.appName = 'fake'; spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); done(); }); fixture.detectChanges(); component.reload(); }); it('should emit row click event', (done) => { const row = new ObjectDataRow({ id: '999' }); const rowEvent = new DataRowEvent(row, null); component.rowClick.subscribe((taskId) => { expect(taskId).toEqual('999'); expect(component.getCurrentId()).toEqual('999'); done(); }); component.onRowClick(rowEvent); }); describe('component changes', () => { beforeEach(() => { component.rows = fakeProcessCloudList.list.entries; fixture.detectChanges(); }); it('should reload the process list when input parameters changed', () => { const getProcessByRequestSpy = spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); component.appName = 'mock-app-name'; component.status = 'mock-status'; component.initiator = 'mock-initiator'; const appNameChange = new SimpleChange(undefined, 'mock-app-name', true); const statusChange = new SimpleChange(undefined, 'mock-status', true); const initiatorChange = new SimpleChange(undefined, 'mock-initiator', true); component.ngOnChanges({ 'appName': appNameChange, 'assignee': initiatorChange, 'status': statusChange }); fixture.detectChanges(); expect(component.isListEmpty()).toBeFalsy(); expect(getProcessByRequestSpy).toHaveBeenCalled(); }); it('should set formattedSorting if sorting input changes', () => { spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); spyOn(component, 'formatSorting').and.callThrough(); component.appName = 'mock-app-name'; const mockSort = [ new ProcessListCloudSortingModel({ orderBy: 'startDate', direction: 'DESC' }) ]; const sortChange = new SimpleChange(undefined, mockSort, true); component.ngOnChanges({ 'sorting': sortChange }); fixture.detectChanges(); expect(component.formatSorting).toHaveBeenCalledWith(mockSort); expect(component.formattedSorting).toEqual(['startDate', 'desc']); }); it('should reload process list when sorting on a column changes', () => { const getProcessByRequestSpy = spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); component.onSortingChanged(new CustomEvent('sorting-changed', { detail: { key: 'fakeName', direction: 'asc' }, bubbles: true })); fixture.detectChanges(); expect(component.sorting).toEqual([ new ProcessListCloudSortingModel({ orderBy: 'fakeName', direction: 'ASC' }) ]); expect(component.formattedSorting).toEqual(['fakeName', 'asc']); expect(component.isListEmpty()).toBeFalsy(); expect(getProcessByRequestSpy).toHaveBeenCalled(); }); it('should reset pagination when resetPaginationValues is called', async (done) => { spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); const appName = new SimpleChange(null, 'FAKE-APP-NAME', true); component.ngOnChanges({ appName }); fixture.detectChanges(); const size = component.size; const skipCount = component.skipCount; component.pagination.pipe(skip(3)) .subscribe((updatedPagination) => { fixture.detectChanges(); expect(component.size).toBe(size); expect(component.skipCount).toBe(skipCount); expect(updatedPagination.maxItems).toEqual(size); expect(updatedPagination.skipCount).toEqual(skipCount); done(); }); const pagination = { maxItems: 250, skipCount: 200 }; component.updatePagination(pagination); await fixture.whenStable(); component.resetPagination(); }); it('should set pagination and reload when updatePagination is called', (done) => { spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(fakeProcessCloudList)); spyOn(component, 'reload').and.stub(); const appName = new SimpleChange(null, 'FAKE-APP-NAME', true); component.ngOnChanges({ appName }); fixture.detectChanges(); const pagination = { maxItems: 250, skipCount: 200 }; component.pagination.pipe(skip(1)) .subscribe((updatedPagination) => { fixture.detectChanges(); expect(component.size).toBe(pagination.maxItems); expect(component.skipCount).toBe(pagination.skipCount); expect(updatedPagination.maxItems).toEqual(pagination.maxItems); expect(updatedPagination.skipCount).toEqual(pagination.skipCount); done(); }); component.updatePagination(pagination); }); }); describe('Injecting custom colums for tasklist - CustomTaskListComponent', () => { let fixtureCustom: ComponentFixture<CustomTaskListComponent>; let componentCustom: CustomTaskListComponent; setupTestBed({ imports: [ TranslateModule.forRoot(), ProcessServiceCloudTestingModule ], declarations: [CustomTaskListComponent] }); beforeEach(() => { fixtureCustom = TestBed.createComponent(CustomTaskListComponent); fixtureCustom.detectChanges(); componentCustom = fixtureCustom.componentInstance; }); afterEach(() => { fixtureCustom.destroy(); }); it('should fetch custom schemaColumn from html', () => { fixture.detectChanges(); expect(componentCustom.processListCloud.columnList).toBeDefined(); expect(componentCustom.processListCloud.columns[0]['title']).toEqual('ADF_CLOUD_TASK_LIST.PROPERTIES.NAME'); expect(componentCustom.processListCloud.columns[1]['title']).toEqual('ADF_CLOUD_TASK_LIST.PROPERTIES.CREATED'); expect(componentCustom.processListCloud.columns.length).toEqual(3); }); }); describe('Creating an empty custom template - EmptyTemplateComponent', () => { let fixtureEmpty: ComponentFixture<EmptyTemplateComponent>; setupTestBed({ imports: [ TranslateModule.forRoot(), ProcessServiceCloudTestingModule ], declarations: [EmptyTemplateComponent] }); beforeEach(() => { fixtureEmpty = TestBed.createComponent(EmptyTemplateComponent); fixtureEmpty.detectChanges(); }); afterEach(() => { fixtureEmpty.destroy(); }); it('should render the custom template', fakeAsync((done) => { const emptyList = {list: {entries: []}}; spyOn(processListCloudService, 'getProcessByRequest').and.returnValue(of(emptyList)); component.success.subscribe(() => { expect(fixtureEmpty.debugElement.query(By.css('#custom-id'))).not.toBeNull(); expect(fixtureEmpty.debugElement.query(By.css('.adf-empty-content'))).toBeNull(); done(); }); })); }); });
the_stack
namespace App { function decodeWord(s: string): number { return parseInt(s, 36); } function encodeWord(num: number): string { let s = num.toString(36); if (s.length == 2) { return s; } if (s.length == 1) { return "0" + s; } console.error("bad num: %d", num); return "0"; } const gopherHatList = [ "sprites/none.png", "sprites/hat/sailor.png", "sprites/hat/ushanka.png", "sprites/hat/googler.png", "sprites/hat/tophat.png", "sprites/hat/miner.png", "sprites/hat/student.png", "sprites/hat/puffball.png", "sprites/hat/santa.png", "sprites/hat/sherlock.png", "sprites/hat/bow_yellow.png", "sprites/hat/bow_purple.png", "sprites/hat/bow_blue.png", "sprites/hat/headband_purple.png", "sprites/hat/headband_blue.png", ]; const gopherExtrasList = [ "sprites/none.png", "sprites/extras/bowtie.png", "sprites/extras/beard_adamj.png", "sprites/extras/scar_harry.png", "sprites/extras/antennae.png", "sprites/extras/eyeflames.png", ]; const gopherHairList = [ "sprites/none.png", "sprites/hair/dark_edgy.png", "sprites/hair/payot.png", "sprites/hair/short.png", "sprites/hair/whiskers.png", "sprites/hair/whiskers2.png", "sprites/hair/long.png", "sprites/hair/tennis.png", ]; const gopherTeethList = [ "sprites/none.png", "sprites/teeth/classical.png", "sprites/teeth/edgy.png", "sprites/teeth/fangs.png", "sprites/teeth/fragile.png", "sprites/teeth/funky.png", "sprites/teeth/shy.png", "sprites/teeth/soft.png", "sprites/teeth/broken.png", "sprites/teeth/monoteeth.png", "sprites/teeth/vampire.png", ]; const gopherMouthList = [ "sprites/none.png", "sprites/mouth/grin.png", "sprites/mouth/lol.png", "sprites/mouth/shout.png", "sprites/mouth/surprised.png", "sprites/mouth/tongue.png", "sprites/mouth/annoyed.png", "sprites/mouth/smile.png", ]; const gopherColorsList = [ "sprites/torso/normal/0.png", "sprites/torso/normal/5.png", "sprites/torso/normal/10.png", "sprites/torso/normal/15.png", "sprites/torso/normal/40.png", "sprites/torso/normal/75.png", "sprites/torso/normal/80.png", "sprites/torso/normal/85.png", "sprites/torso/normal/90.png", "sprites/torso/normal/95.png", "sprites/torso/normal/100.png", "sprites/torso/normal/105.png", "sprites/torso/normal/110.png", "sprites/torso/normal/115.png", "sprites/torso/normal/125.png", "sprites/torso/normal/145.png", "sprites/torso/normal/150.png", "sprites/torso/normal/155.png", "sprites/torso/normal/170.png", "sprites/torso/normal/180.png", "sprites/torso/normal/195.png", ]; const gopherEarsList = [ "sprites/none.png", "sprites/ears/fancy", "sprites/ears/fluffy", "sprites/ears/foxy", "sprites/ears/normal", "sprites/ears/playful", "sprites/ears/pointy", "sprites/ears/tiny", "sprites/ears/wide", "sprites/ears/wolf", ]; const gopherTorsoList = [ "sprites/none.png", "sprites/torso/cheeky", "sprites/torso/curly", "sprites/torso/normal", "sprites/torso/shaggy", "sprites/torso/wolf", "sprites/torso/barbed", ]; const gopherPoseList = [ "sprites/none.png", "sprites/pose/cowboy.png", "sprites/pose/dunno.png", "sprites/pose/right_holding.png", "sprites/pose/right_holding.mic.png", "sprites/pose/right_holding.white_rose.png", "sprites/pose/right_holding.wrench.png", "sprites/pose/sides.png", "sprites/pose/sign_blank.png", "sprites/pose/sign_persik_happy.png", "sprites/pose/sign_persik_laugh.png", "sprites/pose/sign_persik_thumbsup.png", "sprites/pose/sign_persik_angry.png", "sprites/pose/sign_go.png", "sprites/pose/sign_linux.png", "sprites/pose/thinking.magnifier.png", "sprites/pose/thinking.medic.png", "sprites/pose/thinking.png", "sprites/pose/timid.beads.png", "sprites/pose/timid.camera.png", "sprites/pose/timid.coffee.png", "sprites/pose/timid.money.png", "sprites/pose/timid.png", "sprites/pose/sign_1.png", "sprites/pose/sign_2.png", "sprites/pose/sign_3.png", "sprites/pose/handsup.png", "sprites/pose/shocked.png", "sprites/pose/nunchuck.png", "sprites/pose/water_magic.png", "sprites/pose/fire_magic.png", "sprites/pose/lightning_magic.png", "sprites/pose/snowball.png", "sprites/pose/dance.png", "sprites/pose/thumbs_up1.png", "sprites/pose/thumbs_up2.png", "sprites/pose/sides2.png", "sprites/pose/sides3.png", "sprites/pose/sides4.png", ]; const gopherNoseList = [ "sprites/nose/neat_a.png", "sprites/nose/neat_b.png", "sprites/nose/oval.png", "sprites/nose/round.png", "sprites/nose/small.png", "sprites/nose/tiny.png", "sprites/nose/apple.png", "sprites/nose/flat.png", ]; const gopherEyewearList = [ "sprites/none.png", "sprites/eyewear/censored_black.png", "sprites/eyewear/censored_red.png", "sprites/eyewear/glasses_cool.png", "sprites/eyewear/deal_with_it.png", "sprites/eyewear/glasses_hipster.png", "sprites/eyewear/glasses_glam.png", "sprites/eyewear/glasses_nerd.png", "sprites/eyewear/glasses_square.png", "sprites/eyewear/glasses_adamj.png", "sprites/eyewear/glasses_cyber.png", "sprites/eyewear/protective_goggles.png", "sprites/eyewear/monocle_left.png", "sprites/eyewear/monocle_right.png", "sprites/eyewear/monocle_black.png", ]; const gopherAccessoryList = [ "sprites/none.png", "sprites/accessory/headphones.png", "sprites/accessory/facemask.png", "sprites/accessory/evil_mustache.png", ]; const gopherEyesList = [ "sprites/eyes/alien_center.png", "sprites/eyes/alien_crazy.png", "sprites/eyes/alien_fish.png", "sprites/eyes/angry.png", "sprites/eyes/angry_one.png", "sprites/eyes/confused.png", "sprites/eyes/different.png", "sprites/eyes/different_mirrored.png", "sprites/eyes/different_mirrored_eyebrow.png", "sprites/eyes/distant_normal_left.png", "sprites/eyes/happy.png", "sprites/eyes/happy_as_in_anime.png", "sprites/eyes/killed.png", "sprites/eyes/normal_up.png", "sprites/eyes/normal_up_lashes.png", "sprites/eyes/oval_center.png", "sprites/eyes/oval_center_lashes.png", "sprites/eyes/oval_crazy.png", "sprites/eyes/oval_curious.png", "sprites/eyes/oval_curious_empty.png", "sprites/eyes/oval_down.png", "sprites/eyes/oval_down_lashes.png", "sprites/eyes/rofl.png", "sprites/eyes/sceptical.png", "sprites/eyes/small_center.png", "sprites/eyes/small_center_lashes.png", "sprites/eyes/wink.png", "sprites/eyes/goofy.png", ]; const gopherUndernoseList = [ "sprites/undernose/normal.png", "sprites/undernose/oval.png", "sprites/undernose/rome.png", "sprites/undernose/small.png", "sprites/undernose/gourmet.png", ]; const gopherTattooList = [ "sprites/none.png", "sprites/tattoo/apple.png", "sprites/tattoo/batman.png", "sprites/tattoo/digital_resistance1.png", "sprites/tattoo/digital_resistance2.png", "sprites/tattoo/durov_dog1.png", "sprites/tattoo/durov_dog2.png", "sprites/tattoo/github.png", "sprites/tattoo/invader.png", "sprites/tattoo/sammy.png", "sprites/tattoo/sekai.png", "sprites/tattoo/slowpoke.png", "sprites/tattoo/ubuntu.png", "sprites/tattoo/usb.png", "sprites/tattoo/vk.png", "sprites/tattoo/x.png", "sprites/tattoo/deusex_logo.png", "sprites/tattoo/gengar.png", "sprites/tattoo/hello_kitty.png", "sprites/tattoo/sonic.png", "sprites/tattoo/vaultboy.png", "sprites/tattoo/reddit.png", "sprites/tattoo/virus1.png", "sprites/tattoo/virus2.png", ]; const optionTabList = [ { key: "colorOptionTab", options: gopherColorsList, label: "Body color", }, { key: "eyesOptionTab", options: gopherEyesList, label: "Eyes", }, { key: "poseOptionTab", options: gopherPoseList, label: "Pose", }, { key: "torsoOptionTab", options: gopherTorsoList, label: "Torso", }, { key: "earsOptionTab", options: gopherEarsList, label: "Ears", }, { key: "teethOptionTab", options: gopherTeethList, label: "Teeth", }, { key: "mouthOptionTab", options: gopherMouthList, label: "Mouth", }, { key: "undernoseOptionTab", options: gopherUndernoseList, label: "Undernose", }, { key: "noseOptionTab", options: gopherNoseList, label: "Nose", }, { key: "eyewearOptionTab", options: gopherEyewearList, label: "Eyewear", }, { key: "accessoryOptionTab", options: gopherAccessoryList, label: "Accessory", }, { key: "tattooOptionTab", options: gopherTattooList, label: "Tattoo", }, { key: "extrasOptionTab", options: gopherExtrasList, label: "Extras", }, { key: "hairOptionTab", options: gopherHairList, label: "Hair", }, { key: "hatOptionTab", options: gopherHatList, label: "Hat", }, ]; function objectListFmt(list) { return { enc: function(x) { for (let i in list) { if (list[i].key == x.key) { return encodeWord(+i); } } console.error("%s not found", x.key); return encodeWord(0); }, dec: function(s) { return list[decodeWord(s)]; }, }; } function stringListFmt(list) { return { enc: function(s) { return encodeWord(list.indexOf(s)); }, dec: function(s) { return list[decodeWord(s)]; }, }; } let optsFmt = { // We have 1296 values. // It's safe to use up to 10 bits (2^10). // // Bits: // 0-1 - isLegacy // 2-9 - reserved enc: function(opts) { let bits = 0; if (opts.isLegacy) { bits = bits | (1 << 0); } return encodeWord(bits); }, dec: function(s) { let opts = {isLegacy: false}; let bits = decodeWord(s); opts.isLegacy = (bits & (1 << 0)) != 0; return opts; }, }; let app = { query: new URLSearchParams(window.location.search), legacyStateSchemeChunks: 13, state: { tabSelection: optionTabList, // TODO(quasilyte): move outside of the "state"? // Defaults. tab: optionTabList[0], colorOptionTab: "sprites/torso/normal/100.png", eyesOptionTab: "sprites/eyes/normal_up.png", poseOptionTab: "sprites/pose/dunno.png", torsoOptionTab: "sprites/torso/normal", earsOptionTab: "sprites/ears/normal", teethOptionTab: "sprites/teeth/classical.png", mouthOptionTab: "sprites/none.png", undernoseOptionTab: "sprites/undernose/normal.png", noseOptionTab: "sprites/nose/oval.png", eyewearOptionTab: "sprites/none.png", accessoryOptionTab: "sprites/none.png", tattooOptionTab: "sprites/none.png", extrasOptionTab: "sprites/none.png", opts: { // Whether URL/state was converted from the pre base-36 form. isLegacy: false, }, hairOptionTab: "sprites/none.png", hatOptionTab: "sprites/none.png", }, stateScheme: [ {name: "tab", fmt: objectListFmt(optionTabList)}, {name: "colorOptionTab", fmt: stringListFmt(gopherColorsList)}, {name: "eyesOptionTab", fmt: stringListFmt(gopherEyesList)}, {name: "poseOptionTab", fmt: stringListFmt(gopherPoseList)}, {name: "torsoOptionTab", fmt: stringListFmt(gopherTorsoList)}, {name: "earsOptionTab", fmt: stringListFmt(gopherEarsList)}, {name: "teethOptionTab", fmt: stringListFmt(gopherTeethList)}, {name: "mouthOptionTab", fmt: stringListFmt(gopherMouthList)}, {name: "undernoseOptionTab", fmt: stringListFmt(gopherUndernoseList)}, {name: "noseOptionTab", fmt: stringListFmt(gopherNoseList)}, {name: "eyewearOptionTab", fmt: stringListFmt(gopherEyewearList)}, {name: "accessoryOptionTab", fmt: stringListFmt(gopherAccessoryList)}, {name: "tattooOptionTab", fmt: stringListFmt(gopherTattooList)}, {name: "extrasOptionTab", fmt: stringListFmt(gopherExtrasList)}, {name: "opts", fmt: optsFmt}, {name: "hairOptionTab", fmt: stringListFmt(gopherHairList)}, {name: "hatOptionTab", fmt: stringListFmt(gopherHatList)}, ], }; function stateString(delta): string { delta = delta || {}; let parts = []; for (let i in app.stateScheme) { let desc = app.stateScheme[i]; let val = delta[desc.name] || app.state[desc.name]; parts.push(desc.fmt.enc(val)); } return parts.join(""); } // Try loading state from the state argument or, // if not explicitely passed, "state" GET param. function loadState(state: string = "") { state = state || app.query.get("state"); if (!state) { return; } let parts = state.match(/.{2}/g); if (parts.length < app.stateScheme.length) { console.warn("legacy state param: have %d chunks, want %d", parts.length, app.stateScheme.length); } else if (parts.length > app.stateScheme.length) { console.error("corrupted state param: have %d chunks, want %d", parts.length, app.stateScheme.length); return; } // Old permalinks detection. if (parts.length == app.legacyStateSchemeChunks) { app.state.opts.isLegacy = true; // Hex radix was used before. // Fix old permalinks by re-encoding base-16 values // into base-36 values. for (let i in parts) { let hexValue = parseInt(parts[i], 16); parts[i] = hexValue.toString(36); } } // This could initialize state only partially in case of // legacy state strings, where some fields are missing. for (let i in parts) { let desc = app.stateScheme[i]; app.state[desc.name] = desc.fmt.dec(parts[i]); } } function initOptionTabSelector() { let tabInfo = app.state.tab; let tabSelector = document.getElementById("tab-selector"); let parts = []; let tabSelection = app.state.tabSelection; for (let i in tabSelection) { let label = tabSelection[i].label; if (tabInfo == tabSelection[i]) { parts.push(`<tr><td><button class='tab-selected' onclick='App.changeTab(${i})'>${label}</button></td></tr>`); } else { parts.push(`<tr><td><button onclick='App.changeTab(${i})'>${label}</button></td></tr>`); } } tabSelector.innerHTML = parts.join(""); } function initOptionTab() { let tabInfo = app.state.tab; let optionTab = document.getElementById(tabInfo.key); optionTab.style.display = "block"; let parts = []; let tabKey = app.state.tab.key; for (let i in tabInfo.options) { let imgURL = spriteURL(tabInfo.options[i]); let delta = {}; delta[tabKey] = tabInfo.options[i]; let updatedState = stateString(delta); if (app.state[tabKey] == tabInfo.options[i]) { parts.push(`<button class='option-link' onclick='App.updateWithoutReload("${updatedState}")'><img class='option-selected' src='${imgURL}'></button>`); } else { parts.push(`<button class='option-link' onclick='App.updateWithoutReload("${updatedState}")'><img src='${imgURL}'></button>`); } } optionTab.innerHTML = parts.join(""); } function spriteURL(url: string) { if (url.endsWith(".png")) { return url; } let parts = app.state.colorOptionTab.split("/"); let suffix = parts[parts.length-1]; return url + "/" + suffix; } function drawImages(images) { let canvas = <HTMLCanvasElement> document.getElementById("gopher"); let ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); for (let i in images) { let img = images[i]; ctx.drawImage(img, 0, 0); } } function renderGopher() { let drawOrder = [ "earsOptionTab", "torsoOptionTab", "hairOptionTab", "eyesOptionTab", "extrasOptionTab", "mouthOptionTab", "teethOptionTab", "undernoseOptionTab", "noseOptionTab", "tattooOptionTab", "hatOptionTab", "accessoryOptionTab", "eyewearOptionTab", "poseOptionTab", ]; let images = []; let toLoad = drawOrder.length; // For sync. for (let i in drawOrder) { let tabKey = drawOrder[i]; let imgURL = spriteURL(app.state[tabKey]); if (!imgURL) { toLoad--; continue; } let img = new Image(); images.push(img); // Order is preserved. img.src = imgURL; img.onload = function() { toLoad--; if (toLoad == 0) { drawImages(images); } }; } } function initDownload() { let link = <HTMLAnchorElement> document.getElementById("download"); link.onclick = function() { let canvas = <HTMLCanvasElement> document.getElementById("gopher"); link.href = canvas.toDataURL("image/png;base64"); }; } function copyToClipboard(text: string) { let el = <HTMLTextAreaElement> document.createElement("textarea"); // Temp container el.value = text; el.setAttribute("readonly", ""); el.style.position = "absolute"; el.style.left = "-9999px"; document.body.appendChild(el); el.select(); try { let ok = document.execCommand("copy"); console.debug("copy to clipboard:", ok); } catch (e) { console.error("clipboard insertion failed", e); } document.body.removeChild(el); } function initShareButton() { let share = document.getElementById("share"); share.onclick = function() { let url = "https://quasilyte.dev/gopherkon/?state=" + stateString({}); copyToClipboard(url); }; } function getOptionsList(key: string) { for (let tab of app.state.tabSelection) { if (tab.key == key) { return tab; } } return null; } function rand(min: number, max: number): number { return Math.floor(Math.random() * (max - min)) + min; } function randBool(v = 0.5): boolean { return Math.random() >= v; } function randomizedState(): string { // preferZero enumerate tabs that should have at least 50% // to have zero value against all other options. let preferZero = { "accessoryOptionTab": 0.15, "eyewearOptionTab": 0.5, "extrasOptionTab": 0.25, "hairOptionTab": 0.25, "tattooOptionTab": 0.5, "hatOptionTab": 0.4, }; // nonZero enumerates tabs that should not have 0 index. let nonZero = new Set([ "poseOptionTab", "torsoOptionTab", "earsOptionTab", "teethOptionTab", ]); let delta = {}; for (let i in app.stateScheme) { let desc = app.stateScheme[i]; let tab = getOptionsList(desc.name); if (tab === null) { continue; } let minIndex = nonZero.has(desc.name) ? 1 : 0; let index = rand(minIndex, tab.options.length); if (preferZero[desc.name] && randBool(preferZero[desc.name])) { index = 0; } let value = desc.fmt.dec(encodeWord(index)); delta[desc.name] = value; } return stateString(delta); } function initShuffleButton() { let shuffle = <HTMLAnchorElement> document.getElementById("shuffle"); shuffle.href = "?state=" + randomizedState(); } export function changeTab(tabIndex) { let tabSelection = app.state.tabSelection; let href = "?state=" + stateString({tab: tabSelection[tabIndex]}); window.location.href = href; } export function updateWithoutReload(state) { loadState(state); initOptionTab(); renderGopher(); // Rewrite URL query, if possible. if (window.history.replaceState) { let url = window.location.protocol + "//" + window.location.host + window.location.pathname; url = url + "?state=" + state; window.history.replaceState({path: url}, "", url); } } export function main() { loadState(); console.debug("decoded state:", app.state); console.debug("state string:", stateString({})); initOptionTabSelector(); initOptionTab(); renderGopher(); initDownload(); initShareButton(); initShuffleButton(); } } window.onload = function() { App.main(); };
the_stack
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, Optional } from '@angular/core'; import { APIClientInterface } from './api-client.interface'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { USE_DOMAIN, USE_HTTP_OPTIONS, APIClient } from './api-client.service'; import { DefaultHttpOptions, HttpOptions } from './types'; import * as models from './models'; import * as guards from './guards'; @Injectable() export class GuardedAPIClient extends APIClient implements APIClientInterface { constructor( readonly httpClient: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { super(httpClient, domain, options); } /** * Find pet by ID * Returns a single pet * Response generated for [ 200 ] HTTP response code. */ getPetById( args: Exclude<APIClientInterface['getPetByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pet>; getPetById( args: Exclude<APIClientInterface['getPetByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pet>>; getPetById( args: Exclude<APIClientInterface['getPetByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pet>>; getPetById( args: Exclude<APIClientInterface['getPetByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Pet | HttpResponse<models.Pet> | HttpEvent<models.Pet>> { return super.getPetById(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isPet(res) || console.error(`TypeGuard for response 'models.Pet' caught inconsistency.`, res))); } /** * Updates a pet in the store with form data * Response generated for [ default ] HTTP response code. */ updatePetWithForm( args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; updatePetWithForm( args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; updatePetWithForm( args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; updatePetWithForm( args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.updatePetWithForm(args, requestHttpOptions, observe); } /** * Deletes a pet * Response generated for [ default ] HTTP response code. */ deletePet( args: Exclude<APIClientInterface['deletePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deletePet( args: Exclude<APIClientInterface['deletePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deletePet( args: Exclude<APIClientInterface['deletePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deletePet( args: Exclude<APIClientInterface['deletePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.deletePet(args, requestHttpOptions, observe); } /** * uploads an image * Response generated for [ 200 ] HTTP response code. */ uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ApiResponse>; uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ApiResponse>>; uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ApiResponse>>; uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ApiResponse | HttpResponse<models.ApiResponse> | HttpEvent<models.ApiResponse>> { return super.uploadFile(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isApiResponse(res) || console.error(`TypeGuard for response 'models.ApiResponse' caught inconsistency.`, res))); } /** * Add a new pet to the store * Response generated for [ default ] HTTP response code. */ addPet( args: Exclude<APIClientInterface['addPetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; addPet( args: Exclude<APIClientInterface['addPetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; addPet( args: Exclude<APIClientInterface['addPetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; addPet( args: Exclude<APIClientInterface['addPetParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.addPet(args, requestHttpOptions, observe); } /** * Update an existing pet * Response generated for [ default ] HTTP response code. */ updatePet( args: Exclude<APIClientInterface['updatePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; updatePet( args: Exclude<APIClientInterface['updatePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; updatePet( args: Exclude<APIClientInterface['updatePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; updatePet( args: Exclude<APIClientInterface['updatePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.updatePet(args, requestHttpOptions, observe); } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * Response generated for [ 200 ] HTTP response code. */ findPetsByStatus( args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pet[]>; findPetsByStatus( args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pet[]>>; findPetsByStatus( args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pet[]>>; findPetsByStatus( args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Pet[] | HttpResponse<models.Pet[]> | HttpEvent<models.Pet[]>> { return super.findPetsByStatus(args, requestHttpOptions, observe) .pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isPet(item)) ) || console.error(`TypeGuard for response 'models.Pet[]' caught inconsistency.`, res))); } /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @deprecated this method has been deprecated and may be removed in future. * Response generated for [ 200 ] HTTP response code. */ findPetsByTags( args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pet[]>; findPetsByTags( args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pet[]>>; findPetsByTags( args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pet[]>>; findPetsByTags( args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Pet[] | HttpResponse<models.Pet[]> | HttpEvent<models.Pet[]>> { return super.findPetsByTags(args, requestHttpOptions, observe) .pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isPet(item)) ) || console.error(`TypeGuard for response 'models.Pet[]' caught inconsistency.`, res))); } /** * Returns pet inventories by status * Returns a map of status codes to quantities * Response generated for [ 200 ] HTTP response code. */ getInventory( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<{ [key: string]: number }>; getInventory( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<{ [key: string]: number }>>; getInventory( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<{ [key: string]: number }>>; getInventory( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<{ [key: string]: number } | HttpResponse<{ [key: string]: number }> | HttpEvent<{ [key: string]: number }>> { return super.getInventory(requestHttpOptions, observe) .pipe(tap((res: any) => Object.values(res).every((value: any) => typeof value === 'number') || console.error(`TypeGuard for response '{ [key: string]: number }' caught inconsistency.`, res))); } /** * Find purchase order by ID * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions * Response generated for [ 200 ] HTTP response code. */ getOrderById( args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Order>; getOrderById( args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Order>>; getOrderById( args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Order>>; getOrderById( args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Order | HttpResponse<models.Order> | HttpEvent<models.Order>> { return super.getOrderById(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isOrder(res) || console.error(`TypeGuard for response 'models.Order' caught inconsistency.`, res))); } /** * Delete purchase order by ID * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors * Response generated for [ default ] HTTP response code. */ deleteOrder( args: Exclude<APIClientInterface['deleteOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteOrder( args: Exclude<APIClientInterface['deleteOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteOrder( args: Exclude<APIClientInterface['deleteOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteOrder( args: Exclude<APIClientInterface['deleteOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.deleteOrder(args, requestHttpOptions, observe); } /** * Place an order for a pet * Response generated for [ 200 ] HTTP response code. */ placeOrder( args: Exclude<APIClientInterface['placeOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Order>; placeOrder( args: Exclude<APIClientInterface['placeOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Order>>; placeOrder( args: Exclude<APIClientInterface['placeOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Order>>; placeOrder( args: Exclude<APIClientInterface['placeOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Order | HttpResponse<models.Order> | HttpEvent<models.Order>> { return super.placeOrder(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isOrder(res) || console.error(`TypeGuard for response 'models.Order' caught inconsistency.`, res))); } /** * Get user by user name * Response generated for [ 200 ] HTTP response code. */ getUserByName( args: Exclude<APIClientInterface['getUserByNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.User>; getUserByName( args: Exclude<APIClientInterface['getUserByNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.User>>; getUserByName( args: Exclude<APIClientInterface['getUserByNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.User>>; getUserByName( args: Exclude<APIClientInterface['getUserByNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.User | HttpResponse<models.User> | HttpEvent<models.User>> { return super.getUserByName(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isUser(res) || console.error(`TypeGuard for response 'models.User' caught inconsistency.`, res))); } /** * Updated user * This can only be done by the logged in user. * Response generated for [ default ] HTTP response code. */ updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.updateUser(args, requestHttpOptions, observe); } /** * Delete user * This can only be done by the logged in user. * Response generated for [ default ] HTTP response code. */ deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.deleteUser(args, requestHttpOptions, observe); } /** * Logs user into the system * Response generated for [ 200 ] HTTP response code. */ loginUser( args: Exclude<APIClientInterface['loginUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<string>; loginUser( args: Exclude<APIClientInterface['loginUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<string>>; loginUser( args: Exclude<APIClientInterface['loginUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<string>>; loginUser( args: Exclude<APIClientInterface['loginUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<string | HttpResponse<string> | HttpEvent<string>> { return super.loginUser(args, requestHttpOptions, observe) .pipe(tap((res: any) => typeof res === 'string' || console.error(`TypeGuard for response 'string' caught inconsistency.`, res))); } /** * Logs out current logged in user session * Response generated for [ default ] HTTP response code. */ logoutUser( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; logoutUser( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; logoutUser( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; logoutUser( requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.logoutUser(requestHttpOptions, observe); } /** * Create user * This can only be done by the logged in user. * Response generated for [ default ] HTTP response code. */ createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.createUser(args, requestHttpOptions, observe); } /** * Creates list of users with given input array * Response generated for [ default ] HTTP response code. */ createUsersWithArrayInput( args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; createUsersWithArrayInput( args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; createUsersWithArrayInput( args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; createUsersWithArrayInput( args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.createUsersWithArrayInput(args, requestHttpOptions, observe); } /** * Creates list of users with given input array * Response generated for [ default ] HTTP response code. */ createUsersWithListInput( args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; createUsersWithListInput( args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; createUsersWithListInput( args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; createUsersWithListInput( args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { return super.createUsersWithListInput(args, requestHttpOptions, observe); } }
the_stack